blob: df353d55e83d9201924260251258225ca9fc0062 [file] [log] [blame]
bellardfc01f7e2003-06-30 10:03:06 +00001/*
2 * QEMU System Emulator block driver
ths5fafdf22007-09-16 21:08:06 +00003 *
bellardfc01f7e2003-06-30 10:03:06 +00004 * Copyright (c) 2003 Fabrice Bellard
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03005 * Copyright (c) 2020 Virtuozzo International GmbH.
ths5fafdf22007-09-16 21:08:06 +00006 *
bellardfc01f7e2003-06-30 10:03:06 +00007 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
Markus Armbrustere688df62018-02-01 12:18:31 +010025
Peter Maydelld38ea872016-01-29 17:50:05 +000026#include "qemu/osdep.h"
Daniel P. Berrange0ab8ed12017-01-25 16:14:15 +000027#include "block/trace.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010028#include "block/block_int.h"
29#include "block/blockjob.h"
Max Reitz0c9b70d2020-10-27 20:05:42 +010030#include "block/fuse.h"
Kevin Wolfcd7fca92016-07-06 11:22:39 +020031#include "block/nbd.h"
Max Reitz609f45e2018-06-14 21:14:28 +020032#include "block/qdict.h"
Markus Armbrusterd49b6832015-03-17 18:29:20 +010033#include "qemu/error-report.h"
Marc-André Lureau5e5733e2019-08-29 22:34:43 +040034#include "block/module_block.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020035#include "qemu/main-loop.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010036#include "qemu/module.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010037#include "qapi/error.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010038#include "qapi/qmp/qdict.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010039#include "qapi/qmp/qjson.h"
Max Reitze59a0cf2018-02-24 16:40:32 +010040#include "qapi/qmp/qnull.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010041#include "qapi/qmp/qstring.h"
Kevin Wolfe1d74bc2018-01-10 15:52:33 +010042#include "qapi/qobject-output-visitor.h"
43#include "qapi/qapi-visit-block-core.h"
Markus Armbrusterbfb197e2014-10-07 13:59:11 +020044#include "sysemu/block-backend.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010045#include "qemu/notify.h"
Markus Armbruster922a01a2018-02-01 12:18:46 +010046#include "qemu/option.h"
Daniel P. Berrange10817bf2015-09-01 14:48:02 +010047#include "qemu/coroutine.h"
Benoît Canetc13163f2014-01-23 21:31:34 +010048#include "block/qapi.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010049#include "qemu/timer.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020050#include "qemu/cutils.h"
51#include "qemu/id.h"
Hanna Reitz0bc329f2021-08-12 10:41:44 +020052#include "qemu/range.h"
53#include "qemu/rcu.h"
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +030054#include "block/coroutines.h"
bellardfc01f7e2003-06-30 10:03:06 +000055
Juan Quintela71e72a12009-07-27 16:12:56 +020056#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000057#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000058#include <sys/queue.h>
Joelle van Dynefeccdce2021-03-15 11:03:39 -070059#if defined(HAVE_SYS_DISK_H)
bellard7674e7b2005-04-26 21:59:26 +000060#include <sys/disk.h>
61#endif
blueswir1c5e97232009-03-07 20:06:23 +000062#endif
bellard7674e7b2005-04-26 21:59:26 +000063
aliguori49dc7682009-03-08 16:26:59 +000064#ifdef _WIN32
65#include <windows.h>
66#endif
67
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010068#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
69
Benoît Canetdc364f42014-01-23 21:31:32 +010070static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
71 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
72
Max Reitz2c1d04e2016-01-29 16:36:11 +010073static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
74 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
75
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010076static QLIST_HEAD(, BlockDriver) bdrv_drivers =
77 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000078
Max Reitz5b363932016-05-17 16:41:31 +020079static BlockDriverState *bdrv_open_inherit(const char *filename,
80 const char *reference,
81 QDict *options, int flags,
82 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +020083 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +020084 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +020085 Error **errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +020086
Kevin Wolfbfb8aa62021-10-18 15:47:14 +020087static bool bdrv_recurse_has_child(BlockDriverState *bs,
88 BlockDriverState *child);
89
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +010090static void bdrv_child_free(BdrvChild *child);
Hanna Reitzbe64bbb2021-11-15 15:54:01 +010091static void bdrv_replace_child_noperm(BdrvChild **child,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +010092 BlockDriverState *new_bs,
93 bool free_empty_child);
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +030094static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
95 BdrvChild *child,
96 Transaction *tran);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +030097static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
98 Transaction *tran);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +030099
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +0300100static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
101 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +0300102 Transaction *change_child_tran, Error **errp);
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +0300103static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
104static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
105
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -0500106static bool bdrv_backing_overridden(BlockDriverState *bs);
107
Markus Armbrustereb852012009-10-27 18:41:44 +0100108/* If non-zero, use only whitelisted block drivers */
109static int use_bdrv_whitelist;
110
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000111#ifdef _WIN32
112static int is_windows_drive_prefix(const char *filename)
113{
114 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
115 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
116 filename[1] == ':');
117}
118
119int is_windows_drive(const char *filename)
120{
121 if (is_windows_drive_prefix(filename) &&
122 filename[2] == '\0')
123 return 1;
124 if (strstart(filename, "\\\\.\\", NULL) ||
125 strstart(filename, "//./", NULL))
126 return 1;
127 return 0;
128}
129#endif
130
Kevin Wolf339064d2013-11-28 10:23:32 +0100131size_t bdrv_opt_mem_align(BlockDriverState *bs)
132{
133 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300134 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800135 return MAX(4096, qemu_real_host_page_size);
Kevin Wolf339064d2013-11-28 10:23:32 +0100136 }
137
138 return bs->bl.opt_mem_alignment;
139}
140
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300141size_t bdrv_min_mem_align(BlockDriverState *bs)
142{
143 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300144 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800145 return MAX(4096, qemu_real_host_page_size);
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300146 }
147
148 return bs->bl.min_mem_alignment;
149}
150
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000151/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100152int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000153{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200154 const char *p;
155
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000156#ifdef _WIN32
157 if (is_windows_drive(path) ||
158 is_windows_drive_prefix(path)) {
159 return 0;
160 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200161 p = path + strcspn(path, ":/\\");
162#else
163 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000164#endif
165
Paolo Bonzini947995c2012-05-08 16:51:48 +0200166 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000167}
168
bellard83f64092006-08-01 16:21:11 +0000169int path_is_absolute(const char *path)
170{
bellard21664422007-01-07 18:22:37 +0000171#ifdef _WIN32
172 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200173 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000174 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200175 }
176 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000177#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200178 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000179#endif
bellard83f64092006-08-01 16:21:11 +0000180}
181
Max Reitz009b03a2019-02-01 20:29:13 +0100182/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000183 path to it by considering it is relative to base_path. URL are
184 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100185char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000186{
Max Reitz009b03a2019-02-01 20:29:13 +0100187 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000188 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100189 char *result;
bellard83f64092006-08-01 16:21:11 +0000190 int len;
191
bellard83f64092006-08-01 16:21:11 +0000192 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100193 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000194 }
Max Reitz009b03a2019-02-01 20:29:13 +0100195
196 if (path_has_protocol(base_path)) {
197 protocol_stripped = strchr(base_path, ':');
198 if (protocol_stripped) {
199 protocol_stripped++;
200 }
201 }
202 p = protocol_stripped ?: base_path;
203
204 p1 = strrchr(base_path, '/');
205#ifdef _WIN32
206 {
207 const char *p2;
208 p2 = strrchr(base_path, '\\');
209 if (!p1 || p2 > p1) {
210 p1 = p2;
211 }
212 }
213#endif
214 if (p1) {
215 p1++;
216 } else {
217 p1 = base_path;
218 }
219 if (p1 > p) {
220 p = p1;
221 }
222 len = p - base_path;
223
224 result = g_malloc(len + strlen(filename) + 1);
225 memcpy(result, base_path, len);
226 strcpy(result + len, filename);
227
228 return result;
229}
230
Max Reitz03c320d2017-05-22 21:52:16 +0200231/*
232 * Helper function for bdrv_parse_filename() implementations to remove optional
233 * protocol prefixes (especially "file:") from a filename and for putting the
234 * stripped filename into the options QDict if there is such a prefix.
235 */
236void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
237 QDict *options)
238{
239 if (strstart(filename, prefix, &filename)) {
240 /* Stripping the explicit protocol prefix may result in a protocol
241 * prefix being (wrongly) detected (if the filename contains a colon) */
242 if (path_has_protocol(filename)) {
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100243 GString *fat_filename;
Max Reitz03c320d2017-05-22 21:52:16 +0200244
245 /* This means there is some colon before the first slash; therefore,
246 * this cannot be an absolute path */
247 assert(!path_is_absolute(filename));
248
249 /* And we can thus fix the protocol detection issue by prefixing it
250 * by "./" */
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100251 fat_filename = g_string_new("./");
252 g_string_append(fat_filename, filename);
Max Reitz03c320d2017-05-22 21:52:16 +0200253
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100254 assert(!path_has_protocol(fat_filename->str));
Max Reitz03c320d2017-05-22 21:52:16 +0200255
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100256 qdict_put(options, "filename",
257 qstring_from_gstring(fat_filename));
Max Reitz03c320d2017-05-22 21:52:16 +0200258 } else {
259 /* If no protocol prefix was detected, we can use the shortened
260 * filename as-is */
261 qdict_put_str(options, "filename", filename);
262 }
263 }
264}
265
266
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200267/* Returns whether the image file is opened as read-only. Note that this can
268 * return false and writing to the image file is still not possible because the
269 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400270bool bdrv_is_read_only(BlockDriverState *bs)
271{
Vladimir Sementsov-Ogievskiy975da072021-05-27 18:40:55 +0300272 return !(bs->open_flags & BDRV_O_RDWR);
Jeff Cody93ed5242017-04-07 16:55:28 -0400273}
274
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200275int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
276 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400277{
Jeff Codye2b82472017-04-07 16:55:26 -0400278 /* Do not set read_only if copy_on_read is enabled */
279 if (bs->copy_on_read && read_only) {
280 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
281 bdrv_get_device_or_node_name(bs));
282 return -EINVAL;
283 }
284
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400285 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200286 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
287 !ignore_allow_rdw)
288 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400289 error_setg(errp, "Node '%s' is read only",
290 bdrv_get_device_or_node_name(bs));
291 return -EPERM;
292 }
293
Jeff Cody45803a02017-04-07 16:55:29 -0400294 return 0;
295}
296
Kevin Wolfeaa24102018-10-12 11:27:41 +0200297/*
298 * Called by a driver that can only provide a read-only image.
299 *
300 * Returns 0 if the node is already read-only or it could switch the node to
301 * read-only because BDRV_O_AUTO_RDONLY is set.
302 *
303 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
304 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
305 * is not NULL, it is used as the error message for the Error object.
306 */
307int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
308 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400309{
310 int ret = 0;
311
Kevin Wolfeaa24102018-10-12 11:27:41 +0200312 if (!(bs->open_flags & BDRV_O_RDWR)) {
313 return 0;
314 }
315 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
316 goto fail;
317 }
318
319 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400320 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200321 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400322 }
323
Kevin Wolfeaa24102018-10-12 11:27:41 +0200324 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200325
Jeff Codye2b82472017-04-07 16:55:26 -0400326 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200327
328fail:
329 error_setg(errp, "%s", errmsg ?: "Image is read-only");
330 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400331}
332
Max Reitz645ae7d2019-02-01 20:29:14 +0100333/*
334 * If @backing is empty, this function returns NULL without setting
335 * @errp. In all other cases, NULL will only be returned with @errp
336 * set.
337 *
338 * Therefore, a return value of NULL without @errp set means that
339 * there is no backing file; if @errp is set, there is one but its
340 * absolute filename cannot be generated.
341 */
342char *bdrv_get_full_backing_filename_from_filename(const char *backed,
343 const char *backing,
344 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100345{
Max Reitz645ae7d2019-02-01 20:29:14 +0100346 if (backing[0] == '\0') {
347 return NULL;
348 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
349 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100350 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
351 error_setg(errp, "Cannot use relative backing file names for '%s'",
352 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100353 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100354 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100355 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100356 }
357}
358
Max Reitz9f4793d2019-02-01 20:29:16 +0100359/*
360 * If @filename is empty or NULL, this function returns NULL without
361 * setting @errp. In all other cases, NULL will only be returned with
362 * @errp set.
363 */
364static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
365 const char *filename, Error **errp)
366{
Max Reitz8df68612019-02-01 20:29:23 +0100367 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100368
Max Reitz8df68612019-02-01 20:29:23 +0100369 if (!filename || filename[0] == '\0') {
370 return NULL;
371 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
372 return g_strdup(filename);
373 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100374
Max Reitz8df68612019-02-01 20:29:23 +0100375 dir = bdrv_dirname(relative_to, errp);
376 if (!dir) {
377 return NULL;
378 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100379
Max Reitz8df68612019-02-01 20:29:23 +0100380 full_name = g_strconcat(dir, filename, NULL);
381 g_free(dir);
382 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100383}
384
Max Reitz6b6833c2019-02-01 20:29:15 +0100385char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200386{
Max Reitz9f4793d2019-02-01 20:29:16 +0100387 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200388}
389
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100390void bdrv_register(BlockDriver *bdrv)
391{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100392 assert(bdrv->format_name);
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100393 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000394}
bellardb3380822004-03-14 21:38:54 +0000395
Markus Armbrustere4e99862014-10-07 13:59:03 +0200396BlockDriverState *bdrv_new(void)
397{
398 BlockDriverState *bs;
399 int i;
400
Markus Armbruster5839e532014-08-19 10:31:08 +0200401 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800402 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800403 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
404 QLIST_INIT(&bs->op_blockers[i]);
405 }
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200406 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200407 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800408 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200409 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200410
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300411 qemu_co_queue_init(&bs->flush_queue);
412
Hanna Reitz0bc329f2021-08-12 10:41:44 +0200413 qemu_co_mutex_init(&bs->bsc_modify_lock);
414 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
415
Kevin Wolf0f122642018-03-28 18:29:18 +0200416 for (i = 0; i < bdrv_drain_all_count; i++) {
417 bdrv_drained_begin(bs);
418 }
419
Max Reitz2c1d04e2016-01-29 16:36:11 +0100420 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
421
bellardb3380822004-03-14 21:38:54 +0000422 return bs;
423}
424
Marc Mari88d88792016-08-12 09:27:03 -0400425static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000426{
427 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400428
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100429 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
430 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000431 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100432 }
bellardea2384d2004-08-01 21:59:26 +0000433 }
Marc Mari88d88792016-08-12 09:27:03 -0400434
bellardea2384d2004-08-01 21:59:26 +0000435 return NULL;
436}
437
Marc Mari88d88792016-08-12 09:27:03 -0400438BlockDriver *bdrv_find_format(const char *format_name)
439{
440 BlockDriver *drv1;
441 int i;
442
443 drv1 = bdrv_do_find_format(format_name);
444 if (drv1) {
445 return drv1;
446 }
447
448 /* The driver isn't registered, maybe we need to load a module */
449 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
450 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
451 block_module_load_one(block_driver_modules[i].library_name);
452 break;
453 }
454 }
455
456 return bdrv_do_find_format(format_name);
457}
458
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300459static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100460{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800461 static const char *whitelist_rw[] = {
462 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200463 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800464 };
465 static const char *whitelist_ro[] = {
466 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200467 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100468 };
469 const char **p;
470
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800471 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100472 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800473 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100474
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800475 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300476 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100477 return 1;
478 }
479 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800480 if (read_only) {
481 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300482 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800483 return 1;
484 }
485 }
486 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100487 return 0;
488}
489
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300490int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
491{
492 return bdrv_format_is_whitelisted(drv->format_name, read_only);
493}
494
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000495bool bdrv_uses_whitelist(void)
496{
497 return use_bdrv_whitelist;
498}
499
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800500typedef struct CreateCo {
501 BlockDriver *drv;
502 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800503 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800504 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200505 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800506} CreateCo;
507
508static void coroutine_fn bdrv_create_co_entry(void *opaque)
509{
Max Reitzcc84d902013-09-06 17:14:26 +0200510 Error *local_err = NULL;
511 int ret;
512
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800513 CreateCo *cco = opaque;
514 assert(cco->drv);
515
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200516 ret = cco->drv->bdrv_co_create_opts(cco->drv,
517 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300518 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200519 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800520}
521
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200522int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800523 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000524{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800525 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200526
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800527 Coroutine *co;
528 CreateCo cco = {
529 .drv = drv,
530 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800531 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800532 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200533 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800534 };
535
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100536 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200537 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300538 ret = -ENOTSUP;
539 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800540 }
541
542 if (qemu_in_coroutine()) {
543 /* Fast-path if already in coroutine context */
544 bdrv_create_co_entry(&cco);
545 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200546 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
547 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800548 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200549 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800550 }
551 }
552
553 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200554 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100555 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200556 error_propagate(errp, cco.err);
557 } else {
558 error_setg_errno(errp, -ret, "Could not create image");
559 }
560 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800561
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300562out:
563 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800564 return ret;
bellardea2384d2004-08-01 21:59:26 +0000565}
566
Max Reitzfd171462020-01-22 17:45:29 +0100567/**
568 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
569 * least the given @minimum_size.
570 *
571 * On success, return @blk's actual length.
572 * Otherwise, return -errno.
573 */
574static int64_t create_file_fallback_truncate(BlockBackend *blk,
575 int64_t minimum_size, Error **errp)
576{
577 Error *local_err = NULL;
578 int64_t size;
579 int ret;
580
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200581 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
582 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100583 if (ret < 0 && ret != -ENOTSUP) {
584 error_propagate(errp, local_err);
585 return ret;
586 }
587
588 size = blk_getlength(blk);
589 if (size < 0) {
590 error_free(local_err);
591 error_setg_errno(errp, -size,
592 "Failed to inquire the new image file's length");
593 return size;
594 }
595
596 if (size < minimum_size) {
597 /* Need to grow the image, but we failed to do that */
598 error_propagate(errp, local_err);
599 return -ENOTSUP;
600 }
601
602 error_free(local_err);
603 local_err = NULL;
604
605 return size;
606}
607
608/**
609 * Helper function for bdrv_create_file_fallback(): Zero the first
610 * sector to remove any potentially pre-existing image header.
611 */
612static int create_file_fallback_zero_first_sector(BlockBackend *blk,
613 int64_t current_size,
614 Error **errp)
615{
616 int64_t bytes_to_clear;
617 int ret;
618
619 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
620 if (bytes_to_clear) {
621 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
622 if (ret < 0) {
623 error_setg_errno(errp, -ret,
624 "Failed to clear the new image's first sector");
625 return ret;
626 }
627 }
628
629 return 0;
630}
631
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200632/**
633 * Simple implementation of bdrv_co_create_opts for protocol drivers
634 * which only support creation via opening a file
635 * (usually existing raw storage device)
636 */
637int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
638 const char *filename,
639 QemuOpts *opts,
640 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100641{
642 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100643 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100644 int64_t size = 0;
645 char *buf = NULL;
646 PreallocMode prealloc;
647 Error *local_err = NULL;
648 int ret;
649
650 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
651 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
652 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
653 PREALLOC_MODE_OFF, &local_err);
654 g_free(buf);
655 if (local_err) {
656 error_propagate(errp, local_err);
657 return -EINVAL;
658 }
659
660 if (prealloc != PREALLOC_MODE_OFF) {
661 error_setg(errp, "Unsupported preallocation mode '%s'",
662 PreallocMode_str(prealloc));
663 return -ENOTSUP;
664 }
665
Max Reitzeeea1fa2020-02-25 16:56:18 +0100666 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100667 qdict_put_str(options, "driver", drv->format_name);
668
669 blk = blk_new_open(filename, NULL, options,
670 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
671 if (!blk) {
672 error_prepend(errp, "Protocol driver '%s' does not support image "
673 "creation, and opening the image failed: ",
674 drv->format_name);
675 return -EINVAL;
676 }
677
678 size = create_file_fallback_truncate(blk, size, errp);
679 if (size < 0) {
680 ret = size;
681 goto out;
682 }
683
684 ret = create_file_fallback_zero_first_sector(blk, size, errp);
685 if (ret < 0) {
686 goto out;
687 }
688
689 ret = 0;
690out:
691 blk_unref(blk);
692 return ret;
693}
694
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800695int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200696{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100697 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200698 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100699 QDict *qdict;
700 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200701
Max Reitzb65a5e12015-02-05 13:58:12 -0500702 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200703 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000704 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200705 }
706
Stefano Garzarella729222a2021-03-08 17:12:32 +0100707 if (!drv->create_opts) {
708 error_setg(errp, "Driver '%s' does not support image creation",
709 drv->format_name);
710 return -ENOTSUP;
711 }
712
713 /*
714 * 'opts' contains a QemuOptsList with a combination of format and protocol
715 * default values.
716 *
717 * The format properly removes its options, but the default values remain
718 * in 'opts->list'. So if the protocol has options with the same name
719 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
720 * of the format, since for overlapping options, the format wins.
721 *
722 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
723 * only the set options, and then convert it back to QemuOpts, using the
724 * create_opts of the protocol. So the new QemuOpts, will contain only the
725 * protocol defaults.
726 */
727 qdict = qemu_opts_to_qdict(opts, NULL);
728 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
729 if (protocol_opts == NULL) {
730 ret = -EINVAL;
731 goto out;
732 }
733
734 ret = bdrv_create(drv, filename, protocol_opts, errp);
735out:
736 qemu_opts_del(protocol_opts);
737 qobject_unref(qdict);
738 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200739}
740
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300741int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
742{
743 Error *local_err = NULL;
744 int ret;
745
746 assert(bs != NULL);
747
748 if (!bs->drv) {
749 error_setg(errp, "Block node '%s' is not opened", bs->filename);
750 return -ENOMEDIUM;
751 }
752
753 if (!bs->drv->bdrv_co_delete_file) {
754 error_setg(errp, "Driver '%s' does not support image deletion",
755 bs->drv->format_name);
756 return -ENOTSUP;
757 }
758
759 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
760 if (ret < 0) {
761 error_propagate(errp, local_err);
762 }
763
764 return ret;
765}
766
Maxim Levitskya890f082020-12-17 19:09:03 +0200767void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
768{
769 Error *local_err = NULL;
770 int ret;
771
772 if (!bs) {
773 return;
774 }
775
776 ret = bdrv_co_delete_file(bs, &local_err);
777 /*
778 * ENOTSUP will happen if the block driver doesn't support
779 * the 'bdrv_co_delete_file' interface. This is a predictable
780 * scenario and shouldn't be reported back to the user.
781 */
782 if (ret == -ENOTSUP) {
783 error_free(local_err);
784 } else if (ret < 0) {
785 error_report_err(local_err);
786 }
787}
788
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100789/**
790 * Try to get @bs's logical and physical block size.
791 * On success, store them in @bsz struct and return 0.
792 * On failure return -errno.
793 * @bs must not be empty.
794 */
795int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
796{
797 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200798 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100799
800 if (drv && drv->bdrv_probe_blocksizes) {
801 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200802 } else if (filtered) {
803 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100804 }
805
806 return -ENOTSUP;
807}
808
809/**
810 * Try to get @bs's geometry (cyls, heads, sectors).
811 * On success, store them in @geo struct and return 0.
812 * On failure return -errno.
813 * @bs must not be empty.
814 */
815int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
816{
817 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200818 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100819
820 if (drv && drv->bdrv_probe_geometry) {
821 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200822 } else if (filtered) {
823 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100824 }
825
826 return -ENOTSUP;
827}
828
Jim Meyeringeba25052012-05-28 09:27:54 +0200829/*
830 * Create a uniquely-named empty temporary file.
831 * Return 0 upon success, otherwise a negative errno value.
832 */
833int get_tmp_filename(char *filename, int size)
834{
bellardd5249392004-08-03 21:14:23 +0000835#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000836 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200837 /* GetTempFileName requires that its output buffer (4th param)
838 have length MAX_PATH or greater. */
839 assert(size >= MAX_PATH);
840 return (GetTempPath(MAX_PATH, temp_dir)
841 && GetTempFileName(temp_dir, "qem", 0, filename)
842 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000843#else
bellardea2384d2004-08-01 21:59:26 +0000844 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000845 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000846 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530847 if (!tmpdir) {
848 tmpdir = "/var/tmp";
849 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200850 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
851 return -EOVERFLOW;
852 }
bellardea2384d2004-08-01 21:59:26 +0000853 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800854 if (fd < 0) {
855 return -errno;
856 }
857 if (close(fd) != 0) {
858 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200859 return -errno;
860 }
861 return 0;
bellardd5249392004-08-03 21:14:23 +0000862#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200863}
bellardea2384d2004-08-01 21:59:26 +0000864
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200865/*
866 * Detect host devices. By convention, /dev/cdrom[N] is always
867 * recognized as a host CDROM.
868 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200869static BlockDriver *find_hdev_driver(const char *filename)
870{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200871 int score_max = 0, score;
872 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200873
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100874 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200875 if (d->bdrv_probe_device) {
876 score = d->bdrv_probe_device(filename);
877 if (score > score_max) {
878 score_max = score;
879 drv = d;
880 }
881 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200882 }
883
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200884 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200885}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200886
Marc Mari88d88792016-08-12 09:27:03 -0400887static BlockDriver *bdrv_do_find_protocol(const char *protocol)
888{
889 BlockDriver *drv1;
890
891 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
892 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
893 return drv1;
894 }
895 }
896
897 return NULL;
898}
899
Kevin Wolf98289622013-07-10 15:47:39 +0200900BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500901 bool allow_protocol_prefix,
902 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200903{
904 BlockDriver *drv1;
905 char protocol[128];
906 int len;
907 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400908 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200909
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200910 /* TODO Drivers without bdrv_file_open must be specified explicitly */
911
Christoph Hellwig39508e72010-06-23 12:25:17 +0200912 /*
913 * XXX(hch): we really should not let host device detection
914 * override an explicit protocol specification, but moving this
915 * later breaks access to device names with colons in them.
916 * Thanks to the brain-dead persistent naming schemes on udev-
917 * based Linux systems those actually are quite common.
918 */
919 drv1 = find_hdev_driver(filename);
920 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200921 return drv1;
922 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200923
Kevin Wolf98289622013-07-10 15:47:39 +0200924 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100925 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200926 }
Kevin Wolf98289622013-07-10 15:47:39 +0200927
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000928 p = strchr(filename, ':');
929 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200930 len = p - filename;
931 if (len > sizeof(protocol) - 1)
932 len = sizeof(protocol) - 1;
933 memcpy(protocol, filename, len);
934 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400935
936 drv1 = bdrv_do_find_protocol(protocol);
937 if (drv1) {
938 return drv1;
939 }
940
941 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
942 if (block_driver_modules[i].protocol_name &&
943 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
944 block_module_load_one(block_driver_modules[i].library_name);
945 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200946 }
947 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500948
Marc Mari88d88792016-08-12 09:27:03 -0400949 drv1 = bdrv_do_find_protocol(protocol);
950 if (!drv1) {
951 error_setg(errp, "Unknown protocol '%s'", protocol);
952 }
953 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200954}
955
Markus Armbrusterc6684242014-11-20 16:27:10 +0100956/*
957 * Guess image format by probing its contents.
958 * This is not a good idea when your image is raw (CVE-2008-2004), but
959 * we do it anyway for backward compatibility.
960 *
961 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100962 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
963 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100964 * @filename is its filename.
965 *
966 * For all block drivers, call the bdrv_probe() method to get its
967 * probing score.
968 * Return the first block driver with the highest probing score.
969 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100970BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
971 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100972{
973 int score_max = 0, score;
974 BlockDriver *drv = NULL, *d;
975
976 QLIST_FOREACH(d, &bdrv_drivers, list) {
977 if (d->bdrv_probe) {
978 score = d->bdrv_probe(buf, buf_size, filename);
979 if (score > score_max) {
980 score_max = score;
981 drv = d;
982 }
983 }
984 }
985
986 return drv;
987}
988
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100989static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200990 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000991{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100992 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100993 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100994 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700995
Kevin Wolf08a00552010-06-01 18:37:31 +0200996 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100997 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100998 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200999 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -07001000 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001001
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001002 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +00001003 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001004 error_setg_errno(errp, -ret, "Could not read image for determining its "
1005 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +02001006 *pdrv = NULL;
1007 return ret;
bellard83f64092006-08-01 16:21:11 +00001008 }
1009
Markus Armbrusterc6684242014-11-20 16:27:10 +01001010 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +02001011 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001012 error_setg(errp, "Could not determine image format: No compatible "
1013 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +02001014 ret = -ENOENT;
1015 }
1016 *pdrv = drv;
1017 return ret;
bellardea2384d2004-08-01 21:59:26 +00001018}
1019
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001020/**
1021 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001022 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001023 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001024int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001025{
1026 BlockDriver *drv = bs->drv;
1027
Max Reitzd470ad42017-11-10 21:31:09 +01001028 if (!drv) {
1029 return -ENOMEDIUM;
1030 }
1031
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001032 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001033 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001034 return 0;
1035
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001036 /* query actual device if possible, otherwise just trust the hint */
1037 if (drv->bdrv_getlength) {
1038 int64_t length = drv->bdrv_getlength(bs);
1039 if (length < 0) {
1040 return length;
1041 }
Fam Zheng7e382002013-11-06 19:48:06 +08001042 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001043 }
1044
1045 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001046
1047 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1048 return -EFBIG;
1049 }
1050
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001051 return 0;
1052}
1053
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001054/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001055 * Combines a QDict of new block driver @options with any missing options taken
1056 * from @old_options, so that leaving out an option defaults to its old value.
1057 */
1058static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1059 QDict *old_options)
1060{
1061 if (bs->drv && bs->drv->bdrv_join_options) {
1062 bs->drv->bdrv_join_options(options, old_options);
1063 } else {
1064 qdict_join(options, old_options, false);
1065 }
1066}
1067
Alberto Garcia543770b2018-09-06 12:37:09 +03001068static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1069 int open_flags,
1070 Error **errp)
1071{
1072 Error *local_err = NULL;
1073 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1074 BlockdevDetectZeroesOptions detect_zeroes =
1075 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1076 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1077 g_free(value);
1078 if (local_err) {
1079 error_propagate(errp, local_err);
1080 return detect_zeroes;
1081 }
1082
1083 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1084 !(open_flags & BDRV_O_UNMAP))
1085 {
1086 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1087 "without setting discard operation to unmap");
1088 }
1089
1090 return detect_zeroes;
1091}
1092
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001093/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001094 * Set open flags for aio engine
1095 *
1096 * Return 0 on success, -1 if the engine specified is invalid
1097 */
1098int bdrv_parse_aio(const char *mode, int *flags)
1099{
1100 if (!strcmp(mode, "threads")) {
1101 /* do nothing, default */
1102 } else if (!strcmp(mode, "native")) {
1103 *flags |= BDRV_O_NATIVE_AIO;
1104#ifdef CONFIG_LINUX_IO_URING
1105 } else if (!strcmp(mode, "io_uring")) {
1106 *flags |= BDRV_O_IO_URING;
1107#endif
1108 } else {
1109 return -1;
1110 }
1111
1112 return 0;
1113}
1114
1115/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001116 * Set open flags for a given discard mode
1117 *
1118 * Return 0 on success, -1 if the discard mode was invalid.
1119 */
1120int bdrv_parse_discard_flags(const char *mode, int *flags)
1121{
1122 *flags &= ~BDRV_O_UNMAP;
1123
1124 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1125 /* do nothing */
1126 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1127 *flags |= BDRV_O_UNMAP;
1128 } else {
1129 return -1;
1130 }
1131
1132 return 0;
1133}
1134
1135/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001136 * Set open flags for a given cache mode
1137 *
1138 * Return 0 on success, -1 if the cache mode was invalid.
1139 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001140int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001141{
1142 *flags &= ~BDRV_O_CACHE_MASK;
1143
1144 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001145 *writethrough = false;
1146 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001147 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001148 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001149 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001150 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001151 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001152 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001153 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001154 *flags |= BDRV_O_NO_FLUSH;
1155 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001156 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001157 } else {
1158 return -1;
1159 }
1160
1161 return 0;
1162}
1163
Kevin Wolfb5411552017-01-17 15:56:16 +01001164static char *bdrv_child_get_parent_desc(BdrvChild *c)
1165{
1166 BlockDriverState *parent = c->opaque;
Vladimir Sementsov-Ogievskiy2c0a3ac2021-06-01 10:52:15 +03001167 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
Kevin Wolfb5411552017-01-17 15:56:16 +01001168}
1169
Kevin Wolf20018e12016-05-23 18:46:59 +02001170static void bdrv_child_cb_drained_begin(BdrvChild *child)
1171{
1172 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001173 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001174}
1175
Kevin Wolf89bd0302018-03-22 14:11:20 +01001176static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1177{
1178 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001179 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001180}
1181
Max Reitze037c092019-07-19 11:26:14 +02001182static void bdrv_child_cb_drained_end(BdrvChild *child,
1183 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001184{
1185 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001186 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001187}
1188
Kevin Wolf38701b62017-05-04 18:52:39 +02001189static int bdrv_child_cb_inactivate(BdrvChild *child)
1190{
1191 BlockDriverState *bs = child->opaque;
1192 assert(bs->open_flags & BDRV_O_INACTIVE);
1193 return 0;
1194}
1195
Kevin Wolf5d231842019-05-06 19:17:56 +02001196static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1197 GSList **ignore, Error **errp)
1198{
1199 BlockDriverState *bs = child->opaque;
1200 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1201}
1202
Kevin Wolf53a7d042019-05-06 19:17:59 +02001203static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1204 GSList **ignore)
1205{
1206 BlockDriverState *bs = child->opaque;
1207 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1208}
1209
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001210/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001211 * Returns the options and flags that a temporary snapshot should get, based on
1212 * the originally requested flags (the originally requested image will have
1213 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001214 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001215static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1216 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001217{
Kevin Wolf73176be2016-03-07 13:02:15 +01001218 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1219
1220 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001221 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1222 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001223
Kevin Wolf3f486862019-04-04 17:04:43 +02001224 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001225 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001226 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001227
Kevin Wolf41869042016-06-16 12:59:30 +02001228 /* aio=native doesn't work for cache.direct=off, so disable it for the
1229 * temporary snapshot */
1230 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001231}
1232
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001233static void bdrv_backing_attach(BdrvChild *c)
1234{
1235 BlockDriverState *parent = c->opaque;
1236 BlockDriverState *backing_hd = c->bs;
1237
1238 assert(!parent->backing_blocker);
1239 error_setg(&parent->backing_blocker,
1240 "node is used as backing hd of '%s'",
1241 bdrv_get_device_or_node_name(parent));
1242
Max Reitzf30c66b2019-02-01 20:29:05 +01001243 bdrv_refresh_filename(backing_hd);
1244
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001245 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001246
1247 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1248 /* Otherwise we won't be able to commit or stream */
1249 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1250 parent->backing_blocker);
1251 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1252 parent->backing_blocker);
1253 /*
1254 * We do backup in 3 ways:
1255 * 1. drive backup
1256 * The target bs is new opened, and the source is top BDS
1257 * 2. blockdev backup
1258 * Both the source and the target are top BDSes.
1259 * 3. internal backup(used for block replication)
1260 * Both the source and the target are backing file
1261 *
1262 * In case 1 and 2, neither the source nor the target is the backing file.
1263 * In case 3, we will block the top BDS, so there is only one block job
1264 * for the top BDS and its backing chain.
1265 */
1266 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1267 parent->backing_blocker);
1268 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1269 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001270}
Kevin Wolfd736f112017-12-18 16:05:48 +01001271
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001272static void bdrv_backing_detach(BdrvChild *c)
1273{
1274 BlockDriverState *parent = c->opaque;
1275
1276 assert(parent->backing_blocker);
1277 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1278 error_free(parent->backing_blocker);
1279 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001280}
Kevin Wolfd736f112017-12-18 16:05:48 +01001281
Kevin Wolf6858eba2017-06-29 19:32:21 +02001282static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1283 const char *filename, Error **errp)
1284{
1285 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001286 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001287 int ret;
1288
Alberto Garciae94d3db2018-11-12 16:00:34 +02001289 if (read_only) {
1290 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001291 if (ret < 0) {
1292 return ret;
1293 }
1294 }
1295
Kevin Wolf6858eba2017-06-29 19:32:21 +02001296 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001297 base->drv ? base->drv->format_name : "",
1298 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001299 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001300 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001301 }
1302
Alberto Garciae94d3db2018-11-12 16:00:34 +02001303 if (read_only) {
1304 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001305 }
1306
Kevin Wolf6858eba2017-06-29 19:32:21 +02001307 return ret;
1308}
1309
Max Reitzfae8bd32020-05-13 13:05:20 +02001310/*
1311 * Returns the options and flags that a generic child of a BDS should
1312 * get, based on the given options and flags for the parent BDS.
1313 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001314static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1315 int *child_flags, QDict *child_options,
1316 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001317{
1318 int flags = parent_flags;
1319
1320 /*
1321 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1322 * Generally, the question to answer is: Should this child be
1323 * format-probed by default?
1324 */
1325
1326 /*
1327 * Pure and non-filtered data children of non-format nodes should
1328 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1329 * set). This only affects a very limited set of drivers (namely
1330 * quorum and blkverify when this comment was written).
1331 * Force-clear BDRV_O_PROTOCOL then.
1332 */
1333 if (!parent_is_format &&
1334 (role & BDRV_CHILD_DATA) &&
1335 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1336 {
1337 flags &= ~BDRV_O_PROTOCOL;
1338 }
1339
1340 /*
1341 * All children of format nodes (except for COW children) and all
1342 * metadata children in general should never be format-probed.
1343 * Force-set BDRV_O_PROTOCOL then.
1344 */
1345 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1346 (role & BDRV_CHILD_METADATA))
1347 {
1348 flags |= BDRV_O_PROTOCOL;
1349 }
1350
1351 /*
1352 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1353 * the parent.
1354 */
1355 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1356 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1357 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1358
1359 if (role & BDRV_CHILD_COW) {
1360 /* backing files are opened read-only by default */
1361 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1362 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1363 } else {
1364 /* Inherit the read-only option from the parent if it's not set */
1365 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1366 qdict_copy_default(child_options, parent_options,
1367 BDRV_OPT_AUTO_READ_ONLY);
1368 }
1369
1370 /*
1371 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1372 * can default to enable it on lower layers regardless of the
1373 * parent option.
1374 */
1375 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1376
1377 /* Clear flags that only apply to the top layer */
1378 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1379
1380 if (role & BDRV_CHILD_METADATA) {
1381 flags &= ~BDRV_O_NO_IO;
1382 }
1383 if (role & BDRV_CHILD_COW) {
1384 flags &= ~BDRV_O_TEMPORARY;
1385 }
1386
1387 *child_flags = flags;
1388}
1389
Max Reitzca2f1232020-05-13 13:05:22 +02001390static void bdrv_child_cb_attach(BdrvChild *child)
1391{
1392 BlockDriverState *bs = child->opaque;
1393
Hanna Reitza2253692021-11-15 15:53:58 +01001394 QLIST_INSERT_HEAD(&bs->children, child, next);
1395
Max Reitzca2f1232020-05-13 13:05:22 +02001396 if (child->role & BDRV_CHILD_COW) {
1397 bdrv_backing_attach(child);
1398 }
1399
1400 bdrv_apply_subtree_drain(child, bs);
1401}
1402
Max Reitz48e08282020-05-13 13:05:23 +02001403static void bdrv_child_cb_detach(BdrvChild *child)
1404{
1405 BlockDriverState *bs = child->opaque;
1406
1407 if (child->role & BDRV_CHILD_COW) {
1408 bdrv_backing_detach(child);
1409 }
1410
1411 bdrv_unapply_subtree_drain(child, bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001412
1413 QLIST_REMOVE(child, next);
Max Reitz48e08282020-05-13 13:05:23 +02001414}
1415
Max Reitz43483552020-05-13 13:05:24 +02001416static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1417 const char *filename, Error **errp)
1418{
1419 if (c->role & BDRV_CHILD_COW) {
1420 return bdrv_backing_update_filename(c, base, filename, errp);
1421 }
1422 return 0;
1423}
1424
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001425AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001426{
1427 BlockDriverState *bs = c->opaque;
1428
1429 return bdrv_get_aio_context(bs);
1430}
1431
Max Reitz43483552020-05-13 13:05:24 +02001432const BdrvChildClass child_of_bds = {
1433 .parent_is_bds = true,
1434 .get_parent_desc = bdrv_child_get_parent_desc,
1435 .inherit_options = bdrv_inherited_options,
1436 .drained_begin = bdrv_child_cb_drained_begin,
1437 .drained_poll = bdrv_child_cb_drained_poll,
1438 .drained_end = bdrv_child_cb_drained_end,
1439 .attach = bdrv_child_cb_attach,
1440 .detach = bdrv_child_cb_detach,
1441 .inactivate = bdrv_child_cb_inactivate,
1442 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1443 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1444 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001445 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001446};
1447
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001448AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1449{
1450 return c->klass->get_parent_aio_context(c);
1451}
1452
Kevin Wolf7b272452012-11-12 17:05:39 +01001453static int bdrv_open_flags(BlockDriverState *bs, int flags)
1454{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001455 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001456
1457 /*
1458 * Clear flags that are internal to the block layer before opening the
1459 * image.
1460 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001461 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001462
Kevin Wolf7b272452012-11-12 17:05:39 +01001463 return open_flags;
1464}
1465
Kevin Wolf91a097e2015-05-08 17:49:53 +02001466static void update_flags_from_options(int *flags, QemuOpts *opts)
1467{
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001468 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001469
Alberto Garcia57f9db92018-09-06 12:37:06 +03001470 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001471 *flags |= BDRV_O_NO_FLUSH;
1472 }
1473
Alberto Garcia57f9db92018-09-06 12:37:06 +03001474 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001475 *flags |= BDRV_O_NOCACHE;
1476 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001477
Alberto Garcia57f9db92018-09-06 12:37:06 +03001478 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001479 *flags |= BDRV_O_RDWR;
1480 }
1481
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001482 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1483 *flags |= BDRV_O_AUTO_RDONLY;
1484 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001485}
1486
1487static void update_options_from_flags(QDict *options, int flags)
1488{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001489 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001490 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001491 }
1492 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001493 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1494 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001495 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001496 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001497 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001498 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001499 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1500 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1501 flags & BDRV_O_AUTO_RDONLY);
1502 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001503}
1504
Kevin Wolf636ea372014-01-24 14:11:52 +01001505static void bdrv_assign_node_name(BlockDriverState *bs,
1506 const char *node_name,
1507 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001508{
Jeff Cody15489c72015-10-12 19:36:50 -04001509 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001510
Jeff Cody15489c72015-10-12 19:36:50 -04001511 if (!node_name) {
1512 node_name = gen_node_name = id_generate(ID_BLOCK);
1513 } else if (!id_wellformed(node_name)) {
1514 /*
1515 * Check for empty string or invalid characters, but not if it is
1516 * generated (generated names use characters not available to the user)
1517 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001518 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001519 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001520 }
1521
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001522 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001523 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001524 error_setg(errp, "node-name=%s is conflicting with a device id",
1525 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001526 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001527 }
1528
Benoît Canet6913c0c2014-01-23 21:31:33 +01001529 /* takes care of avoiding duplicates node names */
1530 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001531 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001532 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001533 }
1534
Kevin Wolf824808d2018-07-04 13:28:29 +02001535 /* Make sure that the node name isn't truncated */
1536 if (strlen(node_name) >= sizeof(bs->node_name)) {
1537 error_setg(errp, "Node name too long");
1538 goto out;
1539 }
1540
Benoît Canet6913c0c2014-01-23 21:31:33 +01001541 /* copy node name into the bs and insert it into the graph list */
1542 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1543 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001544out:
1545 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001546}
1547
Kevin Wolf01a56502017-01-18 15:51:56 +01001548static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1549 const char *node_name, QDict *options,
1550 int open_flags, Error **errp)
1551{
1552 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001553 int i, ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001554
1555 bdrv_assign_node_name(bs, node_name, &local_err);
1556 if (local_err) {
1557 error_propagate(errp, local_err);
1558 return -EINVAL;
1559 }
1560
1561 bs->drv = drv;
1562 bs->opaque = g_malloc0(drv->instance_size);
1563
1564 if (drv->bdrv_file_open) {
1565 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1566 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001567 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001568 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001569 } else {
1570 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001571 }
1572
1573 if (ret < 0) {
1574 if (local_err) {
1575 error_propagate(errp, local_err);
1576 } else if (bs->filename[0]) {
1577 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1578 } else {
1579 error_setg_errno(errp, -ret, "Could not open image");
1580 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001581 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001582 }
1583
1584 ret = refresh_total_sectors(bs, bs->total_sectors);
1585 if (ret < 0) {
1586 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001587 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001588 }
1589
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001590 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001591 if (local_err) {
1592 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001593 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001594 }
1595
1596 assert(bdrv_opt_mem_align(bs) != 0);
1597 assert(bdrv_min_mem_align(bs) != 0);
1598 assert(is_power_of_2(bs->bl.request_alignment));
1599
Kevin Wolf0f122642018-03-28 18:29:18 +02001600 for (i = 0; i < bs->quiesce_counter; i++) {
1601 if (drv->bdrv_co_drain_begin) {
1602 drv->bdrv_co_drain_begin(bs);
1603 }
1604 }
1605
Kevin Wolf01a56502017-01-18 15:51:56 +01001606 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001607open_failed:
1608 bs->drv = NULL;
1609 if (bs->file != NULL) {
1610 bdrv_unref_child(bs, bs->file);
1611 bs->file = NULL;
1612 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001613 g_free(bs->opaque);
1614 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001615 return ret;
1616}
1617
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001618/*
1619 * Create and open a block node.
1620 *
1621 * @options is a QDict of options to pass to the block drivers, or NULL for an
1622 * empty set of options. The reference to the QDict belongs to the block layer
1623 * after the call (even on failure), so if the caller intends to reuse the
1624 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1625 */
1626BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1627 const char *node_name,
1628 QDict *options, int flags,
1629 Error **errp)
Kevin Wolf680c7f92017-01-18 17:16:41 +01001630{
1631 BlockDriverState *bs;
1632 int ret;
1633
1634 bs = bdrv_new();
1635 bs->open_flags = flags;
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001636 bs->options = options ?: qdict_new();
1637 bs->explicit_options = qdict_clone_shallow(bs->options);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001638 bs->opaque = NULL;
1639
1640 update_options_from_flags(bs->options, flags);
1641
1642 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1643 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001644 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001645 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001646 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001647 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001648 bdrv_unref(bs);
1649 return NULL;
1650 }
1651
1652 return bs;
1653}
1654
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001655/* Create and open a block node. */
1656BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1657 int flags, Error **errp)
1658{
1659 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1660}
1661
Kevin Wolfc5f30142016-10-06 11:33:17 +02001662QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001663 .name = "bdrv_common",
1664 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1665 .desc = {
1666 {
1667 .name = "node-name",
1668 .type = QEMU_OPT_STRING,
1669 .help = "Node name of the block device node",
1670 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001671 {
1672 .name = "driver",
1673 .type = QEMU_OPT_STRING,
1674 .help = "Block driver to use for the node",
1675 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001676 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001677 .name = BDRV_OPT_CACHE_DIRECT,
1678 .type = QEMU_OPT_BOOL,
1679 .help = "Bypass software writeback cache on the host",
1680 },
1681 {
1682 .name = BDRV_OPT_CACHE_NO_FLUSH,
1683 .type = QEMU_OPT_BOOL,
1684 .help = "Ignore flush requests",
1685 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001686 {
1687 .name = BDRV_OPT_READ_ONLY,
1688 .type = QEMU_OPT_BOOL,
1689 .help = "Node is opened in read-only mode",
1690 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001691 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001692 .name = BDRV_OPT_AUTO_READ_ONLY,
1693 .type = QEMU_OPT_BOOL,
1694 .help = "Node can become read-only if opening read-write fails",
1695 },
1696 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001697 .name = "detect-zeroes",
1698 .type = QEMU_OPT_STRING,
1699 .help = "try to optimize zero writes (off, on, unmap)",
1700 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001701 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001702 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001703 .type = QEMU_OPT_STRING,
1704 .help = "discard operation (ignore/off, unmap/on)",
1705 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001706 {
1707 .name = BDRV_OPT_FORCE_SHARE,
1708 .type = QEMU_OPT_BOOL,
1709 .help = "always accept other writers (default: off)",
1710 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001711 { /* end of list */ }
1712 },
1713};
1714
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001715QemuOptsList bdrv_create_opts_simple = {
1716 .name = "simple-create-opts",
1717 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001718 .desc = {
1719 {
1720 .name = BLOCK_OPT_SIZE,
1721 .type = QEMU_OPT_SIZE,
1722 .help = "Virtual disk size"
1723 },
1724 {
1725 .name = BLOCK_OPT_PREALLOC,
1726 .type = QEMU_OPT_STRING,
1727 .help = "Preallocation mode (allowed values: off)"
1728 },
1729 { /* end of list */ }
1730 }
1731};
1732
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001733/*
Kevin Wolf57915332010-04-14 15:24:50 +02001734 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001735 *
1736 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001737 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001738static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001739 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001740{
1741 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001742 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001743 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001744 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001745 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001746 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001747 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001748 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001749 bool ro;
Kevin Wolf57915332010-04-14 15:24:50 +02001750
Paolo Bonzini64058752012-05-08 16:51:49 +02001751 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001752 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001753
Kevin Wolf62392eb2015-04-24 16:38:02 +02001754 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001755 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001756 ret = -EINVAL;
1757 goto fail_opts;
1758 }
1759
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001760 update_flags_from_options(&bs->open_flags, opts);
1761
Kevin Wolf62392eb2015-04-24 16:38:02 +02001762 driver_name = qemu_opt_get(opts, "driver");
1763 drv = bdrv_find_format(driver_name);
1764 assert(drv != NULL);
1765
Fam Zheng5a9347c2017-05-03 00:35:37 +08001766 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1767
1768 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1769 error_setg(errp,
1770 BDRV_OPT_FORCE_SHARE
1771 "=on can only be used with read-only images");
1772 ret = -EINVAL;
1773 goto fail_opts;
1774 }
1775
Kevin Wolf45673672013-04-22 17:48:40 +02001776 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001777 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001778 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001779 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001780 /*
1781 * Caution: while qdict_get_try_str() is fine, getting
1782 * non-string types would require more care. When @options
1783 * come from -blockdev or blockdev_add, its members are typed
1784 * according to the QAPI schema, but when they come from
1785 * -drive, they're all QString.
1786 */
Kevin Wolf45673672013-04-22 17:48:40 +02001787 filename = qdict_get_try_str(options, "filename");
1788 }
1789
Max Reitz4a008242017-04-13 18:06:24 +02001790 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001791 error_setg(errp, "The '%s' block driver requires a file name",
1792 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001793 ret = -EINVAL;
1794 goto fail_opts;
1795 }
1796
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001797 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1798 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001799
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001800 ro = bdrv_is_read_only(bs);
1801
1802 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1803 if (!ro && bdrv_is_whitelisted(drv, true)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001804 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1805 } else {
1806 ret = -ENOTSUP;
1807 }
1808 if (ret < 0) {
1809 error_setg(errp,
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001810 !ro && bdrv_is_whitelisted(drv, true)
Kevin Wolf8be25de2019-01-22 13:15:31 +01001811 ? "Driver '%s' can only be used for read-only devices"
1812 : "Driver '%s' is not whitelisted",
1813 drv->format_name);
1814 goto fail_opts;
1815 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001816 }
Kevin Wolf57915332010-04-14 15:24:50 +02001817
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001818 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001819 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001820
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001821 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001822 if (!ro) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001823 bdrv_enable_copy_on_read(bs);
1824 } else {
1825 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001826 ret = -EINVAL;
1827 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001828 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001829 }
1830
Alberto Garcia415bbca2018-10-03 13:23:13 +03001831 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001832 if (discard != NULL) {
1833 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1834 error_setg(errp, "Invalid discard option");
1835 ret = -EINVAL;
1836 goto fail_opts;
1837 }
1838 }
1839
Alberto Garcia543770b2018-09-06 12:37:09 +03001840 bs->detect_zeroes =
1841 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1842 if (local_err) {
1843 error_propagate(errp, local_err);
1844 ret = -EINVAL;
1845 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001846 }
1847
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001848 if (filename != NULL) {
1849 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1850 } else {
1851 bs->filename[0] = '\0';
1852 }
Max Reitz91af7012014-07-18 20:24:56 +02001853 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001854
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001855 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001856 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001857 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001858
Kevin Wolf01a56502017-01-18 15:51:56 +01001859 assert(!drv->bdrv_file_open || file == NULL);
1860 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001861 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001862 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001863 }
1864
Kevin Wolf18edf282015-04-07 17:12:56 +02001865 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001866 return 0;
1867
Kevin Wolf18edf282015-04-07 17:12:56 +02001868fail_opts:
1869 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001870 return ret;
1871}
1872
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001873static QDict *parse_json_filename(const char *filename, Error **errp)
1874{
1875 QObject *options_obj;
1876 QDict *options;
1877 int ret;
1878
1879 ret = strstart(filename, "json:", &filename);
1880 assert(ret);
1881
Markus Armbruster5577fff2017-02-28 22:26:59 +01001882 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001883 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001884 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001885 return NULL;
1886 }
1887
Max Reitz7dc847e2018-02-24 16:40:29 +01001888 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001889 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001890 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001891 error_setg(errp, "Invalid JSON object given");
1892 return NULL;
1893 }
1894
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001895 qdict_flatten(options);
1896
1897 return options;
1898}
1899
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001900static void parse_json_protocol(QDict *options, const char **pfilename,
1901 Error **errp)
1902{
1903 QDict *json_options;
1904 Error *local_err = NULL;
1905
1906 /* Parse json: pseudo-protocol */
1907 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1908 return;
1909 }
1910
1911 json_options = parse_json_filename(*pfilename, &local_err);
1912 if (local_err) {
1913 error_propagate(errp, local_err);
1914 return;
1915 }
1916
1917 /* Options given in the filename have lower priority than options
1918 * specified directly */
1919 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001920 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001921 *pfilename = NULL;
1922}
1923
Kevin Wolf57915332010-04-14 15:24:50 +02001924/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001925 * Fills in default options for opening images and converts the legacy
1926 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001927 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1928 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001929 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001930static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001931 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001932{
1933 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001934 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001935 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001936 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001937 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001938
Markus Armbruster129c7d12017-03-30 19:43:12 +02001939 /*
1940 * Caution: while qdict_get_try_str() is fine, getting non-string
1941 * types would require more care. When @options come from
1942 * -blockdev or blockdev_add, its members are typed according to
1943 * the QAPI schema, but when they come from -drive, they're all
1944 * QString.
1945 */
Max Reitz53a29512015-03-19 14:53:16 -04001946 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001947 if (drvname) {
1948 drv = bdrv_find_format(drvname);
1949 if (!drv) {
1950 error_setg(errp, "Unknown driver '%s'", drvname);
1951 return -ENOENT;
1952 }
1953 /* If the user has explicitly specified the driver, this choice should
1954 * override the BDRV_O_PROTOCOL flag */
1955 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001956 }
1957
1958 if (protocol) {
1959 *flags |= BDRV_O_PROTOCOL;
1960 } else {
1961 *flags &= ~BDRV_O_PROTOCOL;
1962 }
1963
Kevin Wolf91a097e2015-05-08 17:49:53 +02001964 /* Translate cache options from flags into options */
1965 update_options_from_flags(*options, *flags);
1966
Kevin Wolff54120f2014-05-26 11:09:59 +02001967 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001968 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001969 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001970 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001971 parse_filename = true;
1972 } else {
1973 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1974 "the same time");
1975 return -EINVAL;
1976 }
1977 }
1978
1979 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001980 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001981 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001982
Max Reitz053e1572015-08-26 19:47:51 +02001983 if (!drvname && protocol) {
1984 if (filename) {
1985 drv = bdrv_find_protocol(filename, parse_filename, errp);
1986 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001987 return -EINVAL;
1988 }
Max Reitz053e1572015-08-26 19:47:51 +02001989
1990 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05001991 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02001992 } else {
1993 error_setg(errp, "Must specify either driver or file");
1994 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001995 }
1996 }
1997
Kevin Wolf17b005f2014-05-27 10:50:29 +02001998 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001999
2000 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002001 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002002 drv->bdrv_parse_filename(filename, *options, &local_err);
2003 if (local_err) {
2004 error_propagate(errp, local_err);
2005 return -EINVAL;
2006 }
2007
2008 if (!drv->bdrv_needs_filename) {
2009 qdict_del(*options, "filename");
2010 }
2011 }
2012
2013 return 0;
2014}
2015
Kevin Wolf148eb132017-09-14 14:32:04 +02002016typedef struct BlockReopenQueueEntry {
2017 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01002018 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02002019 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002020 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02002021} BlockReopenQueueEntry;
2022
2023/*
2024 * Return the flags that @bs will have after the reopens in @q have
2025 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2026 * return the current flags.
2027 */
2028static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2029{
2030 BlockReopenQueueEntry *entry;
2031
2032 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002033 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002034 if (entry->state.bs == bs) {
2035 return entry->state.flags;
2036 }
2037 }
2038 }
2039
2040 return bs->open_flags;
2041}
2042
2043/* Returns whether the image file can be written to after the reopen queue @q
2044 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002045static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2046 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002047{
2048 int flags = bdrv_reopen_get_flags(q, bs);
2049
2050 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2051}
2052
Max Reitzcc022142018-06-06 21:37:00 +02002053/*
2054 * Return whether the BDS can be written to. This is not necessarily
2055 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2056 * be written to but do not count as read-only images.
2057 */
2058bool bdrv_is_writable(BlockDriverState *bs)
2059{
2060 return bdrv_is_writable_after_reopen(bs, NULL);
2061}
2062
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002063static char *bdrv_child_user_desc(BdrvChild *c)
2064{
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002065 return c->klass->get_parent_desc(c);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002066}
2067
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002068/*
2069 * Check that @a allows everything that @b needs. @a and @b must reference same
2070 * child node.
2071 */
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002072static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2073{
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002074 const char *child_bs_name;
2075 g_autofree char *a_user = NULL;
2076 g_autofree char *b_user = NULL;
2077 g_autofree char *perms = NULL;
2078
2079 assert(a->bs);
2080 assert(a->bs == b->bs);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002081
2082 if ((b->perm & a->shared_perm) == b->perm) {
2083 return true;
2084 }
2085
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002086 child_bs_name = bdrv_get_node_name(b->bs);
2087 a_user = bdrv_child_user_desc(a);
2088 b_user = bdrv_child_user_desc(b);
2089 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2090
2091 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2092 "both required by %s (uses node '%s' as '%s' child) and "
2093 "unshared by %s (uses node '%s' as '%s' child).",
2094 child_bs_name, perms,
2095 b_user, child_bs_name, b->name,
2096 a_user, child_bs_name, a->name);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002097
2098 return false;
2099}
2100
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002101static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002102{
2103 BdrvChild *a, *b;
2104
2105 /*
2106 * During the loop we'll look at each pair twice. That's correct because
2107 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2108 * directions.
2109 */
2110 QLIST_FOREACH(a, &bs->parents, next_parent) {
2111 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002112 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002113 continue;
2114 }
2115
2116 if (!bdrv_a_allow_b(a, b, errp)) {
2117 return true;
2118 }
2119 }
2120 }
2121
2122 return false;
2123}
2124
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002125static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002126 BdrvChild *c, BdrvChildRole role,
2127 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002128 uint64_t parent_perm, uint64_t parent_shared,
2129 uint64_t *nperm, uint64_t *nshared)
2130{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002131 assert(bs->drv && bs->drv->bdrv_child_perm);
Max Reitze5d8a402020-05-13 13:05:44 +02002132 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002133 parent_perm, parent_shared,
2134 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002135 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002136 if (child_bs && child_bs->force_share) {
2137 *nshared = BLK_PERM_ALL;
2138 }
2139}
2140
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002141/*
2142 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2143 * nodes that are already in the @list, of course) so that final list is
2144 * topologically sorted. Return the result (GSList @list object is updated, so
2145 * don't use old reference after function call).
2146 *
2147 * On function start @list must be already topologically sorted and for any node
2148 * in the @list the whole subtree of the node must be in the @list as well. The
2149 * simplest way to satisfy this criteria: use only result of
2150 * bdrv_topological_dfs() or NULL as @list parameter.
2151 */
2152static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2153 BlockDriverState *bs)
2154{
2155 BdrvChild *child;
2156 g_autoptr(GHashTable) local_found = NULL;
2157
2158 if (!found) {
2159 assert(!list);
2160 found = local_found = g_hash_table_new(NULL, NULL);
2161 }
2162
2163 if (g_hash_table_contains(found, bs)) {
2164 return list;
2165 }
2166 g_hash_table_add(found, bs);
2167
2168 QLIST_FOREACH(child, &bs->children, next) {
2169 list = bdrv_topological_dfs(list, found, child->bs);
2170 }
2171
2172 return g_slist_prepend(list, bs);
2173}
2174
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002175typedef struct BdrvChildSetPermState {
2176 BdrvChild *child;
2177 uint64_t old_perm;
2178 uint64_t old_shared_perm;
2179} BdrvChildSetPermState;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002180
2181static void bdrv_child_set_perm_abort(void *opaque)
2182{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002183 BdrvChildSetPermState *s = opaque;
2184
2185 s->child->perm = s->old_perm;
2186 s->child->shared_perm = s->old_shared_perm;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002187}
2188
2189static TransactionActionDrv bdrv_child_set_pem_drv = {
2190 .abort = bdrv_child_set_perm_abort,
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002191 .clean = g_free,
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002192};
2193
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002194static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2195 uint64_t shared, Transaction *tran)
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002196{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002197 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2198
2199 *s = (BdrvChildSetPermState) {
2200 .child = c,
2201 .old_perm = c->perm,
2202 .old_shared_perm = c->shared_perm,
2203 };
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002204
2205 c->perm = perm;
2206 c->shared_perm = shared;
2207
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002208 tran_add(tran, &bdrv_child_set_pem_drv, s);
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002209}
2210
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002211static void bdrv_drv_set_perm_commit(void *opaque)
2212{
2213 BlockDriverState *bs = opaque;
2214 uint64_t cumulative_perms, cumulative_shared_perms;
2215
2216 if (bs->drv->bdrv_set_perm) {
2217 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2218 &cumulative_shared_perms);
2219 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2220 }
2221}
2222
2223static void bdrv_drv_set_perm_abort(void *opaque)
2224{
2225 BlockDriverState *bs = opaque;
2226
2227 if (bs->drv->bdrv_abort_perm_update) {
2228 bs->drv->bdrv_abort_perm_update(bs);
2229 }
2230}
2231
2232TransactionActionDrv bdrv_drv_set_perm_drv = {
2233 .abort = bdrv_drv_set_perm_abort,
2234 .commit = bdrv_drv_set_perm_commit,
2235};
2236
2237static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2238 uint64_t shared_perm, Transaction *tran,
2239 Error **errp)
2240{
2241 if (!bs->drv) {
2242 return 0;
2243 }
2244
2245 if (bs->drv->bdrv_check_perm) {
2246 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2247 if (ret < 0) {
2248 return ret;
2249 }
2250 }
2251
2252 if (tran) {
2253 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2254 }
2255
2256 return 0;
2257}
2258
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002259typedef struct BdrvReplaceChildState {
2260 BdrvChild *child;
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002261 BdrvChild **childp;
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002262 BlockDriverState *old_bs;
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002263 bool free_empty_child;
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002264} BdrvReplaceChildState;
2265
2266static void bdrv_replace_child_commit(void *opaque)
2267{
2268 BdrvReplaceChildState *s = opaque;
2269
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002270 if (s->free_empty_child && !s->child->bs) {
2271 bdrv_child_free(s->child);
2272 }
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002273 bdrv_unref(s->old_bs);
2274}
2275
2276static void bdrv_replace_child_abort(void *opaque)
2277{
2278 BdrvReplaceChildState *s = opaque;
2279 BlockDriverState *new_bs = s->child->bs;
2280
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002281 /*
2282 * old_bs reference is transparently moved from @s to s->child.
2283 *
2284 * Pass &s->child here instead of s->childp, because:
2285 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2286 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2287 * will not modify s->child. From that perspective, it does not matter
2288 * whether we pass s->childp or &s->child.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002289 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2290 * it here.
2291 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2292 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2293 * must not pass a NULL *s->childp here.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002294 *
2295 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2296 * any case, there is no reason to pass it anyway.
2297 */
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002298 bdrv_replace_child_noperm(&s->child, s->old_bs, true);
2299 /*
2300 * The child was pre-existing, so s->old_bs must be non-NULL, and
2301 * s->child thus must not have been freed
2302 */
2303 assert(s->child != NULL);
2304 if (!new_bs) {
2305 /* As described above, *s->childp was cleared, so restore it */
2306 assert(s->childp != NULL);
2307 *s->childp = s->child;
2308 }
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002309 bdrv_unref(new_bs);
2310}
2311
2312static TransactionActionDrv bdrv_replace_child_drv = {
2313 .commit = bdrv_replace_child_commit,
2314 .abort = bdrv_replace_child_abort,
2315 .clean = g_free,
2316};
2317
2318/*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002319 * bdrv_replace_child_tran
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002320 *
2321 * Note: real unref of old_bs is done only on commit.
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002322 *
2323 * The function doesn't update permissions, caller is responsible for this.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002324 *
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002325 * (*childp)->bs must not be NULL.
2326 *
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002327 * Note that if new_bs == NULL, @childp is stored in a state object attached
2328 * to @tran, so that the old child can be reinstated in the abort handler.
2329 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2330 * transaction is committed or aborted.
2331 *
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002332 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2333 * freed (on commit). @free_empty_child should only be false if the
2334 * caller will free the BDrvChild themselves (which may be important
2335 * if this is in turn called in another transactional context).
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002336 */
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002337static void bdrv_replace_child_tran(BdrvChild **childp,
2338 BlockDriverState *new_bs,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002339 Transaction *tran,
2340 bool free_empty_child)
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002341{
2342 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2343 *s = (BdrvReplaceChildState) {
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002344 .child = *childp,
2345 .childp = new_bs == NULL ? childp : NULL,
2346 .old_bs = (*childp)->bs,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002347 .free_empty_child = free_empty_child,
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002348 };
2349 tran_add(tran, &bdrv_replace_child_drv, s);
2350
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002351 /* The abort handler relies on this */
2352 assert(s->old_bs != NULL);
2353
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002354 if (new_bs) {
2355 bdrv_ref(new_bs);
2356 }
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002357 /*
2358 * Pass free_empty_child=false, we will free the child (if
2359 * necessary) in bdrv_replace_child_commit() (if our
2360 * @free_empty_child parameter was true).
2361 */
2362 bdrv_replace_child_noperm(childp, new_bs, false);
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002363 /* old_bs reference is transparently moved from *childp to @s */
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002364}
2365
Kevin Wolf33a610c2016-12-15 13:04:20 +01002366/*
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002367 * Refresh permissions in @bs subtree. The function is intended to be called
2368 * after some graph modification that was done without permission update.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002369 */
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002370static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2371 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002372{
2373 BlockDriver *drv = bs->drv;
2374 BdrvChild *c;
2375 int ret;
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002376 uint64_t cumulative_perms, cumulative_shared_perms;
2377
2378 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002379
2380 /* Write permissions never work with read-only images */
2381 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002382 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002383 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002384 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2385 error_setg(errp, "Block node is read-only");
2386 } else {
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002387 error_setg(errp, "Read-only block node '%s' cannot support "
2388 "read-write users", bdrv_get_node_name(bs));
Max Reitz481e0ee2019-05-15 22:15:00 +02002389 }
2390
Kevin Wolf33a610c2016-12-15 13:04:20 +01002391 return -EPERM;
2392 }
2393
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002394 /*
2395 * Unaligned requests will automatically be aligned to bl.request_alignment
2396 * and without RESIZE we can't extend requests to write to space beyond the
2397 * end of the image, so it's required that the image size is aligned.
2398 */
2399 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2400 !(cumulative_perms & BLK_PERM_RESIZE))
2401 {
2402 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2403 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2404 "Image size is not a multiple of request "
2405 "alignment");
2406 return -EPERM;
2407 }
2408 }
2409
Kevin Wolf33a610c2016-12-15 13:04:20 +01002410 /* Check this node */
2411 if (!drv) {
2412 return 0;
2413 }
2414
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002415 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002416 errp);
2417 if (ret < 0) {
2418 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002419 }
2420
Kevin Wolf78e421c2016-12-20 23:25:12 +01002421 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002422 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002423 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002424 return 0;
2425 }
2426
2427 /* Check all children */
2428 QLIST_FOREACH(c, &bs->children, next) {
2429 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002430
Max Reitze5d8a402020-05-13 13:05:44 +02002431 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002432 cumulative_perms, cumulative_shared_perms,
2433 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002434 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002435 }
2436
2437 return 0;
2438}
2439
Vladimir Sementsov-Ogievskiy25409802021-04-28 18:18:00 +03002440static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2441 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002442{
2443 int ret;
2444 BlockDriverState *bs;
2445
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002446 for ( ; list; list = list->next) {
2447 bs = list->data;
2448
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002449 if (bdrv_parent_perms_conflict(bs, errp)) {
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002450 return -EINVAL;
2451 }
2452
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002453 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002454 if (ret < 0) {
2455 return ret;
2456 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002457 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002458
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002459 return 0;
2460}
2461
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002462void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2463 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002464{
2465 BdrvChild *c;
2466 uint64_t cumulative_perms = 0;
2467 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2468
2469 QLIST_FOREACH(c, &bs->parents, next_parent) {
2470 cumulative_perms |= c->perm;
2471 cumulative_shared_perms &= c->shared_perm;
2472 }
2473
2474 *perm = cumulative_perms;
2475 *shared_perm = cumulative_shared_perms;
2476}
2477
Fam Zheng51761962017-05-03 00:35:36 +08002478char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002479{
2480 struct perm_name {
2481 uint64_t perm;
2482 const char *name;
2483 } permissions[] = {
2484 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2485 { BLK_PERM_WRITE, "write" },
2486 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2487 { BLK_PERM_RESIZE, "resize" },
Kevin Wolfd0833192017-01-16 18:26:20 +01002488 { 0, NULL }
2489 };
2490
Alberto Garciae2a74232020-01-10 18:15:18 +01002491 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002492 struct perm_name *p;
2493
2494 for (p = permissions; p->name; p++) {
2495 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002496 if (result->len > 0) {
2497 g_string_append(result, ", ");
2498 }
2499 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002500 }
2501 }
2502
Alberto Garciae2a74232020-01-10 18:15:18 +01002503 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002504}
2505
Kevin Wolf33a610c2016-12-15 13:04:20 +01002506
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002507static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002508{
2509 int ret;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002510 Transaction *tran = tran_new();
2511 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002512
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002513 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2514 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002515
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002516 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002517}
2518
Kevin Wolf33a610c2016-12-15 13:04:20 +01002519int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2520 Error **errp)
2521{
Max Reitz10467792019-05-22 19:03:51 +02002522 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002523 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002524 int ret;
2525
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002526 bdrv_child_set_perm(c, perm, shared, tran);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002527
2528 ret = bdrv_refresh_perms(c->bs, &local_err);
2529
2530 tran_finalize(tran, ret);
2531
Kevin Wolf33a610c2016-12-15 13:04:20 +01002532 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002533 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2534 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002535 error_propagate(errp, local_err);
2536 } else {
2537 /*
2538 * Our caller may intend to only loosen restrictions and
2539 * does not expect this function to fail. Errors are not
2540 * fatal in such a case, so we can just hide them from our
2541 * caller.
2542 */
2543 error_free(local_err);
2544 ret = 0;
2545 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002546 }
2547
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002548 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002549}
2550
Max Reitzc1087f12019-05-22 19:03:46 +02002551int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2552{
2553 uint64_t parent_perms, parent_shared;
2554 uint64_t perms, shared;
2555
2556 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002557 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002558 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002559
2560 return bdrv_child_try_set_perm(c, perms, shared, errp);
2561}
2562
Max Reitz87278af2020-05-13 13:05:40 +02002563/*
2564 * Default implementation for .bdrv_child_perm() for block filters:
2565 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2566 * filtered child.
2567 */
2568static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002569 BdrvChildRole role,
2570 BlockReopenQueue *reopen_queue,
2571 uint64_t perm, uint64_t shared,
2572 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002573{
Kevin Wolfe444fa82019-08-02 15:59:41 +02002574 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2575 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002576}
2577
Max Reitz70082db2020-05-13 13:05:26 +02002578static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002579 BdrvChildRole role,
2580 BlockReopenQueue *reopen_queue,
2581 uint64_t perm, uint64_t shared,
2582 uint64_t *nperm, uint64_t *nshared)
2583{
Max Reitze5d8a402020-05-13 13:05:44 +02002584 assert(role & BDRV_CHILD_COW);
Max Reitz70082db2020-05-13 13:05:26 +02002585
2586 /*
2587 * We want consistent read from backing files if the parent needs it.
2588 * No other operations are performed on backing files.
2589 */
2590 perm &= BLK_PERM_CONSISTENT_READ;
2591
2592 /*
2593 * If the parent can deal with changing data, we're okay with a
2594 * writable and resizable backing file.
2595 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2596 */
2597 if (shared & BLK_PERM_WRITE) {
2598 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2599 } else {
2600 shared = 0;
2601 }
2602
Vladimir Sementsov-Ogievskiy64631f32021-09-02 12:37:54 +03002603 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
Max Reitz70082db2020-05-13 13:05:26 +02002604
2605 if (bs->open_flags & BDRV_O_INACTIVE) {
2606 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2607 }
2608
2609 *nperm = perm;
2610 *nshared = shared;
2611}
2612
Max Reitz6f838a42020-05-13 13:05:27 +02002613static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002614 BdrvChildRole role,
2615 BlockReopenQueue *reopen_queue,
2616 uint64_t perm, uint64_t shared,
2617 uint64_t *nperm, uint64_t *nshared)
2618{
2619 int flags;
2620
Max Reitze5d8a402020-05-13 13:05:44 +02002621 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002622
2623 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2624
2625 /*
2626 * Apart from the modifications below, the same permissions are
2627 * forwarded and left alone as for filters
2628 */
Max Reitze5d8a402020-05-13 13:05:44 +02002629 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002630 perm, shared, &perm, &shared);
2631
Max Reitzf8890542020-05-13 13:05:28 +02002632 if (role & BDRV_CHILD_METADATA) {
2633 /* Format drivers may touch metadata even if the guest doesn't write */
2634 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2635 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2636 }
2637
2638 /*
2639 * bs->file always needs to be consistent because of the
2640 * metadata. We can never allow other users to resize or write
2641 * to it.
2642 */
2643 if (!(flags & BDRV_O_NO_IO)) {
2644 perm |= BLK_PERM_CONSISTENT_READ;
2645 }
2646 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002647 }
2648
Max Reitzf8890542020-05-13 13:05:28 +02002649 if (role & BDRV_CHILD_DATA) {
2650 /*
2651 * Technically, everything in this block is a subset of the
2652 * BDRV_CHILD_METADATA path taken above, and so this could
2653 * be an "else if" branch. However, that is not obvious, and
2654 * this function is not performance critical, therefore we let
2655 * this be an independent "if".
2656 */
2657
2658 /*
2659 * We cannot allow other users to resize the file because the
2660 * format driver might have some assumptions about the size
2661 * (e.g. because it is stored in metadata, or because the file
2662 * is split into fixed-size data files).
2663 */
2664 shared &= ~BLK_PERM_RESIZE;
2665
2666 /*
2667 * WRITE_UNCHANGED often cannot be performed as such on the
2668 * data file. For example, the qcow2 driver may still need to
2669 * write copied clusters on copy-on-read.
2670 */
2671 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2672 perm |= BLK_PERM_WRITE;
2673 }
2674
2675 /*
2676 * If the data file is written to, the format driver may
2677 * expect to be able to resize it by writing beyond the EOF.
2678 */
2679 if (perm & BLK_PERM_WRITE) {
2680 perm |= BLK_PERM_RESIZE;
2681 }
Max Reitz6f838a42020-05-13 13:05:27 +02002682 }
Max Reitz6f838a42020-05-13 13:05:27 +02002683
2684 if (bs->open_flags & BDRV_O_INACTIVE) {
2685 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2686 }
2687
2688 *nperm = perm;
2689 *nshared = shared;
2690}
2691
Max Reitz2519f542020-05-13 13:05:29 +02002692void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002693 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002694 uint64_t perm, uint64_t shared,
2695 uint64_t *nperm, uint64_t *nshared)
2696{
Max Reitz2519f542020-05-13 13:05:29 +02002697 if (role & BDRV_CHILD_FILTERED) {
2698 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2699 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002700 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002701 perm, shared, nperm, nshared);
2702 } else if (role & BDRV_CHILD_COW) {
2703 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002704 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002705 perm, shared, nperm, nshared);
2706 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002707 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002708 perm, shared, nperm, nshared);
2709 } else {
2710 g_assert_not_reached();
2711 }
2712}
2713
Max Reitz7b1d9c42019-11-08 13:34:51 +01002714uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2715{
2716 static const uint64_t permissions[] = {
2717 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2718 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2719 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2720 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
Max Reitz7b1d9c42019-11-08 13:34:51 +01002721 };
2722
2723 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2724 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2725
2726 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2727
2728 return permissions[qapi_perm];
2729}
2730
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002731/**
2732 * Replace (*childp)->bs by @new_bs.
2733 *
2734 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2735 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2736 * BdrvChild.bs should generally immediately be followed by the
2737 * BdrvChild pointer being cleared as well.
2738 *
2739 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2740 * freed. @free_empty_child should only be false if the caller will
2741 * free the BdrvChild themselves (this may be important in a
2742 * transactional context, where it may only be freed on commit).
2743 */
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002744static void bdrv_replace_child_noperm(BdrvChild **childp,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002745 BlockDriverState *new_bs,
2746 bool free_empty_child)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002747{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002748 BdrvChild *child = *childp;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002749 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002750 int new_bs_quiesce_counter;
2751 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002752
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002753 assert(!child->frozen);
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02002754 assert(old_bs != new_bs);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002755
Fam Zhengbb2614e2017-04-07 14:54:10 +08002756 if (old_bs && new_bs) {
2757 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2758 }
Max Reitzdebc2922019-07-22 15:33:44 +02002759
2760 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2761 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2762
2763 /*
2764 * If the new child node is drained but the old one was not, flush
2765 * all outstanding requests to the old child node.
2766 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002767 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002768 bdrv_parent_drained_begin_single(child, true);
2769 drain_saldo--;
2770 }
2771
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002772 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002773 /* Detach first so that the recursive drain sections coming from @child
2774 * are already gone and we only end the drain sections that came from
2775 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002776 if (child->klass->detach) {
2777 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002778 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002779 QLIST_REMOVE(child, next_parent);
2780 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002781
2782 child->bs = new_bs;
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002783 if (!new_bs) {
2784 *childp = NULL;
2785 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002786
2787 if (new_bs) {
2788 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002789
2790 /*
2791 * Detaching the old node may have led to the new node's
2792 * quiesce_counter having been decreased. Not a problem, we
2793 * just need to recognize this here and then invoke
2794 * drained_end appropriately more often.
2795 */
2796 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2797 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002798
Kevin Wolfd736f112017-12-18 16:05:48 +01002799 /* Attach only after starting new drained sections, so that recursive
2800 * drain sections coming from @child don't get an extra .drained_begin
2801 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002802 if (child->klass->attach) {
2803 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002804 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002805 }
Max Reitzdebc2922019-07-22 15:33:44 +02002806
2807 /*
2808 * If the old child node was drained but the new one is not, allow
2809 * requests to come in only after the new node has been attached.
2810 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002811 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002812 bdrv_parent_drained_end_single(child);
2813 drain_saldo++;
2814 }
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002815
2816 if (free_empty_child && !child->bs) {
2817 bdrv_child_free(child);
2818 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002819}
2820
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002821/**
2822 * Free the given @child.
2823 *
2824 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2825 * unused (i.e. not in a children list).
2826 */
2827static void bdrv_child_free(BdrvChild *child)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002828{
2829 assert(!child->bs);
Hanna Reitza2253692021-11-15 15:53:58 +01002830 assert(!child->next.le_prev); /* not in children list */
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002831
2832 g_free(child->name);
2833 g_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002834}
2835
2836typedef struct BdrvAttachChildCommonState {
2837 BdrvChild **child;
2838 AioContext *old_parent_ctx;
2839 AioContext *old_child_ctx;
2840} BdrvAttachChildCommonState;
2841
2842static void bdrv_attach_child_common_abort(void *opaque)
2843{
2844 BdrvAttachChildCommonState *s = opaque;
2845 BdrvChild *child = *s->child;
2846 BlockDriverState *bs = child->bs;
2847
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002848 /*
2849 * Pass free_empty_child=false, because we still need the child
2850 * for the AioContext operations on the parent below; those
2851 * BdrvChildClass methods all work on a BdrvChild object, so we
2852 * need to keep it as an empty shell (after this function, it will
2853 * not be attached to any parent, and it will not have a .bs).
2854 */
2855 bdrv_replace_child_noperm(s->child, NULL, false);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002856
2857 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2858 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2859 }
2860
2861 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
Hanna Reitz26518062021-11-15 15:54:00 +01002862 GSList *ignore;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002863
Hanna Reitz26518062021-11-15 15:54:00 +01002864 /* No need to ignore `child`, because it has been detached already */
2865 ignore = NULL;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002866 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2867 &error_abort);
2868 g_slist_free(ignore);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002869
Hanna Reitz26518062021-11-15 15:54:00 +01002870 ignore = NULL;
2871 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002872 g_slist_free(ignore);
2873 }
2874
2875 bdrv_unref(bs);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002876 bdrv_child_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002877}
2878
2879static TransactionActionDrv bdrv_attach_child_common_drv = {
2880 .abort = bdrv_attach_child_common_abort,
2881 .clean = g_free,
2882};
2883
2884/*
2885 * Common part of attaching bdrv child to bs or to blk or to job
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002886 *
2887 * Resulting new child is returned through @child.
2888 * At start *@child must be NULL.
2889 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2890 * NULL on abort(). So referenced variable must live at least until transaction
2891 * end.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002892 *
2893 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002894 */
2895static int bdrv_attach_child_common(BlockDriverState *child_bs,
2896 const char *child_name,
2897 const BdrvChildClass *child_class,
2898 BdrvChildRole child_role,
2899 uint64_t perm, uint64_t shared_perm,
2900 void *opaque, BdrvChild **child,
2901 Transaction *tran, Error **errp)
2902{
2903 BdrvChild *new_child;
2904 AioContext *parent_ctx;
2905 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2906
2907 assert(child);
2908 assert(*child == NULL);
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002909 assert(child_class->get_parent_desc);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002910
2911 new_child = g_new(BdrvChild, 1);
2912 *new_child = (BdrvChild) {
2913 .bs = NULL,
2914 .name = g_strdup(child_name),
2915 .klass = child_class,
2916 .role = child_role,
2917 .perm = perm,
2918 .shared_perm = shared_perm,
2919 .opaque = opaque,
2920 };
2921
2922 /*
2923 * If the AioContexts don't match, first try to move the subtree of
2924 * child_bs into the AioContext of the new parent. If this doesn't work,
2925 * try moving the parent into the AioContext of child_bs instead.
2926 */
2927 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2928 if (child_ctx != parent_ctx) {
2929 Error *local_err = NULL;
2930 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2931
2932 if (ret < 0 && child_class->can_set_aio_ctx) {
2933 GSList *ignore = g_slist_prepend(NULL, new_child);
2934 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2935 NULL))
2936 {
2937 error_free(local_err);
2938 ret = 0;
2939 g_slist_free(ignore);
2940 ignore = g_slist_prepend(NULL, new_child);
2941 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2942 }
2943 g_slist_free(ignore);
2944 }
2945
2946 if (ret < 0) {
2947 error_propagate(errp, local_err);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002948 bdrv_child_free(new_child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002949 return ret;
2950 }
2951 }
2952
2953 bdrv_ref(child_bs);
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002954 bdrv_replace_child_noperm(&new_child, child_bs, true);
2955 /* child_bs was non-NULL, so new_child must not have been freed */
2956 assert(new_child != NULL);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002957
2958 *child = new_child;
2959
2960 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
2961 *s = (BdrvAttachChildCommonState) {
2962 .child = child,
2963 .old_parent_ctx = parent_ctx,
2964 .old_child_ctx = child_ctx,
2965 };
2966 tran_add(tran, &bdrv_attach_child_common_drv, s);
2967
2968 return 0;
2969}
2970
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002971/*
2972 * Variable referenced by @child must live at least until transaction end.
2973 * (see bdrv_attach_child_common() doc for details)
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002974 *
2975 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002976 */
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002977static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
2978 BlockDriverState *child_bs,
2979 const char *child_name,
2980 const BdrvChildClass *child_class,
2981 BdrvChildRole child_role,
2982 BdrvChild **child,
2983 Transaction *tran,
2984 Error **errp)
2985{
2986 int ret;
2987 uint64_t perm, shared_perm;
2988
2989 assert(parent_bs->drv);
2990
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02002991 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
2992 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
2993 child_bs->node_name, child_name, parent_bs->node_name);
2994 return -EINVAL;
2995 }
2996
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002997 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2998 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2999 perm, shared_perm, &perm, &shared_perm);
3000
3001 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3002 child_role, perm, shared_perm, parent_bs,
3003 child, tran, errp);
3004 if (ret < 0) {
3005 return ret;
3006 }
3007
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003008 return 0;
3009}
3010
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003011static void bdrv_detach_child(BdrvChild **childp)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003012{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003013 BlockDriverState *old_bs = (*childp)->bs;
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003014
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01003015 bdrv_replace_child_noperm(childp, NULL, true);
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003016
3017 if (old_bs) {
3018 /*
3019 * Update permissions for old node. We're just taking a parent away, so
3020 * we're loosening restrictions. Errors of permission update are not
3021 * fatal in this case, ignore them.
3022 */
3023 bdrv_refresh_perms(old_bs, NULL);
3024
3025 /*
3026 * When the parent requiring a non-default AioContext is removed, the
3027 * node moves back to the main AioContext
3028 */
3029 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3030 }
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003031}
3032
Alberto Garciab441dc72019-05-13 16:46:18 +03003033/*
3034 * This function steals the reference to child_bs from the caller.
3035 * That reference is later dropped by bdrv_root_unref_child().
3036 *
3037 * On failure NULL is returned, errp is set and the reference to
3038 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003039 *
3040 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3041 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003042 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003043BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3044 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003045 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003046 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003047 uint64_t perm, uint64_t shared_perm,
3048 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003049{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003050 int ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003051 BdrvChild *child = NULL;
3052 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003053
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003054 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3055 child_role, perm, shared_perm, opaque,
3056 &child, tran, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003057 if (ret < 0) {
Kevin Wolfe878bb12021-05-03 13:05:54 +02003058 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003059 }
3060
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003061 ret = bdrv_refresh_perms(child_bs, errp);
Kevin Wolfdf581792015-06-15 11:53:47 +02003062
Kevin Wolfe878bb12021-05-03 13:05:54 +02003063out:
3064 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003065 /* child is unset on failure by bdrv_attach_child_common_abort() */
3066 assert((ret < 0) == !child);
3067
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003068 bdrv_unref(child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003069 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003070}
3071
Alberto Garciab441dc72019-05-13 16:46:18 +03003072/*
3073 * This function transfers the reference to child_bs from the caller
3074 * to parent_bs. That reference is later dropped by parent_bs on
3075 * bdrv_close() or if someone calls bdrv_unref_child().
3076 *
3077 * On failure NULL is returned, errp is set and the reference to
3078 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003079 *
3080 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3081 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003082 */
Wen Congyang98292c62016-05-10 15:36:38 +08003083BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3084 BlockDriverState *child_bs,
3085 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003086 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003087 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003088 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003089{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003090 int ret;
3091 BdrvChild *child = NULL;
3092 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003093
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003094 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3095 child_role, &child, tran, errp);
3096 if (ret < 0) {
3097 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003098 }
3099
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003100 ret = bdrv_refresh_perms(parent_bs, errp);
3101 if (ret < 0) {
3102 goto out;
3103 }
3104
3105out:
3106 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003107 /* child is unset on failure by bdrv_attach_child_common_abort() */
3108 assert((ret < 0) == !child);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003109
3110 bdrv_unref(child_bs);
3111
Kevin Wolff21d96d2016-03-08 13:47:46 +01003112 return child;
3113}
3114
Max Reitz7b99a262019-06-12 16:07:11 +02003115/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003116void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003117{
Kevin Wolf779020c2015-10-13 14:09:44 +02003118 BlockDriverState *child_bs;
3119
Kevin Wolff21d96d2016-03-08 13:47:46 +01003120 child_bs = child->bs;
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003121 bdrv_detach_child(&child);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003122 bdrv_unref(child_bs);
3123}
3124
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003125typedef struct BdrvSetInheritsFrom {
3126 BlockDriverState *bs;
3127 BlockDriverState *old_inherits_from;
3128} BdrvSetInheritsFrom;
3129
3130static void bdrv_set_inherits_from_abort(void *opaque)
3131{
3132 BdrvSetInheritsFrom *s = opaque;
3133
3134 s->bs->inherits_from = s->old_inherits_from;
3135}
3136
3137static TransactionActionDrv bdrv_set_inherits_from_drv = {
3138 .abort = bdrv_set_inherits_from_abort,
3139 .clean = g_free,
3140};
3141
3142/* @tran is allowed to be NULL. In this case no rollback is possible */
3143static void bdrv_set_inherits_from(BlockDriverState *bs,
3144 BlockDriverState *new_inherits_from,
3145 Transaction *tran)
3146{
3147 if (tran) {
3148 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3149
3150 *s = (BdrvSetInheritsFrom) {
3151 .bs = bs,
3152 .old_inherits_from = bs->inherits_from,
3153 };
3154
3155 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3156 }
3157
3158 bs->inherits_from = new_inherits_from;
3159}
3160
Max Reitz3cf746b2019-07-03 19:28:07 +02003161/**
3162 * Clear all inherits_from pointers from children and grandchildren of
3163 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003164 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003165 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003166static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3167 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003168{
Max Reitz3cf746b2019-07-03 19:28:07 +02003169 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003170
Max Reitz3cf746b2019-07-03 19:28:07 +02003171 if (child->bs->inherits_from == root) {
3172 /*
3173 * Remove inherits_from only when the last reference between root and
3174 * child->bs goes away.
3175 */
3176 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003177 if (c != child && c->bs == child->bs) {
3178 break;
3179 }
3180 }
3181 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003182 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003183 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003184 }
3185
Max Reitz3cf746b2019-07-03 19:28:07 +02003186 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003187 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003188 }
3189}
3190
Max Reitz7b99a262019-06-12 16:07:11 +02003191/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003192void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3193{
3194 if (child == NULL) {
3195 return;
3196 }
3197
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003198 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003199 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003200}
3201
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003202
3203static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3204{
3205 BdrvChild *c;
3206 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003207 if (c->klass->change_media) {
3208 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003209 }
3210 }
3211}
3212
Alberto Garcia0065c452018-10-31 18:16:37 +02003213/* Return true if you can reach parent going through child->inherits_from
3214 * recursively. If parent or child are NULL, return false */
3215static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3216 BlockDriverState *parent)
3217{
3218 while (child && child != parent) {
3219 child = child->inherits_from;
3220 }
3221
3222 return child != NULL;
3223}
3224
Kevin Wolf5db15a52015-09-14 15:33:33 +02003225/*
Max Reitz25191e52020-05-13 13:05:33 +02003226 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3227 * mostly used for COW backing children (role = COW), but also for
3228 * filtered children (role = FILTERED | PRIMARY).
3229 */
3230static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3231{
3232 if (bs->drv && bs->drv->is_filter) {
3233 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3234 } else {
3235 return BDRV_CHILD_COW;
3236 }
3237}
3238
3239/*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003240 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3241 * callers which don't need their own reference any more must call bdrv_unref().
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003242 *
3243 * Function doesn't update permissions, caller is responsible for this.
Kevin Wolf5db15a52015-09-14 15:33:33 +02003244 */
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003245static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3246 BlockDriverState *child_bs,
3247 bool is_backing,
3248 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003249{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003250 int ret = 0;
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003251 bool update_inherits_from =
3252 bdrv_inherits_from_recursive(child_bs, parent_bs);
3253 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3254 BdrvChildRole role;
Alberto Garcia0065c452018-10-31 18:16:37 +02003255
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003256 if (!parent_bs->drv) {
3257 /*
3258 * Node without drv is an object without a class :/. TODO: finally fix
3259 * qcow2 driver to never clear bs->drv and implement format corruption
3260 * handling in other way.
3261 */
3262 error_setg(errp, "Node corrupted");
3263 return -EINVAL;
3264 }
3265
3266 if (child && child->frozen) {
3267 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3268 child->name, parent_bs->node_name, child->bs->node_name);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003269 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003270 }
3271
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03003272 if (is_backing && !parent_bs->drv->is_filter &&
3273 !parent_bs->drv->supports_backing)
3274 {
3275 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3276 "files", parent_bs->drv->format_name, parent_bs->node_name);
3277 return -EINVAL;
3278 }
3279
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003280 if (parent_bs->drv->is_filter) {
3281 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3282 } else if (is_backing) {
3283 role = BDRV_CHILD_COW;
3284 } else {
3285 /*
3286 * We only can use same role as it is in existing child. We don't have
3287 * infrastructure to determine role of file child in generic way
3288 */
3289 if (!child) {
3290 error_setg(errp, "Cannot set file child to format node without "
3291 "file child");
3292 return -EINVAL;
3293 }
3294 role = child->role;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003295 }
3296
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003297 if (child) {
3298 bdrv_unset_inherits_from(parent_bs, child, tran);
3299 bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3300 }
3301
3302 if (!child_bs) {
Fam Zheng8d24cce2014-05-23 21:29:45 +08003303 goto out;
3304 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003305
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003306 ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3307 is_backing ? "backing" : "file",
3308 &child_of_bds, role,
3309 is_backing ? &parent_bs->backing :
3310 &parent_bs->file,
3311 tran, errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003312 if (ret < 0) {
3313 return ret;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003314 }
3315
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003316
3317 /*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003318 * If inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003319 * point directly to bs (else it will become NULL).
3320 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003321 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003322 bdrv_set_inherits_from(child_bs, parent_bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003323 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003324
Fam Zheng8d24cce2014-05-23 21:29:45 +08003325out:
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003326 bdrv_refresh_limits(parent_bs, tran, NULL);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003327
3328 return 0;
3329}
3330
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003331static int bdrv_set_backing_noperm(BlockDriverState *bs,
3332 BlockDriverState *backing_hd,
3333 Transaction *tran, Error **errp)
3334{
3335 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3336}
3337
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003338int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3339 Error **errp)
3340{
3341 int ret;
3342 Transaction *tran = tran_new();
3343
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003344 bdrv_drained_begin(bs);
3345
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003346 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3347 if (ret < 0) {
3348 goto out;
3349 }
3350
3351 ret = bdrv_refresh_perms(bs, errp);
3352out:
3353 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003354
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003355 bdrv_drained_end(bs);
3356
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003357 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003358}
3359
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003360/*
3361 * Opens the backing file for a BlockDriverState if not yet open
3362 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003363 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3364 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3365 * itself, all options starting with "${bdref_key}." are considered part of the
3366 * BlockdevRef.
3367 *
3368 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003369 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003370int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3371 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003372{
Max Reitz6b6833c2019-02-01 20:29:15 +01003373 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003374 char *bdref_key_dot;
3375 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003376 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003377 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003378 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003379 QDict *options;
3380 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003381 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003382
Kevin Wolf760e0062015-06-17 14:55:21 +02003383 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003384 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003385 }
3386
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003387 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003388 if (parent_options == NULL) {
3389 tmp_parent_options = qdict_new();
3390 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003391 }
3392
Paolo Bonzini9156df12012-10-18 16:49:17 +02003393 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003394
3395 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3396 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3397 g_free(bdref_key_dot);
3398
Markus Armbruster129c7d12017-03-30 19:43:12 +02003399 /*
3400 * Caution: while qdict_get_try_str() is fine, getting non-string
3401 * types would require more care. When @parent_options come from
3402 * -blockdev or blockdev_add, its members are typed according to
3403 * the QAPI schema, but when they come from -drive, they're all
3404 * QString.
3405 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003406 reference = qdict_get_try_str(parent_options, bdref_key);
3407 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003408 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003409 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003410 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003411 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003412 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003413 if (qdict_size(options) == 0) {
3414 /* If the user specifies options that do not modify the
3415 * backing file's behavior, we might still consider it the
3416 * implicit backing file. But it's easier this way, and
3417 * just specifying some of the backing BDS's options is
3418 * only possible with -drive anyway (otherwise the QAPI
3419 * schema forces the user to specify everything). */
3420 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3421 }
3422
Max Reitz6b6833c2019-02-01 20:29:15 +01003423 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003424 if (local_err) {
3425 ret = -EINVAL;
3426 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003427 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003428 goto free_exit;
3429 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003430 }
3431
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003432 if (!bs->drv || !bs->drv->supports_backing) {
3433 ret = -EINVAL;
3434 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003435 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003436 goto free_exit;
3437 }
3438
Peter Krempa6bff5972017-10-12 16:14:10 +02003439 if (!reference &&
3440 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003441 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003442 }
3443
Max Reitz6b6833c2019-02-01 20:29:15 +01003444 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003445 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003446 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003447 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003448 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003449 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003450 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003451 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003452
Max Reitz998c2012019-02-01 20:29:08 +01003453 if (implicit_backing) {
3454 bdrv_refresh_filename(backing_hd);
3455 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3456 backing_hd->filename);
3457 }
3458
Kevin Wolf5db15a52015-09-14 15:33:33 +02003459 /* Hook up the backing file link; drop our reference, bs owns the
3460 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003461 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003462 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003463 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003464 goto free_exit;
3465 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003466
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003467 qdict_del(parent_options, bdref_key);
3468
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003469free_exit:
3470 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003471 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003472 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003473}
3474
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003475static BlockDriverState *
3476bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003477 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003478 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003479{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003480 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003481 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003482 char *bdref_key_dot;
3483 const char *reference;
3484
Max Reitzbd86fb92020-05-13 13:05:13 +02003485 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003486
Max Reitzda557aa2013-12-20 19:28:11 +01003487 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3488 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3489 g_free(bdref_key_dot);
3490
Markus Armbruster129c7d12017-03-30 19:43:12 +02003491 /*
3492 * Caution: while qdict_get_try_str() is fine, getting non-string
3493 * types would require more care. When @options come from
3494 * -blockdev or blockdev_add, its members are typed according to
3495 * the QAPI schema, but when they come from -drive, they're all
3496 * QString.
3497 */
Max Reitzda557aa2013-12-20 19:28:11 +01003498 reference = qdict_get_try_str(options, bdref_key);
3499 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003500 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003501 error_setg(errp, "A block device must be specified for \"%s\"",
3502 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003503 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003504 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003505 goto done;
3506 }
3507
Max Reitz5b363932016-05-17 16:41:31 +02003508 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003509 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003510 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003511 goto done;
3512 }
3513
Max Reitzda557aa2013-12-20 19:28:11 +01003514done:
3515 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003516 return bs;
3517}
3518
3519/*
3520 * Opens a disk image whose options are given as BlockdevRef in another block
3521 * device's options.
3522 *
3523 * If allow_none is true, no image will be opened if filename is false and no
3524 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3525 *
3526 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3527 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3528 * itself, all options starting with "${bdref_key}." are considered part of the
3529 * BlockdevRef.
3530 *
3531 * The BlockdevRef will be removed from the options QDict.
3532 */
3533BdrvChild *bdrv_open_child(const char *filename,
3534 QDict *options, const char *bdref_key,
3535 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003536 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003537 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003538 bool allow_none, Error **errp)
3539{
3540 BlockDriverState *bs;
3541
Max Reitzbd86fb92020-05-13 13:05:13 +02003542 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003543 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003544 if (bs == NULL) {
3545 return NULL;
3546 }
3547
Max Reitz258b7762020-05-13 13:05:15 +02003548 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3549 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003550}
3551
Max Reitzbd86fb92020-05-13 13:05:13 +02003552/*
3553 * TODO Future callers may need to specify parent/child_class in order for
3554 * option inheritance to work. Existing callers use it for the root node.
3555 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003556BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3557{
3558 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003559 QObject *obj = NULL;
3560 QDict *qdict = NULL;
3561 const char *reference = NULL;
3562 Visitor *v = NULL;
3563
3564 if (ref->type == QTYPE_QSTRING) {
3565 reference = ref->u.reference;
3566 } else {
3567 BlockdevOptions *options = &ref->u.definition;
3568 assert(ref->type == QTYPE_QDICT);
3569
3570 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003571 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003572 visit_complete(v, &obj);
3573
Max Reitz7dc847e2018-02-24 16:40:29 +01003574 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003575 qdict_flatten(qdict);
3576
3577 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3578 * compatibility with other callers) rather than what we want as the
3579 * real defaults. Apply the defaults here instead. */
3580 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3581 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3582 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003583 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3584
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003585 }
3586
Max Reitz272c02e2020-05-13 13:05:17 +02003587 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003588 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003589 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003590 visit_free(v);
3591 return bs;
3592}
3593
Max Reitz66836182016-05-17 16:41:27 +02003594static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3595 int flags,
3596 QDict *snapshot_options,
3597 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003598{
3599 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003600 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003601 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003602 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003603 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003604 int ret;
3605
3606 /* if snapshot, we create a temporary backing file and open it
3607 instead of opening 'filename' directly */
3608
3609 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003610 total_size = bdrv_getlength(bs);
3611 if (total_size < 0) {
3612 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003613 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003614 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003615
3616 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003617 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003618 if (ret < 0) {
3619 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003620 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003621 }
3622
Max Reitzef810432014-12-02 18:32:42 +01003623 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003624 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003625 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003626 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003627 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003628 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003629 error_prepend(errp, "Could not create temporary overlay '%s': ",
3630 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003631 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003632 }
3633
Kevin Wolf73176be2016-03-07 13:02:15 +01003634 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003635 qdict_put_str(snapshot_options, "file.driver", "file");
3636 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3637 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003638
Max Reitz5b363932016-05-17 16:41:31 +02003639 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003640 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003641 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003642 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003643 }
3644
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003645 ret = bdrv_append(bs_snapshot, bs, errp);
3646 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003647 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003648 goto out;
3649 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003650
3651out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003652 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003653 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003654 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003655}
3656
Max Reitzda557aa2013-12-20 19:28:11 +01003657/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003658 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003659 *
3660 * options is a QDict of options to pass to the block drivers, or NULL for an
3661 * empty set of options. The reference to the QDict belongs to the block layer
3662 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003663 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003664 *
3665 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3666 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003667 *
3668 * The reference parameter may be used to specify an existing block device which
3669 * should be opened. If specified, neither options nor a filename may be given,
3670 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003671 */
Max Reitz5b363932016-05-17 16:41:31 +02003672static BlockDriverState *bdrv_open_inherit(const char *filename,
3673 const char *reference,
3674 QDict *options, int flags,
3675 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003676 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003677 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003678 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003679{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003680 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003681 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003682 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003683 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003684 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003685 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003686 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003687 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003688 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003689 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003690
Max Reitzbd86fb92020-05-13 13:05:13 +02003691 assert(!child_class || !flags);
3692 assert(!child_class == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01003693
Max Reitzddf56362014-02-18 18:33:06 +01003694 if (reference) {
3695 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003696 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003697
Max Reitzddf56362014-02-18 18:33:06 +01003698 if (filename || options_non_empty) {
3699 error_setg(errp, "Cannot reference an existing block device with "
3700 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003701 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003702 }
3703
3704 bs = bdrv_lookup_bs(reference, reference, errp);
3705 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003706 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003707 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003708
Max Reitzddf56362014-02-18 18:33:06 +01003709 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003710 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003711 }
3712
Max Reitz5b363932016-05-17 16:41:31 +02003713 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003714
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003715 /* NULL means an empty set of options */
3716 if (options == NULL) {
3717 options = qdict_new();
3718 }
3719
Kevin Wolf145f5982015-05-08 16:15:03 +02003720 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003721 parse_json_protocol(options, &filename, &local_err);
3722 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003723 goto fail;
3724 }
3725
Kevin Wolf145f5982015-05-08 16:15:03 +02003726 bs->explicit_options = qdict_clone_shallow(options);
3727
Max Reitzbd86fb92020-05-13 13:05:13 +02003728 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003729 bool parent_is_format;
3730
3731 if (parent->drv) {
3732 parent_is_format = parent->drv->is_format;
3733 } else {
3734 /*
3735 * parent->drv is not set yet because this node is opened for
3736 * (potential) format probing. That means that @parent is going
3737 * to be a format node.
3738 */
3739 parent_is_format = true;
3740 }
3741
Kevin Wolfbddcec32015-04-09 18:47:50 +02003742 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003743 child_class->inherit_options(child_role, parent_is_format,
3744 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003745 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003746 }
3747
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003748 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003749 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003750 goto fail;
3751 }
3752
Markus Armbruster129c7d12017-03-30 19:43:12 +02003753 /*
3754 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3755 * Caution: getting a boolean member of @options requires care.
3756 * When @options come from -blockdev or blockdev_add, members are
3757 * typed according to the QAPI schema, but when they come from
3758 * -drive, they're all QString.
3759 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003760 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3761 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3762 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3763 } else {
3764 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003765 }
3766
3767 if (flags & BDRV_O_SNAPSHOT) {
3768 snapshot_options = qdict_new();
3769 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3770 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003771 /* Let bdrv_backing_options() override "read-only" */
3772 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003773 bdrv_inherited_options(BDRV_CHILD_COW, true,
3774 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003775 }
3776
Kevin Wolf62392eb2015-04-24 16:38:02 +02003777 bs->open_flags = flags;
3778 bs->options = options;
3779 options = qdict_clone_shallow(options);
3780
Kevin Wolf76c591b2014-06-04 14:19:44 +02003781 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003782 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003783 drvname = qdict_get_try_str(options, "driver");
3784 if (drvname) {
3785 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003786 if (!drv) {
3787 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003788 goto fail;
3789 }
3790 }
3791
3792 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003793
Markus Armbruster129c7d12017-03-30 19:43:12 +02003794 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003795 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003796 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3797 (backing && *backing == '\0'))
3798 {
Max Reitz4f7be282018-02-24 16:40:33 +01003799 if (backing) {
3800 warn_report("Use of \"backing\": \"\" is deprecated; "
3801 "use \"backing\": null instead");
3802 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003803 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003804 qdict_del(bs->explicit_options, "backing");
3805 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003806 qdict_del(options, "backing");
3807 }
3808
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003809 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003810 * probing, the block drivers will do their own bdrv_open_child() for the
3811 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003812 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003813 BlockDriverState *file_bs;
3814
3815 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003816 &child_of_bds, BDRV_CHILD_IMAGE,
3817 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003818 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003819 goto fail;
3820 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003821 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003822 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3823 * looking at the header to guess the image format. This works even
3824 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003825 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003826 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003827 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003828 if (local_err) {
3829 goto fail;
3830 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003831
Eric Blake46f5ac22017-04-27 16:58:17 -05003832 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003833 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003834 }
3835
Kevin Wolf76c591b2014-06-04 14:19:44 +02003836 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003837 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003838 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003839 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003840 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003841 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003842 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003843 /*
3844 * This option update would logically belong in bdrv_fill_options(),
3845 * but we first need to open bs->file for the probing to work, while
3846 * opening bs->file already requires the (mostly) final set of options
3847 * so that cache mode etc. can be inherited.
3848 *
3849 * Adding the driver later is somewhat ugly, but it's not an option
3850 * that would ever be inherited, so it's correct. We just need to make
3851 * sure to update both bs->options (which has the full effective
3852 * options for bs) and options (which has file.* already removed).
3853 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003854 qdict_put_str(bs->options, "driver", drv->format_name);
3855 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003856 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003857 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003858 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003859 }
3860
Max Reitz53a29512015-03-19 14:53:16 -04003861 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3862 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3863 /* file must be NULL if a protocol BDS is about to be created
3864 * (the inverse results in an error message from bdrv_open_common()) */
3865 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3866
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003867 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003868 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003869 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003870 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003871 }
3872
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003873 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003874 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003875 file = NULL;
3876 }
3877
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003878 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003879 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003880 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003881 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003882 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003883 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003884 }
3885
Alberto Garcia50196d72018-09-06 12:37:03 +03003886 /* Remove all children options and references
3887 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003888 QLIST_FOREACH(child, &bs->children, next) {
3889 char *child_key_dot;
3890 child_key_dot = g_strdup_printf("%s.", child->name);
3891 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3892 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003893 qdict_del(bs->explicit_options, child->name);
3894 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003895 g_free(child_key_dot);
3896 }
3897
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003898 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003899 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003900 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003901 if (flags & BDRV_O_PROTOCOL) {
3902 error_setg(errp, "Block protocol '%s' doesn't support the option "
3903 "'%s'", drv->format_name, entry->key);
3904 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003905 error_setg(errp,
3906 "Block format '%s' does not support the option '%s'",
3907 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003908 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003909
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003910 goto close_and_fail;
3911 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003912
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003913 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003914
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003915 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003916 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003917
3918 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3919 * temporary snapshot afterwards. */
3920 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003921 BlockDriverState *snapshot_bs;
3922 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3923 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003924 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003925 if (local_err) {
3926 goto close_and_fail;
3927 }
Max Reitz5b363932016-05-17 16:41:31 +02003928 /* We are not going to return bs but the overlay on top of it
3929 * (snapshot_bs); thus, we have to drop the strong reference to bs
3930 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3931 * though, because the overlay still has a reference to it. */
3932 bdrv_unref(bs);
3933 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003934 }
3935
Max Reitz5b363932016-05-17 16:41:31 +02003936 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003937
Kevin Wolf8bfea152014-04-11 19:16:36 +02003938fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003939 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003940 qobject_unref(snapshot_options);
3941 qobject_unref(bs->explicit_options);
3942 qobject_unref(bs->options);
3943 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003944 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003945 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003946 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003947 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003948 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003949
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003950close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02003951 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003952 qobject_unref(snapshot_options);
3953 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003954 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003955 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003956}
3957
Max Reitz5b363932016-05-17 16:41:31 +02003958BlockDriverState *bdrv_open(const char *filename, const char *reference,
3959 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02003960{
Max Reitz5b363932016-05-17 16:41:31 +02003961 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02003962 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003963}
3964
Alberto Garciafaf116b2019-03-12 18:48:49 +02003965/* Return true if the NULL-terminated @list contains @str */
3966static bool is_str_in_list(const char *str, const char *const *list)
3967{
3968 if (str && list) {
3969 int i;
3970 for (i = 0; list[i] != NULL; i++) {
3971 if (!strcmp(str, list[i])) {
3972 return true;
3973 }
3974 }
3975 }
3976 return false;
3977}
3978
3979/*
3980 * Check that every option set in @bs->options is also set in
3981 * @new_opts.
3982 *
3983 * Options listed in the common_options list and in
3984 * @bs->drv->mutable_opts are skipped.
3985 *
3986 * Return 0 on success, otherwise return -EINVAL and set @errp.
3987 */
3988static int bdrv_reset_options_allowed(BlockDriverState *bs,
3989 const QDict *new_opts, Error **errp)
3990{
3991 const QDictEntry *e;
3992 /* These options are common to all block drivers and are handled
3993 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3994 const char *const common_options[] = {
3995 "node-name", "discard", "cache.direct", "cache.no-flush",
3996 "read-only", "auto-read-only", "detect-zeroes", NULL
3997 };
3998
3999 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4000 if (!qdict_haskey(new_opts, e->key) &&
4001 !is_str_in_list(e->key, common_options) &&
4002 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4003 error_setg(errp, "Option '%s' cannot be reset "
4004 "to its default value", e->key);
4005 return -EINVAL;
4006 }
4007 }
4008
4009 return 0;
4010}
4011
Jeff Codye971aa12012-09-20 15:13:19 -04004012/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004013 * Returns true if @child can be reached recursively from @bs
4014 */
4015static bool bdrv_recurse_has_child(BlockDriverState *bs,
4016 BlockDriverState *child)
4017{
4018 BdrvChild *c;
4019
4020 if (bs == child) {
4021 return true;
4022 }
4023
4024 QLIST_FOREACH(c, &bs->children, next) {
4025 if (bdrv_recurse_has_child(c->bs, child)) {
4026 return true;
4027 }
4028 }
4029
4030 return false;
4031}
4032
4033/*
Jeff Codye971aa12012-09-20 15:13:19 -04004034 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4035 * reopen of multiple devices.
4036 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004037 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04004038 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4039 * be created and initialized. This newly created BlockReopenQueue should be
4040 * passed back in for subsequent calls that are intended to be of the same
4041 * atomic 'set'.
4042 *
4043 * bs is the BlockDriverState to add to the reopen queue.
4044 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004045 * options contains the changed options for the associated bs
4046 * (the BlockReopenQueue takes ownership)
4047 *
Jeff Codye971aa12012-09-20 15:13:19 -04004048 * flags contains the open flags for the associated bs
4049 *
4050 * returns a pointer to bs_queue, which is either the newly allocated
4051 * bs_queue, or the existing bs_queue being used.
4052 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004053 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004054 */
Kevin Wolf28518102015-05-08 17:07:31 +02004055static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4056 BlockDriverState *bs,
4057 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02004058 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02004059 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004060 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02004061 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004062 int parent_flags,
4063 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04004064{
4065 assert(bs != NULL);
4066
4067 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02004068 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004069 QDict *old_options, *explicit_options, *options_copy;
4070 int flags;
4071 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004072
Kevin Wolf1a63a902017-12-06 20:24:44 +01004073 /* Make sure that the caller remembered to use a drained section. This is
4074 * important to avoid graph changes between the recursive queuing here and
4075 * bdrv_reopen_multiple(). */
4076 assert(bs->quiesce_counter > 0);
4077
Jeff Codye971aa12012-09-20 15:13:19 -04004078 if (bs_queue == NULL) {
4079 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004080 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04004081 }
4082
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004083 if (!options) {
4084 options = qdict_new();
4085 }
4086
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004087 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004088 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004089 if (bs == bs_entry->state.bs) {
4090 break;
4091 }
4092 }
4093
Kevin Wolf28518102015-05-08 17:07:31 +02004094 /*
4095 * Precedence of options:
4096 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004097 * 2. Retained from explicitly set options of bs
4098 * 3. Inherited from parent node
4099 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004100 */
4101
Kevin Wolf145f5982015-05-08 16:15:03 +02004102 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004103 if (bs_entry || keep_old_opts) {
4104 old_options = qdict_clone_shallow(bs_entry ?
4105 bs_entry->state.explicit_options :
4106 bs->explicit_options);
4107 bdrv_join_options(bs, options, old_options);
4108 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004109 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004110
4111 explicit_options = qdict_clone_shallow(options);
4112
Kevin Wolf28518102015-05-08 17:07:31 +02004113 /* Inherit from parent node */
4114 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004115 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004116 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004117 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004118 } else {
4119 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004120 }
4121
Alberto Garcia077e8e22019-03-12 18:48:44 +02004122 if (keep_old_opts) {
4123 /* Old values are used for options that aren't set yet */
4124 old_options = qdict_clone_shallow(bs->options);
4125 bdrv_join_options(bs, options, old_options);
4126 qobject_unref(old_options);
4127 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004128
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004129 /* We have the final set of options so let's update the flags */
4130 options_copy = qdict_clone_shallow(options);
4131 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4132 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4133 update_flags_from_options(&flags, opts);
4134 qemu_opts_del(opts);
4135 qobject_unref(options_copy);
4136
Kevin Wolffd452022017-08-03 17:02:59 +02004137 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004138 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004139 if (flags & BDRV_O_RDWR) {
4140 flags |= BDRV_O_ALLOW_RDWR;
4141 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004142
Kevin Wolf1857c972017-09-14 14:53:46 +02004143 if (!bs_entry) {
4144 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004145 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004146 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004147 qobject_unref(bs_entry->state.options);
4148 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004149 }
4150
4151 bs_entry->state.bs = bs;
4152 bs_entry->state.options = options;
4153 bs_entry->state.explicit_options = explicit_options;
4154 bs_entry->state.flags = flags;
4155
Alberto Garcia85466322019-03-12 18:48:45 +02004156 /*
4157 * If keep_old_opts is false then it means that unspecified
4158 * options must be reset to their original value. We don't allow
4159 * resetting 'backing' but we need to know if the option is
4160 * missing in order to decide if we have to return an error.
4161 */
4162 if (!keep_old_opts) {
4163 bs_entry->state.backing_missing =
4164 !qdict_haskey(options, "backing") &&
4165 !qdict_haskey(options, "backing.driver");
4166 }
4167
Kevin Wolf67251a32015-04-09 18:54:04 +02004168 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004169 QDict *new_child_options = NULL;
4170 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004171
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004172 /* reopen can only change the options of block devices that were
4173 * implicitly created and inherited options. For other (referenced)
4174 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004175 if (child->bs->inherits_from != bs) {
4176 continue;
4177 }
4178
Alberto Garcia85466322019-03-12 18:48:45 +02004179 /* Check if the options contain a child reference */
4180 if (qdict_haskey(options, child->name)) {
4181 const char *childref = qdict_get_try_str(options, child->name);
4182 /*
4183 * The current child must not be reopened if the child
4184 * reference is null or points to a different node.
4185 */
4186 if (g_strcmp0(childref, child->bs->node_name)) {
4187 continue;
4188 }
4189 /*
4190 * If the child reference points to the current child then
4191 * reopen it with its existing set of options (note that
4192 * it can still inherit new options from the parent).
4193 */
4194 child_keep_old = true;
4195 } else {
4196 /* Extract child options ("child-name.*") */
4197 char *child_key_dot = g_strdup_printf("%s.", child->name);
4198 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4199 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4200 g_free(child_key_dot);
4201 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004202
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004203 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004204 child->klass, child->role, bs->drv->is_format,
4205 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004206 }
4207
Jeff Codye971aa12012-09-20 15:13:19 -04004208 return bs_queue;
4209}
4210
Kevin Wolf28518102015-05-08 17:07:31 +02004211BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4212 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004213 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004214{
Max Reitz3cdc69d2020-05-13 13:05:18 +02004215 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4216 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004217}
4218
Alberto Garciaab5b52282021-07-08 13:47:05 +02004219void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4220{
4221 if (bs_queue) {
4222 BlockReopenQueueEntry *bs_entry, *next;
4223 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4224 qobject_unref(bs_entry->state.explicit_options);
4225 qobject_unref(bs_entry->state.options);
4226 g_free(bs_entry);
4227 }
4228 g_free(bs_queue);
4229 }
4230}
4231
Jeff Codye971aa12012-09-20 15:13:19 -04004232/*
4233 * Reopen multiple BlockDriverStates atomically & transactionally.
4234 *
4235 * The queue passed in (bs_queue) must have been built up previous
4236 * via bdrv_reopen_queue().
4237 *
4238 * Reopens all BDS specified in the queue, with the appropriate
4239 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004240 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004241 * data cleaned up.
4242 *
4243 * If all devices prepare successfully, then the changes are committed
4244 * to all devices.
4245 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004246 * All affected nodes must be drained between bdrv_reopen_queue() and
4247 * bdrv_reopen_multiple().
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004248 *
4249 * To be called from the main thread, with all other AioContexts unlocked.
Jeff Codye971aa12012-09-20 15:13:19 -04004250 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004251int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004252{
4253 int ret = -1;
4254 BlockReopenQueueEntry *bs_entry, *next;
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004255 AioContext *ctx;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004256 Transaction *tran = tran_new();
4257 g_autoptr(GHashTable) found = NULL;
4258 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004259
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004260 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Jeff Codye971aa12012-09-20 15:13:19 -04004261 assert(bs_queue != NULL);
4262
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004263 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004264 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4265 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004266 ret = bdrv_flush(bs_entry->state.bs);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004267 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004268 if (ret < 0) {
4269 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004270 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004271 }
4272 }
4273
4274 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004275 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004276 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4277 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004278 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004279 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004280 if (ret < 0) {
4281 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004282 }
4283 bs_entry->prepared = true;
4284 }
4285
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004286 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004287 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004288 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004289
4290 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4291 if (state->old_backing_bs) {
4292 refresh_list = bdrv_topological_dfs(refresh_list, found,
4293 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004294 }
Alberto Garciaecd30d22021-06-10 15:05:36 +03004295 if (state->old_file_bs) {
4296 refresh_list = bdrv_topological_dfs(refresh_list, found,
4297 state->old_file_bs);
4298 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004299 }
4300
4301 /*
4302 * Note that file-posix driver rely on permission update done during reopen
4303 * (even if no permission changed), because it wants "new" permissions for
4304 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4305 * in raw_reopen_prepare() which is called with "old" permissions.
4306 */
4307 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4308 if (ret < 0) {
4309 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004310 }
4311
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004312 /*
4313 * If we reach this point, we have success and just need to apply the
4314 * changes.
4315 *
4316 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4317 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4318 * children are usually goes after parents in reopen-queue, so go from last
4319 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004320 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004321 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004322 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4323 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004324 bdrv_reopen_commit(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004325 aio_context_release(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004326 }
4327
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004328 tran_commit(tran);
4329
4330 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4331 BlockDriverState *bs = bs_entry->state.bs;
4332
4333 if (bs->drv->bdrv_reopen_commit_post) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004334 ctx = bdrv_get_aio_context(bs);
4335 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004336 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004337 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004338 }
4339 }
4340
Jeff Codye971aa12012-09-20 15:13:19 -04004341 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004342 goto cleanup;
4343
4344abort:
4345 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004346 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004347 if (bs_entry->prepared) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004348 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4349 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004350 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004351 aio_context_release(ctx);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004352 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004353 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004354
Jeff Codye971aa12012-09-20 15:13:19 -04004355cleanup:
Alberto Garciaab5b52282021-07-08 13:47:05 +02004356 bdrv_reopen_queue_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004357
Jeff Codye971aa12012-09-20 15:13:19 -04004358 return ret;
4359}
4360
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004361int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4362 Error **errp)
4363{
4364 AioContext *ctx = bdrv_get_aio_context(bs);
4365 BlockReopenQueue *queue;
4366 int ret;
4367
4368 bdrv_subtree_drained_begin(bs);
4369 if (ctx != qemu_get_aio_context()) {
4370 aio_context_release(ctx);
4371 }
4372
4373 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4374 ret = bdrv_reopen_multiple(queue, errp);
4375
4376 if (ctx != qemu_get_aio_context()) {
4377 aio_context_acquire(ctx);
4378 }
4379 bdrv_subtree_drained_end(bs);
4380
4381 return ret;
4382}
4383
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004384int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4385 Error **errp)
4386{
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004387 QDict *opts = qdict_new();
4388
4389 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4390
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004391 return bdrv_reopen(bs, opts, true, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004392}
4393
Jeff Codye971aa12012-09-20 15:13:19 -04004394/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004395 * Take a BDRVReopenState and check if the value of 'backing' in the
4396 * reopen_state->options QDict is valid or not.
4397 *
4398 * If 'backing' is missing from the QDict then return 0.
4399 *
4400 * If 'backing' contains the node name of the backing file of
4401 * reopen_state->bs then return 0.
4402 *
4403 * If 'backing' contains a different node name (or is null) then check
4404 * whether the current backing file can be replaced with the new one.
4405 * If that's the case then reopen_state->replace_backing_bs is set to
4406 * true and reopen_state->new_backing_bs contains a pointer to the new
4407 * backing BlockDriverState (or NULL).
4408 *
4409 * Return 0 on success, otherwise return < 0 and set @errp.
4410 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004411static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4412 bool is_backing, Transaction *tran,
4413 Error **errp)
Alberto Garciacb828c32019-03-12 18:48:47 +02004414{
4415 BlockDriverState *bs = reopen_state->bs;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004416 BlockDriverState *new_child_bs;
4417 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4418 child_bs(bs->file);
4419 const char *child_name = is_backing ? "backing" : "file";
Alberto Garciacb828c32019-03-12 18:48:47 +02004420 QObject *value;
4421 const char *str;
4422
Alberto Garciaecd30d22021-06-10 15:05:36 +03004423 value = qdict_get(reopen_state->options, child_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004424 if (value == NULL) {
4425 return 0;
4426 }
4427
4428 switch (qobject_type(value)) {
4429 case QTYPE_QNULL:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004430 assert(is_backing); /* The 'file' option does not allow a null value */
4431 new_child_bs = NULL;
Alberto Garciacb828c32019-03-12 18:48:47 +02004432 break;
4433 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004434 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciaecd30d22021-06-10 15:05:36 +03004435 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4436 if (new_child_bs == NULL) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004437 return -EINVAL;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004438 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4439 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4440 "cycle", str, child_name, bs->node_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004441 return -EINVAL;
4442 }
4443 break;
4444 default:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004445 /*
4446 * The options QDict has been flattened, so 'backing' and 'file'
4447 * do not allow any other data type here.
4448 */
Alberto Garciacb828c32019-03-12 18:48:47 +02004449 g_assert_not_reached();
4450 }
4451
Alberto Garciaecd30d22021-06-10 15:05:36 +03004452 if (old_child_bs == new_child_bs) {
4453 return 0;
4454 }
4455
4456 if (old_child_bs) {
4457 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004458 return 0;
4459 }
4460
Alberto Garciaecd30d22021-06-10 15:05:36 +03004461 if (old_child_bs->implicit) {
4462 error_setg(errp, "Cannot replace implicit %s child of %s",
4463 child_name, bs->node_name);
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004464 return -EPERM;
4465 }
4466 }
4467
Alberto Garciaecd30d22021-06-10 15:05:36 +03004468 if (bs->drv->is_filter && !old_child_bs) {
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004469 /*
4470 * Filters always have a file or a backing child, so we are trying to
4471 * change wrong child
4472 */
4473 error_setg(errp, "'%s' is a %s filter node that does not support a "
Alberto Garciaecd30d22021-06-10 15:05:36 +03004474 "%s child", bs->node_name, bs->drv->format_name, child_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004475 return -EINVAL;
4476 }
4477
Alberto Garciaecd30d22021-06-10 15:05:36 +03004478 if (is_backing) {
4479 reopen_state->old_backing_bs = old_child_bs;
4480 } else {
4481 reopen_state->old_file_bs = old_child_bs;
4482 }
4483
4484 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4485 tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004486}
4487
4488/*
Jeff Codye971aa12012-09-20 15:13:19 -04004489 * Prepares a BlockDriverState for reopen. All changes are staged in the
4490 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4491 * the block driver layer .bdrv_reopen_prepare()
4492 *
4493 * bs is the BlockDriverState to reopen
4494 * flags are the new open flags
4495 * queue is the reopen queue
4496 *
4497 * Returns 0 on success, non-zero on error. On error errp will be set
4498 * as well.
4499 *
4500 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4501 * It is the responsibility of the caller to then call the abort() or
4502 * commit() for any other BDS that have been left in a prepare() state
4503 *
4504 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004505static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004506 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +03004507 Transaction *change_child_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004508{
4509 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004510 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004511 Error *local_err = NULL;
4512 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004513 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004514 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004515 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004516 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004517 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004518
4519 assert(reopen_state != NULL);
4520 assert(reopen_state->bs->drv != NULL);
4521 drv = reopen_state->bs->drv;
4522
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004523 /* This function and each driver's bdrv_reopen_prepare() remove
4524 * entries from reopen_state->options as they are processed, so
4525 * we need to make a copy of the original QDict. */
4526 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4527
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004528 /* Process generic block layer options */
4529 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004530 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004531 ret = -EINVAL;
4532 goto error;
4533 }
4534
Alberto Garciae6d79c42018-11-12 16:00:47 +02004535 /* This was already called in bdrv_reopen_queue_child() so the flags
4536 * are up-to-date. This time we simply want to remove the options from
4537 * QemuOpts in order to indicate that they have been processed. */
4538 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004539 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004540 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004541
Alberto Garcia415bbca2018-10-03 13:23:13 +03004542 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004543 if (discard != NULL) {
4544 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4545 error_setg(errp, "Invalid discard option");
4546 ret = -EINVAL;
4547 goto error;
4548 }
4549 }
4550
Alberto Garcia543770b2018-09-06 12:37:09 +03004551 reopen_state->detect_zeroes =
4552 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4553 if (local_err) {
4554 error_propagate(errp, local_err);
4555 ret = -EINVAL;
4556 goto error;
4557 }
4558
Alberto Garcia57f9db92018-09-06 12:37:06 +03004559 /* All other options (including node-name and driver) must be unchanged.
4560 * Put them back into the QDict, so that they are checked at the end
4561 * of this function. */
4562 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004563
Jeff Cody3d8ce172017-04-07 16:55:30 -04004564 /* If we are to stay read-only, do not allow permission change
4565 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4566 * not set, or if the BDS still has copy_on_read enabled */
4567 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004568 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004569 if (local_err) {
4570 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004571 goto error;
4572 }
4573
Jeff Codye971aa12012-09-20 15:13:19 -04004574 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004575 /*
4576 * If a driver-specific option is missing, it means that we
4577 * should reset it to its default value.
4578 * But not all options allow that, so we need to check it first.
4579 */
4580 ret = bdrv_reset_options_allowed(reopen_state->bs,
4581 reopen_state->options, errp);
4582 if (ret) {
4583 goto error;
4584 }
4585
Jeff Codye971aa12012-09-20 15:13:19 -04004586 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4587 if (ret) {
4588 if (local_err != NULL) {
4589 error_propagate(errp, local_err);
4590 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004591 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004592 error_setg(errp, "failed while preparing to reopen image '%s'",
4593 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004594 }
4595 goto error;
4596 }
4597 } else {
4598 /* It is currently mandatory to have a bdrv_reopen_prepare()
4599 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004600 error_setg(errp, "Block format '%s' used by node '%s' "
4601 "does not support reopening files", drv->format_name,
4602 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004603 ret = -1;
4604 goto error;
4605 }
4606
Max Reitz9ad08c42018-11-16 17:45:24 +01004607 drv_prepared = true;
4608
Alberto Garciabacd9b82019-03-12 18:48:46 +02004609 /*
4610 * We must provide the 'backing' option if the BDS has a backing
4611 * file or if the image file has a backing file name as part of
4612 * its metadata. Otherwise the 'backing' option can be omitted.
4613 */
4614 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004615 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004616 error_setg(errp, "backing is missing for '%s'",
4617 reopen_state->bs->node_name);
4618 ret = -EINVAL;
4619 goto error;
4620 }
4621
Alberto Garciacb828c32019-03-12 18:48:47 +02004622 /*
4623 * Allow changing the 'backing' option. The new value can be
4624 * either a reference to an existing node (using its node name)
4625 * or NULL to simply detach the current backing file.
4626 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004627 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4628 change_child_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004629 if (ret < 0) {
4630 goto error;
4631 }
4632 qdict_del(reopen_state->options, "backing");
4633
Alberto Garciaecd30d22021-06-10 15:05:36 +03004634 /* Allow changing the 'file' option. In this case NULL is not allowed */
4635 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4636 change_child_tran, errp);
4637 if (ret < 0) {
4638 goto error;
4639 }
4640 qdict_del(reopen_state->options, "file");
4641
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004642 /* Options that are not handled are only okay if they are unchanged
4643 * compared to the old state. It is expected that some options are only
4644 * used for the initial open, but not reopen (e.g. filename) */
4645 if (qdict_size(reopen_state->options)) {
4646 const QDictEntry *entry = qdict_first(reopen_state->options);
4647
4648 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004649 QObject *new = entry->value;
4650 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004651
Alberto Garciadb905282018-09-06 12:37:05 +03004652 /* Allow child references (child_name=node_name) as long as they
4653 * point to the current child (i.e. everything stays the same). */
4654 if (qobject_type(new) == QTYPE_QSTRING) {
4655 BdrvChild *child;
4656 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4657 if (!strcmp(child->name, entry->key)) {
4658 break;
4659 }
4660 }
4661
4662 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004663 if (!strcmp(child->bs->node_name,
4664 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004665 continue; /* Found child with this name, skip option */
4666 }
4667 }
4668 }
4669
Max Reitz54fd1b02017-11-14 19:01:26 +01004670 /*
4671 * TODO: When using -drive to specify blockdev options, all values
4672 * will be strings; however, when using -blockdev, blockdev-add or
4673 * filenames using the json:{} pseudo-protocol, they will be
4674 * correctly typed.
4675 * In contrast, reopening options are (currently) always strings
4676 * (because you can only specify them through qemu-io; all other
4677 * callers do not specify any options).
4678 * Therefore, when using anything other than -drive to create a BDS,
4679 * this cannot detect non-string options as unchanged, because
4680 * qobject_is_equal() always returns false for objects of different
4681 * type. In the future, this should be remedied by correctly typing
4682 * all options. For now, this is not too big of an issue because
4683 * the user can simply omit options which cannot be changed anyway,
4684 * so they will stay unchanged.
4685 */
4686 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004687 error_setg(errp, "Cannot change the option '%s'", entry->key);
4688 ret = -EINVAL;
4689 goto error;
4690 }
4691 } while ((entry = qdict_next(reopen_state->options, entry)));
4692 }
4693
Jeff Codye971aa12012-09-20 15:13:19 -04004694 ret = 0;
4695
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004696 /* Restore the original reopen_state->options QDict */
4697 qobject_unref(reopen_state->options);
4698 reopen_state->options = qobject_ref(orig_reopen_opts);
4699
Jeff Codye971aa12012-09-20 15:13:19 -04004700error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004701 if (ret < 0 && drv_prepared) {
4702 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4703 * call drv->bdrv_reopen_abort() before signaling an error
4704 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4705 * when the respective bdrv_reopen_prepare() has failed) */
4706 if (drv->bdrv_reopen_abort) {
4707 drv->bdrv_reopen_abort(reopen_state);
4708 }
4709 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004710 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004711 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004712 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004713 return ret;
4714}
4715
4716/*
4717 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4718 * makes them final by swapping the staging BlockDriverState contents into
4719 * the active BlockDriverState contents.
4720 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004721static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004722{
4723 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004724 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004725 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004726
4727 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004728 bs = reopen_state->bs;
4729 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004730 assert(drv != NULL);
4731
4732 /* If there are any driver level actions to take */
4733 if (drv->bdrv_reopen_commit) {
4734 drv->bdrv_reopen_commit(reopen_state);
4735 }
4736
4737 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004738 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004739 qobject_unref(bs->options);
Alberto Garciaab5b52282021-07-08 13:47:05 +02004740 qobject_ref(reopen_state->explicit_options);
4741 qobject_ref(reopen_state->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004742
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004743 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004744 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004745 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004746 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004747
Alberto Garcia50196d72018-09-06 12:37:03 +03004748 /* Remove child references from bs->options and bs->explicit_options.
4749 * Child options were already removed in bdrv_reopen_queue_child() */
4750 QLIST_FOREACH(child, &bs->children, next) {
4751 qdict_del(bs->explicit_options, child->name);
4752 qdict_del(bs->options, child->name);
4753 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004754 /* backing is probably removed, so it's not handled by previous loop */
4755 qdict_del(bs->explicit_options, "backing");
4756 qdict_del(bs->options, "backing");
4757
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004758 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004759}
4760
4761/*
4762 * Abort the reopen, and delete and free the staged changes in
4763 * reopen_state
4764 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004765static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004766{
4767 BlockDriver *drv;
4768
4769 assert(reopen_state != NULL);
4770 drv = reopen_state->bs->drv;
4771 assert(drv != NULL);
4772
4773 if (drv->bdrv_reopen_abort) {
4774 drv->bdrv_reopen_abort(reopen_state);
4775 }
4776}
4777
4778
Max Reitz64dff522016-01-29 16:36:10 +01004779static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004780{
Max Reitz33384422014-06-20 21:57:33 +02004781 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004782 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004783
Max Reitz30f55fb2016-05-17 16:41:32 +02004784 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004785
Paolo Bonzinifc272912015-12-23 11:48:24 +01004786 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004787 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004788 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004789
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004790 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004791 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004792 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004793 bs->drv->bdrv_close(bs);
4794 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004795 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004796 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004797
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004798 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004799 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004800 }
4801
Alberto Garciadd4118c2019-05-13 16:46:17 +03004802 bs->backing = NULL;
4803 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004804 g_free(bs->opaque);
4805 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004806 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004807 bs->backing_file[0] = '\0';
4808 bs->backing_format[0] = '\0';
4809 bs->total_sectors = 0;
4810 bs->encrypted = false;
4811 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004812 qobject_unref(bs->options);
4813 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004814 bs->options = NULL;
4815 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004816 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004817 bs->full_open_options = NULL;
Hanna Reitz0bc329f2021-08-12 10:41:44 +02004818 g_free(bs->block_status_cache);
4819 bs->block_status_cache = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004820
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004821 bdrv_release_named_dirty_bitmaps(bs);
4822 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4823
Max Reitz33384422014-06-20 21:57:33 +02004824 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4825 g_free(ban);
4826 }
4827 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004828 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004829
4830 /*
4831 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4832 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4833 * gets called.
4834 */
4835 if (bs->quiesce_counter) {
4836 bdrv_drain_all_end_quiesce(bs);
4837 }
bellardb3380822004-03-14 21:38:54 +00004838}
4839
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004840void bdrv_close_all(void)
4841{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004842 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004843
Max Reitzca9bd242016-01-29 16:36:14 +01004844 /* Drop references from requests still in flight, such as canceled block
4845 * jobs whose AIO context has not been polled yet */
4846 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004847
Max Reitzca9bd242016-01-29 16:36:14 +01004848 blk_remove_all_bs();
4849 blockdev_close_all_bdrv_states();
4850
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004851 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004852}
4853
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004854static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004855{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004856 GQueue *queue;
4857 GHashTable *found;
4858 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004859
Max Reitzbd86fb92020-05-13 13:05:13 +02004860 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004861 return false;
4862 }
4863
Max Reitzec9f10f2018-06-13 20:18:15 +02004864 /* If the child @c belongs to the BDS @to, replacing the current
4865 * c->bs by @to would mean to create a loop.
4866 *
4867 * Such a case occurs when appending a BDS to a backing chain.
4868 * For instance, imagine the following chain:
4869 *
4870 * guest device -> node A -> further backing chain...
4871 *
4872 * Now we create a new BDS B which we want to put on top of this
4873 * chain, so we first attach A as its backing node:
4874 *
4875 * node B
4876 * |
4877 * v
4878 * guest device -> node A -> further backing chain...
4879 *
4880 * Finally we want to replace A by B. When doing that, we want to
4881 * replace all pointers to A by pointers to B -- except for the
4882 * pointer from B because (1) that would create a loop, and (2)
4883 * that pointer should simply stay intact:
4884 *
4885 * guest device -> node B
4886 * |
4887 * v
4888 * node A -> further backing chain...
4889 *
4890 * In general, when replacing a node A (c->bs) by a node B (@to),
4891 * if A is a child of B, that means we cannot replace A by B there
4892 * because that would create a loop. Silently detaching A from B
4893 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004894 * place there is the most sensible choice.
4895 *
4896 * We would also create a loop in any cases where @c is only
4897 * indirectly referenced by @to. Prevent this by returning false
4898 * if @c is found (by breadth-first search) anywhere in the whole
4899 * subtree of @to.
4900 */
4901
4902 ret = true;
4903 found = g_hash_table_new(NULL, NULL);
4904 g_hash_table_add(found, to);
4905 queue = g_queue_new();
4906 g_queue_push_tail(queue, to);
4907
4908 while (!g_queue_is_empty(queue)) {
4909 BlockDriverState *v = g_queue_pop_head(queue);
4910 BdrvChild *c2;
4911
4912 QLIST_FOREACH(c2, &v->children, next) {
4913 if (c2 == c) {
4914 ret = false;
4915 break;
4916 }
4917
4918 if (g_hash_table_contains(found, c2->bs)) {
4919 continue;
4920 }
4921
4922 g_queue_push_tail(queue, c2->bs);
4923 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004924 }
4925 }
4926
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004927 g_queue_free(queue);
4928 g_hash_table_destroy(found);
4929
4930 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004931}
4932
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004933typedef struct BdrvRemoveFilterOrCowChild {
4934 BdrvChild *child;
Hanna Reitz82b54cf2021-11-15 15:54:04 +01004935 BlockDriverState *bs;
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004936 bool is_backing;
4937} BdrvRemoveFilterOrCowChild;
4938
4939static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
4940{
4941 BdrvRemoveFilterOrCowChild *s = opaque;
4942 BlockDriverState *parent_bs = s->child->opaque;
4943
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004944 if (s->is_backing) {
4945 parent_bs->backing = s->child;
4946 } else {
4947 parent_bs->file = s->child;
4948 }
4949
4950 /*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004951 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004952 * because that function is transactionable and it registered own completion
4953 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
4954 * called automatically.
4955 */
4956}
4957
4958static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
4959{
4960 BdrvRemoveFilterOrCowChild *s = opaque;
4961
4962 bdrv_child_free(s->child);
4963}
4964
Hanna Reitz82b54cf2021-11-15 15:54:04 +01004965static void bdrv_remove_filter_or_cow_child_clean(void *opaque)
4966{
4967 BdrvRemoveFilterOrCowChild *s = opaque;
4968
4969 /* Drop the bs reference after the transaction is done */
4970 bdrv_unref(s->bs);
4971 g_free(s);
4972}
4973
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004974static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
4975 .abort = bdrv_remove_filter_or_cow_child_abort,
4976 .commit = bdrv_remove_filter_or_cow_child_commit,
Hanna Reitz82b54cf2021-11-15 15:54:04 +01004977 .clean = bdrv_remove_filter_or_cow_child_clean,
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004978};
4979
4980/*
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004981 * A function to remove backing or file child of @bs.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03004982 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004983 */
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004984static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
4985 BdrvChild *child,
4986 Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004987{
Hanna Reitz562bda82021-11-15 15:54:02 +01004988 BdrvChild **childp;
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004989 BdrvRemoveFilterOrCowChild *s;
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004990
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004991 if (!child) {
4992 return;
4993 }
4994
Hanna Reitz82b54cf2021-11-15 15:54:04 +01004995 /*
4996 * Keep a reference to @bs so @childp will stay valid throughout the
4997 * transaction (required by bdrv_replace_child_tran())
4998 */
4999 bdrv_ref(bs);
Hanna Reitz562bda82021-11-15 15:54:02 +01005000 if (child == bs->backing) {
5001 childp = &bs->backing;
5002 } else if (child == bs->file) {
5003 childp = &bs->file;
5004 } else {
5005 g_assert_not_reached();
5006 }
5007
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005008 if (child->bs) {
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005009 /*
5010 * Pass free_empty_child=false, we will free the child in
5011 * bdrv_remove_filter_or_cow_child_commit()
5012 */
5013 bdrv_replace_child_tran(childp, NULL, tran, false);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005014 }
5015
5016 s = g_new(BdrvRemoveFilterOrCowChild, 1);
5017 *s = (BdrvRemoveFilterOrCowChild) {
5018 .child = child,
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005019 .bs = bs,
Hanna Reitz562bda82021-11-15 15:54:02 +01005020 .is_backing = (childp == &bs->backing),
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005021 };
5022 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005023}
5024
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005025/*
5026 * A function to remove backing-chain child of @bs if exists: cow child for
5027 * format nodes (always .backing) and filter child for filters (may be .file or
5028 * .backing)
5029 */
5030static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
5031 Transaction *tran)
5032{
5033 bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
5034}
5035
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005036static int bdrv_replace_node_noperm(BlockDriverState *from,
5037 BlockDriverState *to,
5038 bool auto_skip, Transaction *tran,
5039 Error **errp)
5040{
5041 BdrvChild *c, *next;
5042
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005043 assert(to != NULL);
5044
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005045 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5046 assert(c->bs == from);
5047 if (!should_update_child(c, to)) {
5048 if (auto_skip) {
5049 continue;
5050 }
5051 error_setg(errp, "Should not change '%s' link to '%s'",
5052 c->name, from->node_name);
5053 return -EINVAL;
5054 }
5055 if (c->frozen) {
5056 error_setg(errp, "Cannot change '%s' link to '%s'",
5057 c->name, from->node_name);
5058 return -EPERM;
5059 }
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005060
5061 /*
5062 * Passing a pointer to the local variable @c is fine here, because
5063 * @to is not NULL, and so &c will not be attached to the transaction.
5064 */
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005065 bdrv_replace_child_tran(&c, to, tran, true);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005066 }
5067
5068 return 0;
5069}
5070
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005071/*
5072 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5073 * if it creates a parent-child relation loop or if parent is block-job.
5074 *
5075 * With auto_skip=false the error is returned if from has a parent which should
5076 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005077 *
5078 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5079 * case backing link of the cow-parent of @to is removed.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005080 *
5081 * @to must not be NULL.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005082 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005083static int bdrv_replace_node_common(BlockDriverState *from,
5084 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005085 bool auto_skip, bool detach_subchain,
5086 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005087{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005088 Transaction *tran = tran_new();
5089 g_autoptr(GHashTable) found = NULL;
5090 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04005091 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005092 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005093
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005094 assert(to != NULL);
5095
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005096 if (detach_subchain) {
5097 assert(bdrv_chain_contains(from, to));
5098 assert(from != to);
5099 for (to_cow_parent = from;
5100 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5101 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5102 {
5103 ;
5104 }
5105 }
5106
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005107 /* Make sure that @from doesn't go away until we have successfully attached
5108 * all of its parents to @to. */
5109 bdrv_ref(from);
5110
Kevin Wolff871abd2019-05-21 19:00:25 +02005111 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01005112 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02005113 bdrv_drained_begin(from);
5114
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005115 /*
5116 * Do the replacement without permission update.
5117 * Replacement may influence the permissions, we should calculate new
5118 * permissions based on new graph. If we fail, we'll roll-back the
5119 * replacement.
5120 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005121 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5122 if (ret < 0) {
5123 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005124 }
5125
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005126 if (detach_subchain) {
5127 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
5128 }
5129
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005130 found = g_hash_table_new(NULL, NULL);
5131
5132 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5133 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5134
5135 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005136 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005137 goto out;
5138 }
5139
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005140 ret = 0;
5141
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005142out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005143 tran_finalize(tran, ret);
5144
Kevin Wolff871abd2019-05-21 19:00:25 +02005145 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005146 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005147
5148 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005149}
5150
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005151/**
5152 * Replace node @from by @to (where neither may be NULL).
5153 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005154int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5155 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005156{
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005157 return bdrv_replace_node_common(from, to, true, false, errp);
5158}
5159
5160int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5161{
5162 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5163 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005164}
5165
Jeff Cody8802d1f2012-02-28 15:54:06 -05005166/*
5167 * Add new bs contents at the top of an image chain while the chain is
5168 * live, while keeping required fields on the top layer.
5169 *
5170 * This will modify the BlockDriverState fields, and swap contents
5171 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5172 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005173 * bs_new must not be attached to a BlockBackend and must not have backing
5174 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005175 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005176 * This function does not create any image files.
5177 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005178int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5179 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005180{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005181 int ret;
5182 Transaction *tran = tran_new();
5183
5184 assert(!bs_new->backing);
5185
5186 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5187 &child_of_bds, bdrv_backing_role(bs_new),
5188 &bs_new->backing, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005189 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005190 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005191 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005192
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005193 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005194 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005195 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005196 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005197
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005198 ret = bdrv_refresh_perms(bs_new, errp);
5199out:
5200 tran_finalize(tran, ret);
5201
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005202 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005203
5204 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005205}
5206
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005207/* Not for empty child */
5208int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5209 Error **errp)
5210{
5211 int ret;
5212 Transaction *tran = tran_new();
5213 g_autoptr(GHashTable) found = NULL;
5214 g_autoptr(GSList) refresh_list = NULL;
5215 BlockDriverState *old_bs = child->bs;
5216
5217 bdrv_ref(old_bs);
5218 bdrv_drained_begin(old_bs);
5219 bdrv_drained_begin(new_bs);
5220
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005221 bdrv_replace_child_tran(&child, new_bs, tran, true);
5222 /* @new_bs must have been non-NULL, so @child must not have been freed */
5223 assert(child != NULL);
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005224
5225 found = g_hash_table_new(NULL, NULL);
5226 refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5227 refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5228
5229 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5230
5231 tran_finalize(tran, ret);
5232
5233 bdrv_drained_end(old_bs);
5234 bdrv_drained_end(new_bs);
5235 bdrv_unref(old_bs);
5236
5237 return ret;
5238}
5239
Fam Zheng4f6fd342013-08-23 09:14:47 +08005240static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005241{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005242 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005243 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02005244
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005245 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005246 if (bs->node_name[0] != '\0') {
5247 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5248 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005249 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5250
Anton Kuchin30c321f2019-05-07 11:12:56 +03005251 bdrv_close(bs);
5252
Anthony Liguori7267c092011-08-20 22:09:37 -05005253 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005254}
5255
Vladimir Sementsov-Ogievskiy96796fa2021-09-20 14:55:36 +03005256
5257/*
5258 * Replace @bs by newly created block node.
5259 *
5260 * @options is a QDict of options to pass to the block drivers, or NULL for an
5261 * empty set of options. The reference to the QDict belongs to the block layer
5262 * after the call (even on failure), so if the caller intends to reuse the
5263 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5264 */
5265BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005266 int flags, Error **errp)
5267{
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005268 ERRP_GUARD();
5269 int ret;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005270 BlockDriverState *new_node_bs = NULL;
5271 const char *drvname, *node_name;
5272 BlockDriver *drv;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005273
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005274 drvname = qdict_get_try_str(options, "driver");
5275 if (!drvname) {
5276 error_setg(errp, "driver is not specified");
5277 goto fail;
5278 }
5279
5280 drv = bdrv_find_format(drvname);
5281 if (!drv) {
5282 error_setg(errp, "Unknown driver: '%s'", drvname);
5283 goto fail;
5284 }
5285
5286 node_name = qdict_get_try_str(options, "node-name");
5287
5288 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5289 errp);
5290 options = NULL; /* bdrv_new_open_driver() eats options */
5291 if (!new_node_bs) {
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005292 error_prepend(errp, "Could not create node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005293 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005294 }
5295
5296 bdrv_drained_begin(bs);
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005297 ret = bdrv_replace_node(bs, new_node_bs, errp);
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005298 bdrv_drained_end(bs);
5299
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005300 if (ret < 0) {
5301 error_prepend(errp, "Could not replace node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005302 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005303 }
5304
5305 return new_node_bs;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005306
5307fail:
5308 qobject_unref(options);
5309 bdrv_unref(new_node_bs);
5310 return NULL;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005311}
5312
aliguorie97fc192009-04-21 23:11:50 +00005313/*
5314 * Run consistency checks on an image
5315 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005316 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005317 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005318 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005319 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005320int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5321 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005322{
Max Reitz908bcd52014-08-07 22:47:55 +02005323 if (bs->drv == NULL) {
5324 return -ENOMEDIUM;
5325 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005326 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005327 return -ENOTSUP;
5328 }
5329
Kevin Wolfe076f332010-06-29 11:43:13 +02005330 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005331 return bs->drv->bdrv_co_check(bs, res, fix);
5332}
5333
Kevin Wolf756e6732010-01-12 12:55:17 +01005334/*
5335 * Return values:
5336 * 0 - success
5337 * -EINVAL - backing format specified, but no file
5338 * -ENOSPC - can't update the backing file because no space is left in the
5339 * image file header
5340 * -ENOTSUP - format driver doesn't support changing the backing file
5341 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005342int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
Eric Blake497a30d2021-05-03 14:36:00 -07005343 const char *backing_fmt, bool require)
Kevin Wolf756e6732010-01-12 12:55:17 +01005344{
5345 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005346 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005347
Max Reitzd470ad42017-11-10 21:31:09 +01005348 if (!drv) {
5349 return -ENOMEDIUM;
5350 }
5351
Paolo Bonzini5f377792012-04-12 14:01:01 +02005352 /* Backing file format doesn't make sense without a backing file */
5353 if (backing_fmt && !backing_file) {
5354 return -EINVAL;
5355 }
5356
Eric Blake497a30d2021-05-03 14:36:00 -07005357 if (require && backing_file && !backing_fmt) {
5358 return -EINVAL;
Eric Blakee54ee1b2020-07-06 15:39:53 -05005359 }
5360
Kevin Wolf756e6732010-01-12 12:55:17 +01005361 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005362 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005363 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005364 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005365 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005366
5367 if (ret == 0) {
5368 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5369 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005370 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5371 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005372 }
5373 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005374}
5375
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005376/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005377 * Finds the first non-filter node above bs in the chain between
5378 * active and bs. The returned node is either an immediate parent of
5379 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005380 *
5381 * Returns NULL if bs is not found in active's image chain,
5382 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005383 *
5384 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005385 */
5386BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5387 BlockDriverState *bs)
5388{
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005389 bs = bdrv_skip_filters(bs);
5390 active = bdrv_skip_filters(active);
5391
5392 while (active) {
5393 BlockDriverState *next = bdrv_backing_chain_next(active);
5394 if (bs == next) {
5395 return active;
5396 }
5397 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005398 }
5399
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005400 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005401}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005402
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005403/* Given a BDS, searches for the base layer. */
5404BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5405{
5406 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005407}
5408
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005409/*
Max Reitz7b99a262019-06-12 16:07:11 +02005410 * Return true if at least one of the COW (backing) and filter links
5411 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005412 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005413 */
5414bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5415 Error **errp)
5416{
5417 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005418 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005419
Max Reitz7b99a262019-06-12 16:07:11 +02005420 for (i = bs; i != base; i = child_bs(child)) {
5421 child = bdrv_filter_or_cow_child(i);
5422
5423 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005424 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005425 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005426 return true;
5427 }
5428 }
5429
5430 return false;
5431}
5432
5433/*
Max Reitz7b99a262019-06-12 16:07:11 +02005434 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005435 * If any of the links is already frozen the operation is aborted and
5436 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005437 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005438 * Returns 0 on success. On failure returns < 0 and sets @errp.
5439 */
5440int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5441 Error **errp)
5442{
5443 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005444 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005445
5446 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5447 return -EPERM;
5448 }
5449
Max Reitz7b99a262019-06-12 16:07:11 +02005450 for (i = bs; i != base; i = child_bs(child)) {
5451 child = bdrv_filter_or_cow_child(i);
5452 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005453 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005454 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005455 return -EPERM;
5456 }
5457 }
5458
Max Reitz7b99a262019-06-12 16:07:11 +02005459 for (i = bs; i != base; i = child_bs(child)) {
5460 child = bdrv_filter_or_cow_child(i);
5461 if (child) {
5462 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005463 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005464 }
5465
5466 return 0;
5467}
5468
5469/*
Max Reitz7b99a262019-06-12 16:07:11 +02005470 * Unfreeze all COW (backing) and filter links between @bs and @base.
5471 * The caller must ensure that all links are frozen before using this
5472 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005473 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005474 */
5475void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5476{
5477 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005478 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005479
Max Reitz7b99a262019-06-12 16:07:11 +02005480 for (i = bs; i != base; i = child_bs(child)) {
5481 child = bdrv_filter_or_cow_child(i);
5482 if (child) {
5483 assert(child->frozen);
5484 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005485 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005486 }
5487}
5488
5489/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005490 * Drops images above 'base' up to and including 'top', and sets the image
5491 * above 'top' to have base as its backing file.
5492 *
5493 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5494 * information in 'bs' can be properly updated.
5495 *
5496 * E.g., this will convert the following chain:
5497 * bottom <- base <- intermediate <- top <- active
5498 *
5499 * to
5500 *
5501 * bottom <- base <- active
5502 *
5503 * It is allowed for bottom==base, in which case it converts:
5504 *
5505 * base <- intermediate <- top <- active
5506 *
5507 * to
5508 *
5509 * base <- active
5510 *
Jeff Cody54e26902014-06-25 15:40:10 -04005511 * If backing_file_str is non-NULL, it will be used when modifying top's
5512 * overlay image metadata.
5513 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005514 * Error conditions:
5515 * if active == top, that is considered an error
5516 *
5517 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005518int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5519 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005520{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005521 BlockDriverState *explicit_top = top;
5522 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005523 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005524 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005525 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005526 g_autoptr(GSList) updated_children = NULL;
5527 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005528
Kevin Wolf6858eba2017-06-29 19:32:21 +02005529 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005530 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005531
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005532 if (!top->drv || !base->drv) {
5533 goto exit;
5534 }
5535
Kevin Wolf5db15a52015-09-14 15:33:33 +02005536 /* Make sure that base is in the backing chain of top */
5537 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005538 goto exit;
5539 }
5540
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005541 /* If 'base' recursively inherits from 'top' then we should set
5542 * base->inherits_from to top->inherits_from after 'top' and all
5543 * other intermediate nodes have been dropped.
5544 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5545 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005546 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005547 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5548
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005549 /* success - we can delete the intermediate states, and link top->base */
Max Reitzf30c66b2019-02-01 20:29:05 +01005550 if (!backing_file_str) {
5551 bdrv_refresh_filename(base);
5552 backing_file_str = base->filename;
5553 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005554
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005555 QLIST_FOREACH(c, &top->parents, next_parent) {
5556 updated_children = g_slist_prepend(updated_children, c);
5557 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005558
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005559 /*
5560 * It seems correct to pass detach_subchain=true here, but it triggers
5561 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5562 * another drained section, which modify the graph (for example, removing
5563 * the child, which we keep in updated_children list). So, it's a TODO.
5564 *
5565 * Note, bug triggered if pass detach_subchain=true here and run
5566 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5567 * That's a FIXME.
5568 */
5569 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005570 if (local_err) {
5571 error_report_err(local_err);
5572 goto exit;
5573 }
5574
5575 for (p = updated_children; p; p = p->next) {
5576 c = p->data;
5577
Max Reitzbd86fb92020-05-13 13:05:13 +02005578 if (c->klass->update_filename) {
5579 ret = c->klass->update_filename(c, base, backing_file_str,
5580 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005581 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005582 /*
5583 * TODO: Actually, we want to rollback all previous iterations
5584 * of this loop, and (which is almost impossible) previous
5585 * bdrv_replace_node()...
5586 *
5587 * Note, that c->klass->update_filename may lead to permission
5588 * update, so it's a bad idea to call it inside permission
5589 * update transaction of bdrv_replace_node.
5590 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005591 error_report_err(local_err);
5592 goto exit;
5593 }
5594 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005595 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005596
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005597 if (update_inherits_from) {
5598 base->inherits_from = explicit_top->inherits_from;
5599 }
5600
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005601 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005602exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005603 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005604 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005605 return ret;
5606}
5607
bellard83f64092006-08-01 16:21:11 +00005608/**
Max Reitz081e4652019-06-12 18:14:13 +02005609 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5610 * sums the size of all data-bearing children. (This excludes backing
5611 * children.)
5612 */
5613static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5614{
5615 BdrvChild *child;
5616 int64_t child_size, sum = 0;
5617
5618 QLIST_FOREACH(child, &bs->children, next) {
5619 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5620 BDRV_CHILD_FILTERED))
5621 {
5622 child_size = bdrv_get_allocated_file_size(child->bs);
5623 if (child_size < 0) {
5624 return child_size;
5625 }
5626 sum += child_size;
5627 }
5628 }
5629
5630 return sum;
5631}
5632
5633/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005634 * Length of a allocated file in bytes. Sparse files are counted by actual
5635 * allocated space. Return < 0 if error or unknown.
5636 */
5637int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5638{
5639 BlockDriver *drv = bs->drv;
5640 if (!drv) {
5641 return -ENOMEDIUM;
5642 }
5643 if (drv->bdrv_get_allocated_file_size) {
5644 return drv->bdrv_get_allocated_file_size(bs);
5645 }
Max Reitz081e4652019-06-12 18:14:13 +02005646
5647 if (drv->bdrv_file_open) {
5648 /*
5649 * Protocol drivers default to -ENOTSUP (most of their data is
5650 * not stored in any of their children (if they even have any),
5651 * so there is no generic way to figure it out).
5652 */
5653 return -ENOTSUP;
5654 } else if (drv->is_filter) {
5655 /* Filter drivers default to the size of their filtered child */
5656 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5657 } else {
5658 /* Other drivers default to summing their children's sizes */
5659 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005660 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005661}
5662
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005663/*
5664 * bdrv_measure:
5665 * @drv: Format driver
5666 * @opts: Creation options for new image
5667 * @in_bs: Existing image containing data for new image (may be NULL)
5668 * @errp: Error object
5669 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5670 * or NULL on error
5671 *
5672 * Calculate file size required to create a new image.
5673 *
5674 * If @in_bs is given then space for allocated clusters and zero clusters
5675 * from that image are included in the calculation. If @opts contains a
5676 * backing file that is shared by @in_bs then backing clusters may be omitted
5677 * from the calculation.
5678 *
5679 * If @in_bs is NULL then the calculation includes no allocated clusters
5680 * unless a preallocation option is given in @opts.
5681 *
5682 * Note that @in_bs may use a different BlockDriver from @drv.
5683 *
5684 * If an error occurs the @errp pointer is set.
5685 */
5686BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5687 BlockDriverState *in_bs, Error **errp)
5688{
5689 if (!drv->bdrv_measure) {
5690 error_setg(errp, "Block driver '%s' does not support size measurement",
5691 drv->format_name);
5692 return NULL;
5693 }
5694
5695 return drv->bdrv_measure(opts, in_bs, errp);
5696}
5697
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005698/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005699 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005700 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005701int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005702{
5703 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005704
bellard83f64092006-08-01 16:21:11 +00005705 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005706 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005707
Kevin Wolfb94a2612013-10-29 12:18:58 +01005708 if (drv->has_variable_length) {
5709 int ret = refresh_total_sectors(bs, bs->total_sectors);
5710 if (ret < 0) {
5711 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005712 }
bellard83f64092006-08-01 16:21:11 +00005713 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005714 return bs->total_sectors;
5715}
5716
5717/**
5718 * Return length in bytes on success, -errno on error.
5719 * The length is always a multiple of BDRV_SECTOR_SIZE.
5720 */
5721int64_t bdrv_getlength(BlockDriverState *bs)
5722{
5723 int64_t ret = bdrv_nb_sectors(bs);
5724
Eric Blake122860b2020-11-05 09:51:22 -06005725 if (ret < 0) {
5726 return ret;
5727 }
5728 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5729 return -EFBIG;
5730 }
5731 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005732}
5733
bellard19cb3732006-08-19 11:45:59 +00005734/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005735void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005736{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005737 int64_t nb_sectors = bdrv_nb_sectors(bs);
5738
5739 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005740}
bellardcf989512004-02-16 21:56:36 +00005741
Eric Blake54115412016-06-23 16:37:26 -06005742bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005743{
5744 return bs->sg;
5745}
5746
Max Reitzae23f782019-06-12 22:57:15 +02005747/**
5748 * Return whether the given node supports compressed writes.
5749 */
5750bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5751{
5752 BlockDriverState *filtered;
5753
5754 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5755 return false;
5756 }
5757
5758 filtered = bdrv_filter_bs(bs);
5759 if (filtered) {
5760 /*
5761 * Filters can only forward compressed writes, so we have to
5762 * check the child.
5763 */
5764 return bdrv_supports_compressed_writes(filtered);
5765 }
5766
5767 return true;
5768}
5769
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005770const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005771{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005772 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005773}
5774
Stefan Hajnocziada42402014-08-27 12:08:55 +01005775static int qsort_strcmp(const void *a, const void *b)
5776{
Max Reitzceff5bd2016-10-12 22:49:05 +02005777 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005778}
5779
ths5fafdf22007-09-16 21:08:06 +00005780void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005781 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005782{
5783 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005784 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005785 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005786 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005787
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005788 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005789 if (drv->format_name) {
5790 bool found = false;
5791 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005792
5793 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5794 continue;
5795 }
5796
Jeff Codye855e4f2014-04-28 18:29:54 -04005797 while (formats && i && !found) {
5798 found = !strcmp(formats[--i], drv->format_name);
5799 }
5800
5801 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005802 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005803 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005804 }
5805 }
bellardea2384d2004-08-01 21:59:26 +00005806 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005807
Max Reitzeb0df692016-10-12 22:49:06 +02005808 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5809 const char *format_name = block_driver_modules[i].format_name;
5810
5811 if (format_name) {
5812 bool found = false;
5813 int j = count;
5814
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005815 if (use_bdrv_whitelist &&
5816 !bdrv_format_is_whitelisted(format_name, read_only)) {
5817 continue;
5818 }
5819
Max Reitzeb0df692016-10-12 22:49:06 +02005820 while (formats && j && !found) {
5821 found = !strcmp(formats[--j], format_name);
5822 }
5823
5824 if (!found) {
5825 formats = g_renew(const char *, formats, count + 1);
5826 formats[count++] = format_name;
5827 }
5828 }
5829 }
5830
Stefan Hajnocziada42402014-08-27 12:08:55 +01005831 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5832
5833 for (i = 0; i < count; i++) {
5834 it(opaque, formats[i]);
5835 }
5836
Jeff Codye855e4f2014-04-28 18:29:54 -04005837 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005838}
5839
Benoît Canetdc364f42014-01-23 21:31:32 +01005840/* This function is to find a node in the bs graph */
5841BlockDriverState *bdrv_find_node(const char *node_name)
5842{
5843 BlockDriverState *bs;
5844
5845 assert(node_name);
5846
5847 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5848 if (!strcmp(node_name, bs->node_name)) {
5849 return bs;
5850 }
5851 }
5852 return NULL;
5853}
5854
Benoît Canetc13163f2014-01-23 21:31:34 +01005855/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005856BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5857 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005858{
Eric Blake9812e712020-10-27 00:05:47 -05005859 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005860 BlockDriverState *bs;
5861
5862 list = NULL;
5863 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005864 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005865 if (!info) {
5866 qapi_free_BlockDeviceInfoList(list);
5867 return NULL;
5868 }
Eric Blake9812e712020-10-27 00:05:47 -05005869 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005870 }
5871
5872 return list;
5873}
5874
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005875typedef struct XDbgBlockGraphConstructor {
5876 XDbgBlockGraph *graph;
5877 GHashTable *graph_nodes;
5878} XDbgBlockGraphConstructor;
5879
5880static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5881{
5882 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5883
5884 gr->graph = g_new0(XDbgBlockGraph, 1);
5885 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5886
5887 return gr;
5888}
5889
5890static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5891{
5892 XDbgBlockGraph *graph = gr->graph;
5893
5894 g_hash_table_destroy(gr->graph_nodes);
5895 g_free(gr);
5896
5897 return graph;
5898}
5899
5900static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5901{
5902 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5903
5904 if (ret != 0) {
5905 return ret;
5906 }
5907
5908 /*
5909 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5910 * answer of g_hash_table_lookup.
5911 */
5912 ret = g_hash_table_size(gr->graph_nodes) + 1;
5913 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5914
5915 return ret;
5916}
5917
5918static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5919 XDbgBlockGraphNodeType type, const char *name)
5920{
5921 XDbgBlockGraphNode *n;
5922
5923 n = g_new0(XDbgBlockGraphNode, 1);
5924
5925 n->id = xdbg_graph_node_num(gr, node);
5926 n->type = type;
5927 n->name = g_strdup(name);
5928
Eric Blake9812e712020-10-27 00:05:47 -05005929 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005930}
5931
5932static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5933 const BdrvChild *child)
5934{
Max Reitzcdb1cec2019-11-08 13:34:52 +01005935 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005936 XDbgBlockGraphEdge *edge;
5937
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005938 edge = g_new0(XDbgBlockGraphEdge, 1);
5939
5940 edge->parent = xdbg_graph_node_num(gr, parent);
5941 edge->child = xdbg_graph_node_num(gr, child->bs);
5942 edge->name = g_strdup(child->name);
5943
Max Reitzcdb1cec2019-11-08 13:34:52 +01005944 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5945 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5946
5947 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005948 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005949 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01005950 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005951 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005952 }
5953 }
5954
Eric Blake9812e712020-10-27 00:05:47 -05005955 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005956}
5957
5958
5959XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5960{
5961 BlockBackend *blk;
5962 BlockJob *job;
5963 BlockDriverState *bs;
5964 BdrvChild *child;
5965 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5966
5967 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5968 char *allocated_name = NULL;
5969 const char *name = blk_name(blk);
5970
5971 if (!*name) {
5972 name = allocated_name = blk_get_attached_dev_id(blk);
5973 }
5974 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5975 name);
5976 g_free(allocated_name);
5977 if (blk_root(blk)) {
5978 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5979 }
5980 }
5981
5982 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5983 GSList *el;
5984
5985 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5986 job->job.id);
5987 for (el = job->nodes; el; el = el->next) {
5988 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5989 }
5990 }
5991
5992 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5993 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5994 bs->node_name);
5995 QLIST_FOREACH(child, &bs->children, next) {
5996 xdbg_graph_add_edge(gr, bs, child);
5997 }
5998 }
5999
6000 return xdbg_graph_finalize(gr);
6001}
6002
Benoît Canet12d3ba82014-01-23 21:31:35 +01006003BlockDriverState *bdrv_lookup_bs(const char *device,
6004 const char *node_name,
6005 Error **errp)
6006{
Markus Armbruster7f06d472014-10-07 13:59:12 +02006007 BlockBackend *blk;
6008 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006009
Benoît Canet12d3ba82014-01-23 21:31:35 +01006010 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02006011 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006012
Markus Armbruster7f06d472014-10-07 13:59:12 +02006013 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006014 bs = blk_bs(blk);
6015 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02006016 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02006017 }
6018
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006019 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006020 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006021 }
6022
Benoît Canetdd67fa52014-02-12 17:15:06 +01006023 if (node_name) {
6024 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006025
Benoît Canetdd67fa52014-02-12 17:15:06 +01006026 if (bs) {
6027 return bs;
6028 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006029 }
6030
Connor Kuehl785ec4b2021-03-05 09:19:28 -06006031 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01006032 device ? device : "",
6033 node_name ? node_name : "");
6034 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006035}
6036
Jeff Cody5a6684d2014-06-25 15:40:09 -04006037/* If 'base' is in the same chain as 'top', return true. Otherwise,
6038 * return false. If either argument is NULL, return false. */
6039bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6040{
6041 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006042 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04006043 }
6044
6045 return top != NULL;
6046}
6047
Fam Zheng04df7652014-10-31 11:32:54 +08006048BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6049{
6050 if (!bs) {
6051 return QTAILQ_FIRST(&graph_bdrv_states);
6052 }
6053 return QTAILQ_NEXT(bs, node_list);
6054}
6055
Kevin Wolf0f122642018-03-28 18:29:18 +02006056BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6057{
6058 if (!bs) {
6059 return QTAILQ_FIRST(&all_bdrv_states);
6060 }
6061 return QTAILQ_NEXT(bs, bs_list);
6062}
6063
Fam Zheng20a9e772014-10-31 11:32:55 +08006064const char *bdrv_get_node_name(const BlockDriverState *bs)
6065{
6066 return bs->node_name;
6067}
6068
Kevin Wolf1f0c4612016-03-22 18:38:44 +01006069const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006070{
6071 BdrvChild *c;
6072 const char *name;
6073
6074 /* If multiple parents have a name, just pick the first one. */
6075 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006076 if (c->klass->get_name) {
6077 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006078 if (name && *name) {
6079 return name;
6080 }
6081 }
6082 }
6083
6084 return NULL;
6085}
6086
Markus Armbruster7f06d472014-10-07 13:59:12 +02006087/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02006088const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00006089{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006090 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00006091}
6092
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006093/* This can be used to identify nodes that might not have a device
6094 * name associated. Since node and device names live in the same
6095 * namespace, the result is unambiguous. The exception is if both are
6096 * absent, then this returns an empty (non-null) string. */
6097const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6098{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006099 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006100}
6101
Markus Armbrusterc8433282012-06-05 16:49:24 +02006102int bdrv_get_flags(BlockDriverState *bs)
6103{
6104 return bs->open_flags;
6105}
6106
Peter Lieven3ac21622013-06-28 12:47:42 +02006107int bdrv_has_zero_init_1(BlockDriverState *bs)
6108{
6109 return 1;
6110}
6111
Kevin Wolff2feebb2010-04-14 17:30:35 +02006112int bdrv_has_zero_init(BlockDriverState *bs)
6113{
Max Reitz93393e62019-06-12 17:03:38 +02006114 BlockDriverState *filtered;
6115
Max Reitzd470ad42017-11-10 21:31:09 +01006116 if (!bs->drv) {
6117 return 0;
6118 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006119
Paolo Bonzini11212d82013-09-04 19:00:27 +02006120 /* If BS is a copy on write image, it is initialized to
6121 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02006122 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02006123 return 0;
6124 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02006125 if (bs->drv->bdrv_has_zero_init) {
6126 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02006127 }
Max Reitz93393e62019-06-12 17:03:38 +02006128
6129 filtered = bdrv_filter_bs(bs);
6130 if (filtered) {
6131 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006132 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006133
Peter Lieven3ac21622013-06-28 12:47:42 +02006134 /* safe default */
6135 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02006136}
6137
Peter Lieven4ce78692013-10-24 12:06:54 +02006138bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6139{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03006140 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02006141 return false;
6142 }
6143
Eric Blakee24d8132018-01-26 13:34:39 -06006144 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02006145}
6146
ths5fafdf22007-09-16 21:08:06 +00006147void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00006148 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00006149{
Kevin Wolf3574c602011-10-26 11:02:11 +02006150 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00006151}
6152
bellardfaea38e2006-08-05 21:31:00 +00006153int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6154{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006155 int ret;
bellardfaea38e2006-08-05 21:31:00 +00006156 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006157 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6158 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00006159 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006160 }
6161 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02006162 BlockDriverState *filtered = bdrv_filter_bs(bs);
6163 if (filtered) {
6164 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006165 }
bellardfaea38e2006-08-05 21:31:00 +00006166 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006167 }
bellardfaea38e2006-08-05 21:31:00 +00006168 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006169 ret = drv->bdrv_get_info(bs, bdi);
6170 if (ret < 0) {
6171 return ret;
6172 }
6173
6174 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6175 return -EINVAL;
6176 }
6177
6178 return 0;
bellardfaea38e2006-08-05 21:31:00 +00006179}
6180
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006181ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6182 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02006183{
6184 BlockDriver *drv = bs->drv;
6185 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006186 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02006187 }
6188 return NULL;
6189}
6190
Anton Nefedovd9245592019-09-23 15:17:37 +03006191BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6192{
6193 BlockDriver *drv = bs->drv;
6194 if (!drv || !drv->bdrv_get_specific_stats) {
6195 return NULL;
6196 }
6197 return drv->bdrv_get_specific_stats(bs);
6198}
6199
Eric Blakea31939e2015-11-18 01:52:54 -07006200void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006201{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006202 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006203 return;
6204 }
6205
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006206 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006207}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006208
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006209static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01006210{
6211 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02006212 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006213 }
6214
6215 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006216 assert(bs->drv->bdrv_debug_remove_breakpoint);
6217 return bs;
6218 }
6219
6220 return NULL;
6221}
6222
6223int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6224 const char *tag)
6225{
6226 bs = bdrv_find_debug_node(bs);
6227 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006228 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6229 }
6230
6231 return -ENOTSUP;
6232}
6233
Fam Zheng4cc70e92013-11-20 10:01:54 +08006234int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6235{
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006236 bs = bdrv_find_debug_node(bs);
6237 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006238 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6239 }
6240
6241 return -ENOTSUP;
6242}
6243
Kevin Wolf41c695c2012-12-06 14:32:58 +01006244int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6245{
Max Reitz938789e2014-03-10 23:44:08 +01006246 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006247 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006248 }
6249
6250 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6251 return bs->drv->bdrv_debug_resume(bs, tag);
6252 }
6253
6254 return -ENOTSUP;
6255}
6256
6257bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6258{
6259 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006260 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006261 }
6262
6263 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6264 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6265 }
6266
6267 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006268}
6269
Jeff Codyb1b1d782012-10-16 15:49:09 -04006270/* backing_file can either be relative, or absolute, or a protocol. If it is
6271 * relative, it must be relative to the chain. So, passing in bs->filename
6272 * from a BDS as backing_file should not be done, as that may be relative to
6273 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006274BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6275 const char *backing_file)
6276{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006277 char *filename_full = NULL;
6278 char *backing_file_full = NULL;
6279 char *filename_tmp = NULL;
6280 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006281 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006282 BlockDriverState *curr_bs = NULL;
6283 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006284 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006285
6286 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006287 return NULL;
6288 }
6289
Jeff Codyb1b1d782012-10-16 15:49:09 -04006290 filename_full = g_malloc(PATH_MAX);
6291 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006292
6293 is_protocol = path_has_protocol(backing_file);
6294
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006295 /*
6296 * Being largely a legacy function, skip any filters here
6297 * (because filters do not have normal filenames, so they cannot
6298 * match anyway; and allowing json:{} filenames is a bit out of
6299 * scope).
6300 */
6301 for (curr_bs = bdrv_skip_filters(bs);
6302 bdrv_cow_child(curr_bs) != NULL;
6303 curr_bs = bs_below)
6304 {
6305 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006306
Max Reitz0b877d02018-08-01 20:34:11 +02006307 if (bdrv_backing_overridden(curr_bs)) {
6308 /*
6309 * If the backing file was overridden, we can only compare
6310 * directly against the backing node's filename.
6311 */
6312
6313 if (!filenames_refreshed) {
6314 /*
6315 * This will automatically refresh all of the
6316 * filenames in the rest of the backing chain, so we
6317 * only need to do this once.
6318 */
6319 bdrv_refresh_filename(bs_below);
6320 filenames_refreshed = true;
6321 }
6322
6323 if (strcmp(backing_file, bs_below->filename) == 0) {
6324 retval = bs_below;
6325 break;
6326 }
6327 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6328 /*
6329 * If either of the filename paths is actually a protocol, then
6330 * compare unmodified paths; otherwise make paths relative.
6331 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006332 char *backing_file_full_ret;
6333
Jeff Codyb1b1d782012-10-16 15:49:09 -04006334 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006335 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006336 break;
6337 }
Jeff Cody418661e2017-01-25 20:08:20 -05006338 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006339 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6340 NULL);
6341 if (backing_file_full_ret) {
6342 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6343 g_free(backing_file_full_ret);
6344 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006345 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006346 break;
6347 }
Jeff Cody418661e2017-01-25 20:08:20 -05006348 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006349 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006350 /* If not an absolute filename path, make it relative to the current
6351 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006352 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6353 NULL);
6354 /* We are going to compare canonicalized absolute pathnames */
6355 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6356 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006357 continue;
6358 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006359 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006360
6361 /* We need to make sure the backing filename we are comparing against
6362 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006363 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6364 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6365 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006366 continue;
6367 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006368 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006369
6370 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006371 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006372 break;
6373 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006374 }
6375 }
6376
Jeff Codyb1b1d782012-10-16 15:49:09 -04006377 g_free(filename_full);
6378 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006379 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006380}
6381
bellardea2384d2004-08-01 21:59:26 +00006382void bdrv_init(void)
6383{
Kevin Wolfe5f05f82021-07-09 18:41:41 +02006384#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6385 use_bdrv_whitelist = 1;
6386#endif
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006387 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006388}
pbrookce1a14d2006-08-07 02:38:06 +00006389
Markus Armbrustereb852012009-10-27 18:41:44 +01006390void bdrv_init_with_whitelist(void)
6391{
6392 use_bdrv_whitelist = 1;
6393 bdrv_init();
6394}
6395
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006396int bdrv_activate(BlockDriverState *bs, Error **errp)
6397{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006398 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006399 Error *local_err = NULL;
6400 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006401 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006402
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006403 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006404 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006405 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006406
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006407 QLIST_FOREACH(child, &bs->children, next) {
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006408 bdrv_activate(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006409 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006410 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006411 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006412 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006413 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006414
Kevin Wolfdafe0962017-11-16 13:00:01 +01006415 /*
6416 * Update permissions, they may differ for inactive nodes.
6417 *
6418 * Note that the required permissions of inactive images are always a
6419 * subset of the permissions required after activating the image. This
6420 * allows us to just get the permissions upfront without restricting
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006421 * bdrv_co_invalidate_cache().
Kevin Wolfdafe0962017-11-16 13:00:01 +01006422 *
6423 * It also means that in error cases, we don't have to try and revert to
6424 * the old permissions (which is an operation that could fail, too). We can
6425 * just keep the extended permissions for the next time that an activation
6426 * of the image is tried.
6427 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006428 if (bs->open_flags & BDRV_O_INACTIVE) {
6429 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006430 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006431 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006432 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006433 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006434 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006435
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006436 ret = bdrv_invalidate_cache(bs, errp);
6437 if (ret < 0) {
6438 bs->open_flags |= BDRV_O_INACTIVE;
6439 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006440 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006441
Kevin Wolf7bb49412019-12-17 15:06:38 +01006442 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6443 bdrv_dirty_bitmap_skip_store(bm, false);
6444 }
6445
6446 ret = refresh_total_sectors(bs, bs->total_sectors);
6447 if (ret < 0) {
6448 bs->open_flags |= BDRV_O_INACTIVE;
6449 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006450 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006451 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006452 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006453
6454 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006455 if (parent->klass->activate) {
6456 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006457 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006458 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006459 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006460 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006461 }
6462 }
6463 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006464
6465 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006466}
6467
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006468int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6469{
6470 Error *local_err = NULL;
6471
6472 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6473
6474 if (bs->drv->bdrv_co_invalidate_cache) {
6475 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6476 if (local_err) {
6477 error_propagate(errp, local_err);
6478 return -EINVAL;
6479 }
6480 }
6481
6482 return 0;
6483}
6484
Emanuele Giuseppe Esposito3b717192022-02-09 05:54:51 -05006485void bdrv_activate_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006486{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006487 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006488 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006489
Kevin Wolf88be7b42016-05-20 18:49:07 +02006490 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006491 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006492 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006493
6494 aio_context_acquire(aio_context);
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006495 ret = bdrv_activate(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006496 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006497 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006498 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006499 return;
6500 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006501 }
6502}
6503
Kevin Wolf9e372712018-11-23 15:11:14 +01006504static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6505{
6506 BdrvChild *parent;
6507
6508 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006509 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006510 BlockDriverState *parent_bs = parent->opaque;
6511 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6512 return true;
6513 }
6514 }
6515 }
6516
6517 return false;
6518}
6519
6520static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006521{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006522 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006523 int ret;
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006524 uint64_t cumulative_perms, cumulative_shared_perms;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006525
Max Reitzd470ad42017-11-10 21:31:09 +01006526 if (!bs->drv) {
6527 return -ENOMEDIUM;
6528 }
6529
Kevin Wolf9e372712018-11-23 15:11:14 +01006530 /* Make sure that we don't inactivate a child before its parent.
6531 * It will be covered by recursion from the yet active parent. */
6532 if (bdrv_has_bds_parent(bs, true)) {
6533 return 0;
6534 }
6535
6536 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6537
6538 /* Inactivate this node */
6539 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006540 ret = bs->drv->bdrv_inactivate(bs);
6541 if (ret < 0) {
6542 return ret;
6543 }
6544 }
6545
Kevin Wolf9e372712018-11-23 15:11:14 +01006546 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006547 if (parent->klass->inactivate) {
6548 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006549 if (ret < 0) {
6550 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006551 }
6552 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006553 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006554
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006555 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6556 &cumulative_shared_perms);
6557 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6558 /* Our inactive parents still need write access. Inactivation failed. */
6559 return -EPERM;
6560 }
6561
Kevin Wolf9e372712018-11-23 15:11:14 +01006562 bs->open_flags |= BDRV_O_INACTIVE;
6563
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006564 /*
6565 * Update permissions, they may differ for inactive nodes.
6566 * We only tried to loosen restrictions, so errors are not fatal, ignore
6567 * them.
6568 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006569 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006570
6571 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006572 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006573 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006574 if (ret < 0) {
6575 return ret;
6576 }
6577 }
6578
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006579 return 0;
6580}
6581
6582int bdrv_inactivate_all(void)
6583{
Max Reitz79720af2016-03-16 19:54:44 +01006584 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006585 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006586 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006587 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006588
Kevin Wolf88be7b42016-05-20 18:49:07 +02006589 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006590 AioContext *aio_context = bdrv_get_aio_context(bs);
6591
6592 if (!g_slist_find(aio_ctxs, aio_context)) {
6593 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6594 aio_context_acquire(aio_context);
6595 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006596 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006597
Kevin Wolf9e372712018-11-23 15:11:14 +01006598 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6599 /* Nodes with BDS parents are covered by recursion from the last
6600 * parent that gets inactivated. Don't inactivate them a second
6601 * time if that has already happened. */
6602 if (bdrv_has_bds_parent(bs, false)) {
6603 continue;
6604 }
6605 ret = bdrv_inactivate_recurse(bs);
6606 if (ret < 0) {
6607 bdrv_next_cleanup(&it);
6608 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006609 }
6610 }
6611
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006612out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006613 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6614 AioContext *aio_context = ctx->data;
6615 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006616 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006617 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006618
6619 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006620}
6621
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006622/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006623/* removable device support */
6624
6625/**
6626 * Return TRUE if the media is present
6627 */
Max Reitze031f752015-10-19 17:53:11 +02006628bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006629{
6630 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006631 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006632
Max Reitze031f752015-10-19 17:53:11 +02006633 if (!drv) {
6634 return false;
6635 }
Max Reitz28d7a782015-10-19 17:53:13 +02006636 if (drv->bdrv_is_inserted) {
6637 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006638 }
Max Reitz28d7a782015-10-19 17:53:13 +02006639 QLIST_FOREACH(child, &bs->children, next) {
6640 if (!bdrv_is_inserted(child->bs)) {
6641 return false;
6642 }
6643 }
6644 return true;
bellard19cb3732006-08-19 11:45:59 +00006645}
6646
6647/**
bellard19cb3732006-08-19 11:45:59 +00006648 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6649 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006650void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006651{
6652 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006653
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006654 if (drv && drv->bdrv_eject) {
6655 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006656 }
bellard19cb3732006-08-19 11:45:59 +00006657}
6658
bellard19cb3732006-08-19 11:45:59 +00006659/**
6660 * Lock or unlock the media (if it is locked, the user won't be able
6661 * to eject it manually).
6662 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006663void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006664{
6665 BlockDriver *drv = bs->drv;
6666
Markus Armbruster025e8492011-09-06 18:58:47 +02006667 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006668
Markus Armbruster025e8492011-09-06 18:58:47 +02006669 if (drv && drv->bdrv_lock_medium) {
6670 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006671 }
6672}
ths985a03b2007-12-24 16:10:43 +00006673
Fam Zheng9fcb0252013-08-23 09:14:46 +08006674/* Get a reference to bs */
6675void bdrv_ref(BlockDriverState *bs)
6676{
6677 bs->refcnt++;
6678}
6679
6680/* Release a previously grabbed reference to bs.
6681 * If after releasing, reference count is zero, the BlockDriverState is
6682 * deleted. */
6683void bdrv_unref(BlockDriverState *bs)
6684{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006685 if (!bs) {
6686 return;
6687 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006688 assert(bs->refcnt > 0);
6689 if (--bs->refcnt == 0) {
6690 bdrv_delete(bs);
6691 }
6692}
6693
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006694struct BdrvOpBlocker {
6695 Error *reason;
6696 QLIST_ENTRY(BdrvOpBlocker) list;
6697};
6698
6699bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6700{
6701 BdrvOpBlocker *blocker;
6702 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6703 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6704 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006705 error_propagate_prepend(errp, error_copy(blocker->reason),
6706 "Node '%s' is busy: ",
6707 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006708 return true;
6709 }
6710 return false;
6711}
6712
6713void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6714{
6715 BdrvOpBlocker *blocker;
6716 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6717
Markus Armbruster5839e532014-08-19 10:31:08 +02006718 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006719 blocker->reason = reason;
6720 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6721}
6722
6723void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6724{
6725 BdrvOpBlocker *blocker, *next;
6726 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6727 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6728 if (blocker->reason == reason) {
6729 QLIST_REMOVE(blocker, list);
6730 g_free(blocker);
6731 }
6732 }
6733}
6734
6735void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6736{
6737 int i;
6738 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6739 bdrv_op_block(bs, i, reason);
6740 }
6741}
6742
6743void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6744{
6745 int i;
6746 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6747 bdrv_op_unblock(bs, i, reason);
6748 }
6749}
6750
6751bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6752{
6753 int i;
6754
6755 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6756 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6757 return false;
6758 }
6759 }
6760 return true;
6761}
6762
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006763void bdrv_img_create(const char *filename, const char *fmt,
6764 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006765 char *options, uint64_t img_size, int flags, bool quiet,
6766 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006767{
Chunyan Liu83d05212014-06-05 17:20:51 +08006768 QemuOptsList *create_opts = NULL;
6769 QemuOpts *opts = NULL;
6770 const char *backing_fmt, *backing_file;
6771 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006772 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006773 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006774 int ret = 0;
6775
6776 /* Find driver and parse its options */
6777 drv = bdrv_find_format(fmt);
6778 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006779 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006780 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006781 }
6782
Max Reitzb65a5e12015-02-05 13:58:12 -05006783 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006784 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006785 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006786 }
6787
Max Reitzc6149722014-12-02 18:32:45 +01006788 if (!drv->create_opts) {
6789 error_setg(errp, "Format driver '%s' does not support image creation",
6790 drv->format_name);
6791 return;
6792 }
6793
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006794 if (!proto_drv->create_opts) {
6795 error_setg(errp, "Protocol driver '%s' does not support image creation",
6796 proto_drv->format_name);
6797 return;
6798 }
6799
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006800 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006801 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006802 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006803
Chunyan Liu83d05212014-06-05 17:20:51 +08006804 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006805
6806 /* Parse -o options */
6807 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006808 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006809 goto out;
6810 }
6811 }
6812
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006813 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6814 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6815 } else if (img_size != UINT64_C(-1)) {
6816 error_setg(errp, "The image size must be specified only once");
6817 goto out;
6818 }
6819
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006820 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006821 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006822 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006823 error_setg(errp, "Backing file not supported for file format '%s'",
6824 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006825 goto out;
6826 }
6827 }
6828
6829 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006830 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006831 error_setg(errp, "Backing file format not supported for file "
6832 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006833 goto out;
6834 }
6835 }
6836
Chunyan Liu83d05212014-06-05 17:20:51 +08006837 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6838 if (backing_file) {
6839 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006840 error_setg(errp, "Error: Trying to create an image with the "
6841 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006842 goto out;
6843 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006844 if (backing_file[0] == '\0') {
6845 error_setg(errp, "Expected backing file name, got empty string");
6846 goto out;
6847 }
Jes Sorensen792da932010-12-16 13:52:17 +01006848 }
6849
Chunyan Liu83d05212014-06-05 17:20:51 +08006850 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006851
John Snow6e6e55f2017-07-17 20:34:22 -04006852 /* The size for the image must always be specified, unless we have a backing
6853 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006854 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006855 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6856 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006857 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006858 int back_flags;
6859 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006860
Max Reitz645ae7d2019-02-01 20:29:14 +01006861 full_backing =
6862 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6863 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006864 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006865 goto out;
6866 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006867 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006868
Max Reitzd5b23992021-06-22 16:00:30 +02006869 /*
6870 * No need to do I/O here, which allows us to open encrypted
6871 * backing images without needing the secret
6872 */
John Snow6e6e55f2017-07-17 20:34:22 -04006873 back_flags = flags;
6874 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02006875 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04006876
Fam Zhengcc954f02017-12-15 16:04:45 +08006877 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006878 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006879 qdict_put_str(backing_options, "driver", backing_fmt);
6880 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006881 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006882
6883 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6884 &local_err);
6885 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006886 if (!bs) {
6887 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006888 goto out;
6889 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006890 if (!backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07006891 error_setg(&local_err,
6892 "Backing file specified without backing format");
6893 error_append_hint(&local_err, "Detected format of %s.",
6894 bs->drv->format_name);
6895 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05006896 }
John Snow6e6e55f2017-07-17 20:34:22 -04006897 if (size == -1) {
6898 /* Opened BS, have no size */
6899 size = bdrv_getlength(bs);
6900 if (size < 0) {
6901 error_setg_errno(errp, -size, "Could not get size of '%s'",
6902 backing_file);
6903 bdrv_unref(bs);
6904 goto out;
6905 }
6906 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6907 }
6908 bdrv_unref(bs);
6909 }
Eric Blaked9f059a2020-07-06 15:39:54 -05006910 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6911 } else if (backing_file && !backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07006912 error_setg(&local_err,
6913 "Backing file specified without backing format");
6914 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05006915 }
John Snow6e6e55f2017-07-17 20:34:22 -04006916
6917 if (size == -1) {
6918 error_setg(errp, "Image creation needs a size parameter");
6919 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006920 }
6921
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006922 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02006923 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08006924 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006925 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05006926 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006927 }
Chunyan Liu83d05212014-06-05 17:20:51 +08006928
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006929 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08006930
Max Reitzcc84d902013-09-06 17:14:26 +02006931 if (ret == -EFBIG) {
6932 /* This is generally a better message than whatever the driver would
6933 * deliver (especially because of the cluster_size_hint), since that
6934 * is most probably not much different from "image too large". */
6935 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08006936 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02006937 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006938 }
Max Reitzcc84d902013-09-06 17:14:26 +02006939 error_setg(errp, "The image size is too large for file format '%s'"
6940 "%s", fmt, cluster_size_hint);
6941 error_free(local_err);
6942 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006943 }
6944
6945out:
Chunyan Liu83d05212014-06-05 17:20:51 +08006946 qemu_opts_del(opts);
6947 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03006948 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006949}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006950
6951AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6952{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00006953 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006954}
6955
Kevin Wolfe336fd42020-10-05 17:58:53 +02006956AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6957{
6958 Coroutine *self = qemu_coroutine_self();
6959 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6960 AioContext *new_ctx;
6961
6962 /*
6963 * Increase bs->in_flight to ensure that this operation is completed before
6964 * moving the node to a different AioContext. Read new_ctx only afterwards.
6965 */
6966 bdrv_inc_in_flight(bs);
6967
6968 new_ctx = bdrv_get_aio_context(bs);
6969 aio_co_reschedule_self(new_ctx);
6970 return old_ctx;
6971}
6972
6973void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6974{
6975 aio_co_reschedule_self(old_ctx);
6976 bdrv_dec_in_flight(bs);
6977}
6978
Kevin Wolf18c6ac12020-10-05 17:58:54 +02006979void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6980{
6981 AioContext *ctx = bdrv_get_aio_context(bs);
6982
6983 /* In the main thread, bs->aio_context won't change concurrently */
6984 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6985
6986 /*
6987 * We're in coroutine context, so we already hold the lock of the main
6988 * loop AioContext. Don't lock it twice to avoid deadlocks.
6989 */
6990 assert(qemu_in_coroutine());
6991 if (ctx != qemu_get_aio_context()) {
6992 aio_context_acquire(ctx);
6993 }
6994}
6995
6996void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6997{
6998 AioContext *ctx = bdrv_get_aio_context(bs);
6999
7000 assert(qemu_in_coroutine());
7001 if (ctx != qemu_get_aio_context()) {
7002 aio_context_release(ctx);
7003 }
7004}
7005
Fam Zheng052a7572017-04-10 20:09:25 +08007006void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7007{
7008 aio_co_enter(bdrv_get_aio_context(bs), co);
7009}
7010
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007011static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7012{
7013 QLIST_REMOVE(ban, list);
7014 g_free(ban);
7015}
7016
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007017static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007018{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007019 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007020
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007021 assert(!bs->walking_aio_notifiers);
7022 bs->walking_aio_notifiers = true;
7023 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7024 if (baf->deleted) {
7025 bdrv_do_remove_aio_context_notifier(baf);
7026 } else {
7027 baf->detach_aio_context(baf->opaque);
7028 }
Max Reitz33384422014-06-20 21:57:33 +02007029 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007030 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7031 * remove remaining aio notifiers if we aren't called again.
7032 */
7033 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02007034
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007035 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007036 bs->drv->bdrv_detach_aio_context(bs);
7037 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007038
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007039 if (bs->quiesce_counter) {
7040 aio_enable_external(bs->aio_context);
7041 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007042 bs->aio_context = NULL;
7043}
7044
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007045static void bdrv_attach_aio_context(BlockDriverState *bs,
7046 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007047{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007048 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007049
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007050 if (bs->quiesce_counter) {
7051 aio_disable_external(new_context);
7052 }
7053
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007054 bs->aio_context = new_context;
7055
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007056 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007057 bs->drv->bdrv_attach_aio_context(bs, new_context);
7058 }
Max Reitz33384422014-06-20 21:57:33 +02007059
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007060 assert(!bs->walking_aio_notifiers);
7061 bs->walking_aio_notifiers = true;
7062 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7063 if (ban->deleted) {
7064 bdrv_do_remove_aio_context_notifier(ban);
7065 } else {
7066 ban->attached_aio_context(new_context, ban->opaque);
7067 }
Max Reitz33384422014-06-20 21:57:33 +02007068 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007069 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007070}
7071
Kevin Wolf42a65f02019-05-07 18:31:38 +02007072/*
7073 * Changes the AioContext used for fd handlers, timers, and BHs by this
7074 * BlockDriverState and all its children and parents.
7075 *
Max Reitz43eaaae2019-07-22 15:30:54 +02007076 * Must be called from the main AioContext.
7077 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02007078 * The caller must own the AioContext lock for the old AioContext of bs, but it
7079 * must not own the AioContext lock for new_context (unless new_context is the
7080 * same as the current context of bs).
7081 *
7082 * @ignore will accumulate all visited BdrvChild object. The caller is
7083 * responsible for freeing the list afterwards.
7084 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02007085void bdrv_set_aio_context_ignore(BlockDriverState *bs,
7086 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007087{
Max Reitze037c092019-07-19 11:26:14 +02007088 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007089 GSList *children_to_process = NULL;
7090 GSList *parents_to_process = NULL;
7091 GSList *entry;
7092 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02007093
Max Reitz43eaaae2019-07-22 15:30:54 +02007094 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7095
Max Reitze037c092019-07-19 11:26:14 +02007096 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03007097 return;
7098 }
7099
Kevin Wolfd70d5952019-02-08 16:53:37 +01007100 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02007101
7102 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007103 if (g_slist_find(*ignore, child)) {
7104 continue;
7105 }
7106 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007107 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02007108 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007109
7110 QLIST_FOREACH(parent, &bs->parents, next_parent) {
7111 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007112 continue;
7113 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007114 *ignore = g_slist_prepend(*ignore, parent);
7115 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02007116 }
7117
Sergio Lopez722d8e72021-02-01 13:50:31 +01007118 for (entry = children_to_process;
7119 entry != NULL;
7120 entry = g_slist_next(entry)) {
7121 child = entry->data;
7122 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
7123 }
7124 g_slist_free(children_to_process);
7125
7126 for (entry = parents_to_process;
7127 entry != NULL;
7128 entry = g_slist_next(entry)) {
7129 parent = entry->data;
7130 assert(parent->klass->set_aio_ctx);
7131 parent->klass->set_aio_ctx(parent, new_context, ignore);
7132 }
7133 g_slist_free(parents_to_process);
7134
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007135 bdrv_detach_aio_context(bs);
7136
Max Reitze037c092019-07-19 11:26:14 +02007137 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02007138 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007139 aio_context_acquire(new_context);
7140 }
7141
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007142 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02007143
7144 /*
7145 * If this function was recursively called from
7146 * bdrv_set_aio_context_ignore(), there may be nodes in the
7147 * subtree that have not yet been moved to the new AioContext.
7148 * Release the old one so bdrv_drained_end() can poll them.
7149 */
Max Reitz43eaaae2019-07-22 15:30:54 +02007150 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007151 aio_context_release(old_context);
7152 }
7153
Kevin Wolfd70d5952019-02-08 16:53:37 +01007154 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02007155
Max Reitz43eaaae2019-07-22 15:30:54 +02007156 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007157 aio_context_acquire(old_context);
7158 }
Max Reitz43eaaae2019-07-22 15:30:54 +02007159 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007160 aio_context_release(new_context);
7161 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007162}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02007163
Kevin Wolf5d231842019-05-06 19:17:56 +02007164static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7165 GSList **ignore, Error **errp)
7166{
7167 if (g_slist_find(*ignore, c)) {
7168 return true;
7169 }
7170 *ignore = g_slist_prepend(*ignore, c);
7171
Max Reitzbd86fb92020-05-13 13:05:13 +02007172 /*
7173 * A BdrvChildClass that doesn't handle AioContext changes cannot
7174 * tolerate any AioContext changes
7175 */
7176 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007177 char *user = bdrv_child_user_desc(c);
7178 error_setg(errp, "Changing iothreads is not supported by %s", user);
7179 g_free(user);
7180 return false;
7181 }
Max Reitzbd86fb92020-05-13 13:05:13 +02007182 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007183 assert(!errp || *errp);
7184 return false;
7185 }
7186 return true;
7187}
7188
7189bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7190 GSList **ignore, Error **errp)
7191{
7192 if (g_slist_find(*ignore, c)) {
7193 return true;
7194 }
7195 *ignore = g_slist_prepend(*ignore, c);
7196 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
7197}
7198
7199/* @ignore will accumulate all visited BdrvChild object. The caller is
7200 * responsible for freeing the list afterwards. */
7201bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7202 GSList **ignore, Error **errp)
7203{
7204 BdrvChild *c;
7205
7206 if (bdrv_get_aio_context(bs) == ctx) {
7207 return true;
7208 }
7209
7210 QLIST_FOREACH(c, &bs->parents, next_parent) {
7211 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
7212 return false;
7213 }
7214 }
7215 QLIST_FOREACH(c, &bs->children, next) {
7216 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
7217 return false;
7218 }
7219 }
7220
7221 return true;
7222}
7223
7224int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7225 BdrvChild *ignore_child, Error **errp)
7226{
7227 GSList *ignore;
7228 bool ret;
7229
7230 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7231 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7232 g_slist_free(ignore);
7233
7234 if (!ret) {
7235 return -EPERM;
7236 }
7237
Kevin Wolf53a7d042019-05-06 19:17:59 +02007238 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7239 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7240 g_slist_free(ignore);
7241
Kevin Wolf5d231842019-05-06 19:17:56 +02007242 return 0;
7243}
7244
7245int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7246 Error **errp)
7247{
7248 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7249}
7250
Max Reitz33384422014-06-20 21:57:33 +02007251void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7252 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7253 void (*detach_aio_context)(void *opaque), void *opaque)
7254{
7255 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7256 *ban = (BdrvAioNotifier){
7257 .attached_aio_context = attached_aio_context,
7258 .detach_aio_context = detach_aio_context,
7259 .opaque = opaque
7260 };
7261
7262 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7263}
7264
7265void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7266 void (*attached_aio_context)(AioContext *,
7267 void *),
7268 void (*detach_aio_context)(void *),
7269 void *opaque)
7270{
7271 BdrvAioNotifier *ban, *ban_next;
7272
7273 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7274 if (ban->attached_aio_context == attached_aio_context &&
7275 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007276 ban->opaque == opaque &&
7277 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007278 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007279 if (bs->walking_aio_notifiers) {
7280 ban->deleted = true;
7281 } else {
7282 bdrv_do_remove_aio_context_notifier(ban);
7283 }
Max Reitz33384422014-06-20 21:57:33 +02007284 return;
7285 }
7286 }
7287
7288 abort();
7289}
7290
Max Reitz77485432014-10-27 11:12:50 +01007291int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007292 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007293 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007294 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007295{
Max Reitzd470ad42017-11-10 21:31:09 +01007296 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007297 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007298 return -ENOMEDIUM;
7299 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007300 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007301 error_setg(errp, "Block driver '%s' does not support option amendment",
7302 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007303 return -ENOTSUP;
7304 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007305 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7306 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007307}
Benoît Canetf6186f42013-10-02 14:33:48 +02007308
Max Reitz5d69b5a2020-02-18 11:34:41 +01007309/*
7310 * This function checks whether the given @to_replace is allowed to be
7311 * replaced by a node that always shows the same data as @bs. This is
7312 * used for example to verify whether the mirror job can replace
7313 * @to_replace by the target mirrored from @bs.
7314 * To be replaceable, @bs and @to_replace may either be guaranteed to
7315 * always show the same data (because they are only connected through
7316 * filters), or some driver may allow replacing one of its children
7317 * because it can guarantee that this child's data is not visible at
7318 * all (for example, for dissenting quorum children that have no other
7319 * parents).
7320 */
7321bool bdrv_recurse_can_replace(BlockDriverState *bs,
7322 BlockDriverState *to_replace)
7323{
Max Reitz93393e62019-06-12 17:03:38 +02007324 BlockDriverState *filtered;
7325
Max Reitz5d69b5a2020-02-18 11:34:41 +01007326 if (!bs || !bs->drv) {
7327 return false;
7328 }
7329
7330 if (bs == to_replace) {
7331 return true;
7332 }
7333
7334 /* See what the driver can do */
7335 if (bs->drv->bdrv_recurse_can_replace) {
7336 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7337 }
7338
7339 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007340 filtered = bdrv_filter_bs(bs);
7341 if (filtered) {
7342 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007343 }
7344
7345 /* Safe default */
7346 return false;
7347}
7348
Max Reitz810803a2020-02-18 11:34:44 +01007349/*
7350 * Check whether the given @node_name can be replaced by a node that
7351 * has the same data as @parent_bs. If so, return @node_name's BDS;
7352 * NULL otherwise.
7353 *
7354 * @node_name must be a (recursive) *child of @parent_bs (or this
7355 * function will return NULL).
7356 *
7357 * The result (whether the node can be replaced or not) is only valid
7358 * for as long as no graph or permission changes occur.
7359 */
Wen Congyange12f3782015-07-17 10:12:22 +08007360BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7361 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007362{
7363 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007364 AioContext *aio_context;
7365
Benoît Canet09158f02014-06-27 18:25:25 +02007366 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007367 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007368 return NULL;
7369 }
7370
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007371 aio_context = bdrv_get_aio_context(to_replace_bs);
7372 aio_context_acquire(aio_context);
7373
Benoît Canet09158f02014-06-27 18:25:25 +02007374 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007375 to_replace_bs = NULL;
7376 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007377 }
7378
7379 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7380 * most non filter in order to prevent data corruption.
7381 * Another benefit is that this tests exclude backing files which are
7382 * blocked by the backing blockers.
7383 */
Max Reitz810803a2020-02-18 11:34:44 +01007384 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7385 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7386 "because it cannot be guaranteed that doing so would not "
7387 "lead to an abrupt change of visible data",
7388 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007389 to_replace_bs = NULL;
7390 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007391 }
7392
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007393out:
7394 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007395 return to_replace_bs;
7396}
Ming Lei448ad912014-07-04 18:04:33 +08007397
Max Reitz97e2f022019-02-01 20:29:27 +01007398/**
7399 * Iterates through the list of runtime option keys that are said to
7400 * be "strong" for a BDS. An option is called "strong" if it changes
7401 * a BDS's data. For example, the null block driver's "size" and
7402 * "read-zeroes" options are strong, but its "latency-ns" option is
7403 * not.
7404 *
7405 * If a key returned by this function ends with a dot, all options
7406 * starting with that prefix are strong.
7407 */
7408static const char *const *strong_options(BlockDriverState *bs,
7409 const char *const *curopt)
7410{
7411 static const char *const global_options[] = {
7412 "driver", "filename", NULL
7413 };
7414
7415 if (!curopt) {
7416 return &global_options[0];
7417 }
7418
7419 curopt++;
7420 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7421 curopt = bs->drv->strong_runtime_opts;
7422 }
7423
7424 return (curopt && *curopt) ? curopt : NULL;
7425}
7426
7427/**
7428 * Copies all strong runtime options from bs->options to the given
7429 * QDict. The set of strong option keys is determined by invoking
7430 * strong_options().
7431 *
7432 * Returns true iff any strong option was present in bs->options (and
7433 * thus copied to the target QDict) with the exception of "filename"
7434 * and "driver". The caller is expected to use this value to decide
7435 * whether the existence of strong options prevents the generation of
7436 * a plain filename.
7437 */
7438static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7439{
7440 bool found_any = false;
7441 const char *const *option_name = NULL;
7442
7443 if (!bs->drv) {
7444 return false;
7445 }
7446
7447 while ((option_name = strong_options(bs, option_name))) {
7448 bool option_given = false;
7449
7450 assert(strlen(*option_name) > 0);
7451 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7452 QObject *entry = qdict_get(bs->options, *option_name);
7453 if (!entry) {
7454 continue;
7455 }
7456
7457 qdict_put_obj(d, *option_name, qobject_ref(entry));
7458 option_given = true;
7459 } else {
7460 const QDictEntry *entry;
7461 for (entry = qdict_first(bs->options); entry;
7462 entry = qdict_next(bs->options, entry))
7463 {
7464 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7465 qdict_put_obj(d, qdict_entry_key(entry),
7466 qobject_ref(qdict_entry_value(entry)));
7467 option_given = true;
7468 }
7469 }
7470 }
7471
7472 /* While "driver" and "filename" need to be included in a JSON filename,
7473 * their existence does not prohibit generation of a plain filename. */
7474 if (!found_any && option_given &&
7475 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7476 {
7477 found_any = true;
7478 }
7479 }
7480
Max Reitz62a01a272019-02-01 20:29:34 +01007481 if (!qdict_haskey(d, "driver")) {
7482 /* Drivers created with bdrv_new_open_driver() may not have a
7483 * @driver option. Add it here. */
7484 qdict_put_str(d, "driver", bs->drv->format_name);
7485 }
7486
Max Reitz97e2f022019-02-01 20:29:27 +01007487 return found_any;
7488}
7489
Max Reitz90993622019-02-01 20:29:09 +01007490/* Note: This function may return false positives; it may return true
7491 * even if opening the backing file specified by bs's image header
7492 * would result in exactly bs->backing. */
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -05007493static bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007494{
7495 if (bs->backing) {
7496 return strcmp(bs->auto_backing_file,
7497 bs->backing->bs->filename);
7498 } else {
7499 /* No backing BDS, so if the image header reports any backing
7500 * file, it must have been suppressed */
7501 return bs->auto_backing_file[0] != '\0';
7502 }
7503}
7504
Max Reitz91af7012014-07-18 20:24:56 +02007505/* Updates the following BDS fields:
7506 * - exact_filename: A filename which may be used for opening a block device
7507 * which (mostly) equals the given BDS (even without any
7508 * other options; so reading and writing must return the same
7509 * results, but caching etc. may be different)
7510 * - full_open_options: Options which, when given when opening a block device
7511 * (without a filename), result in a BDS (mostly)
7512 * equalling the given one
7513 * - filename: If exact_filename is set, it is copied here. Otherwise,
7514 * full_open_options is converted to a JSON object, prefixed with
7515 * "json:" (for use through the JSON pseudo protocol) and put here.
7516 */
7517void bdrv_refresh_filename(BlockDriverState *bs)
7518{
7519 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007520 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007521 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007522 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007523 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007524 bool generate_json_filename; /* Whether our default implementation should
7525 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007526
7527 if (!drv) {
7528 return;
7529 }
7530
Max Reitze24518e2019-02-01 20:29:06 +01007531 /* This BDS's file name may depend on any of its children's file names, so
7532 * refresh those first */
7533 QLIST_FOREACH(child, &bs->children, next) {
7534 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007535 }
7536
Max Reitzbb808d52019-02-01 20:29:07 +01007537 if (bs->implicit) {
7538 /* For implicit nodes, just copy everything from the single child */
7539 child = QLIST_FIRST(&bs->children);
7540 assert(QLIST_NEXT(child, next) == NULL);
7541
7542 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7543 child->bs->exact_filename);
7544 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7545
Pan Nengyuancb895612020-01-16 16:56:00 +08007546 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007547 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7548
7549 return;
7550 }
7551
Max Reitz90993622019-02-01 20:29:09 +01007552 backing_overridden = bdrv_backing_overridden(bs);
7553
7554 if (bs->open_flags & BDRV_O_NO_IO) {
7555 /* Without I/O, the backing file does not change anything.
7556 * Therefore, in such a case (primarily qemu-img), we can
7557 * pretend the backing file has not been overridden even if
7558 * it technically has been. */
7559 backing_overridden = false;
7560 }
7561
Max Reitz97e2f022019-02-01 20:29:27 +01007562 /* Gather the options QDict */
7563 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007564 generate_json_filename = append_strong_runtime_options(opts, bs);
7565 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007566
7567 if (drv->bdrv_gather_child_options) {
7568 /* Some block drivers may not want to present all of their children's
7569 * options, or name them differently from BdrvChild.name */
7570 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7571 } else {
7572 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007573 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007574 /* We can skip the backing BDS if it has not been overridden */
7575 continue;
7576 }
7577
7578 qdict_put(opts, child->name,
7579 qobject_ref(child->bs->full_open_options));
7580 }
7581
7582 if (backing_overridden && !bs->backing) {
7583 /* Force no backing file */
7584 qdict_put_null(opts, "backing");
7585 }
7586 }
7587
7588 qobject_unref(bs->full_open_options);
7589 bs->full_open_options = opts;
7590
Max Reitz52f72d62019-06-12 17:43:03 +02007591 primary_child_bs = bdrv_primary_bs(bs);
7592
Max Reitz998b3a12019-02-01 20:29:28 +01007593 if (drv->bdrv_refresh_filename) {
7594 /* Obsolete information is of no use here, so drop the old file name
7595 * information before refreshing it */
7596 bs->exact_filename[0] = '\0';
7597
7598 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007599 } else if (primary_child_bs) {
7600 /*
7601 * Try to reconstruct valid information from the underlying
7602 * file -- this only works for format nodes (filter nodes
7603 * cannot be probed and as such must be selected by the user
7604 * either through an options dict, or through a special
7605 * filename which the filter driver must construct in its
7606 * .bdrv_refresh_filename() implementation).
7607 */
Max Reitz998b3a12019-02-01 20:29:28 +01007608
7609 bs->exact_filename[0] = '\0';
7610
Max Reitzfb695c72019-02-01 20:29:29 +01007611 /*
7612 * We can use the underlying file's filename if:
7613 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007614 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007615 * - the file is a protocol BDS, and
7616 * - opening that file (as this BDS's format) will automatically create
7617 * the BDS tree we have right now, that is:
7618 * - the user did not significantly change this BDS's behavior with
7619 * some explicit (strong) options
7620 * - no non-file child of this BDS has been overridden by the user
7621 * Both of these conditions are represented by generate_json_filename.
7622 */
Max Reitz52f72d62019-06-12 17:43:03 +02007623 if (primary_child_bs->exact_filename[0] &&
7624 primary_child_bs->drv->bdrv_file_open &&
7625 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007626 {
Max Reitz52f72d62019-06-12 17:43:03 +02007627 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007628 }
7629 }
7630
Max Reitz91af7012014-07-18 20:24:56 +02007631 if (bs->exact_filename[0]) {
7632 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007633 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007634 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007635 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007636 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007637 /* Give user a hint if we truncated things. */
7638 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7639 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007640 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007641 }
7642}
Wen Congyange06018a2016-05-10 15:36:37 +08007643
Max Reitz1e89d0f2019-02-01 20:29:18 +01007644char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7645{
7646 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007647 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007648
7649 if (!drv) {
7650 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7651 return NULL;
7652 }
7653
7654 if (drv->bdrv_dirname) {
7655 return drv->bdrv_dirname(bs, errp);
7656 }
7657
Max Reitz52f72d62019-06-12 17:43:03 +02007658 child_bs = bdrv_primary_bs(bs);
7659 if (child_bs) {
7660 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007661 }
7662
7663 bdrv_refresh_filename(bs);
7664 if (bs->exact_filename[0] != '\0') {
7665 return path_combine(bs->exact_filename, "");
7666 }
7667
7668 error_setg(errp, "Cannot generate a base directory for %s nodes",
7669 drv->format_name);
7670 return NULL;
7671}
7672
Wen Congyange06018a2016-05-10 15:36:37 +08007673/*
7674 * Hot add/remove a BDS's child. So the user can take a child offline when
7675 * it is broken and take a new child online
7676 */
7677void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7678 Error **errp)
7679{
7680
7681 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7682 error_setg(errp, "The node %s does not support adding a child",
7683 bdrv_get_device_or_node_name(parent_bs));
7684 return;
7685 }
7686
7687 if (!QLIST_EMPTY(&child_bs->parents)) {
7688 error_setg(errp, "The node %s already has a parent",
7689 child_bs->node_name);
7690 return;
7691 }
7692
7693 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7694}
7695
7696void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7697{
7698 BdrvChild *tmp;
7699
7700 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7701 error_setg(errp, "The node %s does not support removing a child",
7702 bdrv_get_device_or_node_name(parent_bs));
7703 return;
7704 }
7705
7706 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7707 if (tmp == child) {
7708 break;
7709 }
7710 }
7711
7712 if (!tmp) {
7713 error_setg(errp, "The node %s does not have a child named %s",
7714 bdrv_get_device_or_node_name(parent_bs),
7715 bdrv_get_device_or_node_name(child->bs));
7716 return;
7717 }
7718
7719 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7720}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007721
7722int bdrv_make_empty(BdrvChild *c, Error **errp)
7723{
7724 BlockDriver *drv = c->bs->drv;
7725 int ret;
7726
7727 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7728
7729 if (!drv->bdrv_make_empty) {
7730 error_setg(errp, "%s does not support emptying nodes",
7731 drv->format_name);
7732 return -ENOTSUP;
7733 }
7734
7735 ret = drv->bdrv_make_empty(c->bs);
7736 if (ret < 0) {
7737 error_setg_errno(errp, -ret, "Failed to empty %s",
7738 c->bs->filename);
7739 return ret;
7740 }
7741
7742 return 0;
7743}
Max Reitz9a6fc882019-05-31 15:23:11 +02007744
7745/*
7746 * Return the child that @bs acts as an overlay for, and from which data may be
7747 * copied in COW or COR operations. Usually this is the backing file.
7748 */
7749BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7750{
7751 if (!bs || !bs->drv) {
7752 return NULL;
7753 }
7754
7755 if (bs->drv->is_filter) {
7756 return NULL;
7757 }
7758
7759 if (!bs->backing) {
7760 return NULL;
7761 }
7762
7763 assert(bs->backing->role & BDRV_CHILD_COW);
7764 return bs->backing;
7765}
7766
7767/*
7768 * If @bs acts as a filter for exactly one of its children, return
7769 * that child.
7770 */
7771BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7772{
7773 BdrvChild *c;
7774
7775 if (!bs || !bs->drv) {
7776 return NULL;
7777 }
7778
7779 if (!bs->drv->is_filter) {
7780 return NULL;
7781 }
7782
7783 /* Only one of @backing or @file may be used */
7784 assert(!(bs->backing && bs->file));
7785
7786 c = bs->backing ?: bs->file;
7787 if (!c) {
7788 return NULL;
7789 }
7790
7791 assert(c->role & BDRV_CHILD_FILTERED);
7792 return c;
7793}
7794
7795/*
7796 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7797 * whichever is non-NULL.
7798 *
7799 * Return NULL if both are NULL.
7800 */
7801BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7802{
7803 BdrvChild *cow_child = bdrv_cow_child(bs);
7804 BdrvChild *filter_child = bdrv_filter_child(bs);
7805
7806 /* Filter nodes cannot have COW backing files */
7807 assert(!(cow_child && filter_child));
7808
7809 return cow_child ?: filter_child;
7810}
7811
7812/*
7813 * Return the primary child of this node: For filters, that is the
7814 * filtered child. For other nodes, that is usually the child storing
7815 * metadata.
7816 * (A generally more helpful description is that this is (usually) the
7817 * child that has the same filename as @bs.)
7818 *
7819 * Drivers do not necessarily have a primary child; for example quorum
7820 * does not.
7821 */
7822BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7823{
7824 BdrvChild *c, *found = NULL;
7825
7826 QLIST_FOREACH(c, &bs->children, next) {
7827 if (c->role & BDRV_CHILD_PRIMARY) {
7828 assert(!found);
7829 found = c;
7830 }
7831 }
7832
7833 return found;
7834}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007835
7836static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7837 bool stop_on_explicit_filter)
7838{
7839 BdrvChild *c;
7840
7841 if (!bs) {
7842 return NULL;
7843 }
7844
7845 while (!(stop_on_explicit_filter && !bs->implicit)) {
7846 c = bdrv_filter_child(bs);
7847 if (!c) {
7848 /*
7849 * A filter that is embedded in a working block graph must
7850 * have a child. Assert this here so this function does
7851 * not return a filter node that is not expected by the
7852 * caller.
7853 */
7854 assert(!bs->drv || !bs->drv->is_filter);
7855 break;
7856 }
7857 bs = c->bs;
7858 }
7859 /*
7860 * Note that this treats nodes with bs->drv == NULL as not being
7861 * filters (bs->drv == NULL should be replaced by something else
7862 * anyway).
7863 * The advantage of this behavior is that this function will thus
7864 * always return a non-NULL value (given a non-NULL @bs).
7865 */
7866
7867 return bs;
7868}
7869
7870/*
7871 * Return the first BDS that has not been added implicitly or that
7872 * does not have a filtered child down the chain starting from @bs
7873 * (including @bs itself).
7874 */
7875BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7876{
7877 return bdrv_do_skip_filters(bs, true);
7878}
7879
7880/*
7881 * Return the first BDS that does not have a filtered child down the
7882 * chain starting from @bs (including @bs itself).
7883 */
7884BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7885{
7886 return bdrv_do_skip_filters(bs, false);
7887}
7888
7889/*
7890 * For a backing chain, return the first non-filter backing image of
7891 * the first non-filter image.
7892 */
7893BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7894{
7895 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7896}
Hanna Reitz0bc329f2021-08-12 10:41:44 +02007897
7898/**
7899 * Check whether [offset, offset + bytes) overlaps with the cached
7900 * block-status data region.
7901 *
7902 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
7903 * which is what bdrv_bsc_is_data()'s interface needs.
7904 * Otherwise, *pnum is not touched.
7905 */
7906static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
7907 int64_t offset, int64_t bytes,
7908 int64_t *pnum)
7909{
7910 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
7911 bool overlaps;
7912
7913 overlaps =
7914 qatomic_read(&bsc->valid) &&
7915 ranges_overlap(offset, bytes, bsc->data_start,
7916 bsc->data_end - bsc->data_start);
7917
7918 if (overlaps && pnum) {
7919 *pnum = bsc->data_end - offset;
7920 }
7921
7922 return overlaps;
7923}
7924
7925/**
7926 * See block_int.h for this function's documentation.
7927 */
7928bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
7929{
7930 RCU_READ_LOCK_GUARD();
7931
7932 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
7933}
7934
7935/**
7936 * See block_int.h for this function's documentation.
7937 */
7938void bdrv_bsc_invalidate_range(BlockDriverState *bs,
7939 int64_t offset, int64_t bytes)
7940{
7941 RCU_READ_LOCK_GUARD();
7942
7943 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
7944 qatomic_set(&bs->block_status_cache->valid, false);
7945 }
7946}
7947
7948/**
7949 * See block_int.h for this function's documentation.
7950 */
7951void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
7952{
7953 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
7954 BdrvBlockStatusCache *old_bsc;
7955
7956 *new_bsc = (BdrvBlockStatusCache) {
7957 .valid = true,
7958 .data_start = offset,
7959 .data_end = offset + bytes,
7960 };
7961
7962 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
7963
7964 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
7965 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
7966 if (old_bsc) {
7967 g_free_rcu(old_bsc, rcu);
7968 }
7969}