blob: ed1026e4d886ab5376573b2c056d220e0acced2e [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
Emanuele Giuseppe Esposito3b491a92022-03-03 10:15:48 -050070/* Protected by BQL */
Benoît Canetdc364f42014-01-23 21:31:32 +010071static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
72 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
73
Emanuele Giuseppe Esposito3b491a92022-03-03 10:15:48 -050074/* Protected by BQL */
Max Reitz2c1d04e2016-01-29 16:36:11 +010075static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
76 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
77
Emanuele Giuseppe Esposito3b491a92022-03-03 10:15:48 -050078/* Protected by BQL */
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010079static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000081
Max Reitz5b363932016-05-17 16:41:31 +020082static BlockDriverState *bdrv_open_inherit(const char *filename,
83 const char *reference,
84 QDict *options, int flags,
85 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +020086 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +020087 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +020088 Error **errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +020089
Kevin Wolfbfb8aa62021-10-18 15:47:14 +020090static bool bdrv_recurse_has_child(BlockDriverState *bs,
91 BlockDriverState *child);
92
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +010093static void bdrv_child_free(BdrvChild *child);
Hanna Reitzbe64bbb2021-11-15 15:54:01 +010094static void bdrv_replace_child_noperm(BdrvChild **child,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +010095 BlockDriverState *new_bs,
96 bool free_empty_child);
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +030097static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
98 BdrvChild *child,
99 Transaction *tran);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +0300100static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
101 Transaction *tran);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +0300102
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +0300103static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
104 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +0300105 Transaction *change_child_tran, Error **errp);
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +0300106static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
107static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
108
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -0500109static bool bdrv_backing_overridden(BlockDriverState *bs);
110
Markus Armbrustereb852012009-10-27 18:41:44 +0100111/* If non-zero, use only whitelisted block drivers */
112static int use_bdrv_whitelist;
113
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000114#ifdef _WIN32
115static int is_windows_drive_prefix(const char *filename)
116{
117 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
118 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
119 filename[1] == ':');
120}
121
122int is_windows_drive(const char *filename)
123{
124 if (is_windows_drive_prefix(filename) &&
125 filename[2] == '\0')
126 return 1;
127 if (strstart(filename, "\\\\.\\", NULL) ||
128 strstart(filename, "//./", NULL))
129 return 1;
130 return 0;
131}
132#endif
133
Kevin Wolf339064d2013-11-28 10:23:32 +0100134size_t bdrv_opt_mem_align(BlockDriverState *bs)
135{
136 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300137 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800138 return MAX(4096, qemu_real_host_page_size);
Kevin Wolf339064d2013-11-28 10:23:32 +0100139 }
140
141 return bs->bl.opt_mem_alignment;
142}
143
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300144size_t bdrv_min_mem_align(BlockDriverState *bs)
145{
146 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300147 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800148 return MAX(4096, qemu_real_host_page_size);
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300149 }
150
151 return bs->bl.min_mem_alignment;
152}
153
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000154/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100155int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000156{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200157 const char *p;
158
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000159#ifdef _WIN32
160 if (is_windows_drive(path) ||
161 is_windows_drive_prefix(path)) {
162 return 0;
163 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200164 p = path + strcspn(path, ":/\\");
165#else
166 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000167#endif
168
Paolo Bonzini947995c2012-05-08 16:51:48 +0200169 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000170}
171
bellard83f64092006-08-01 16:21:11 +0000172int path_is_absolute(const char *path)
173{
bellard21664422007-01-07 18:22:37 +0000174#ifdef _WIN32
175 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200176 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000177 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200178 }
179 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000180#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200181 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000182#endif
bellard83f64092006-08-01 16:21:11 +0000183}
184
Max Reitz009b03a2019-02-01 20:29:13 +0100185/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000186 path to it by considering it is relative to base_path. URL are
187 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100188char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000189{
Max Reitz009b03a2019-02-01 20:29:13 +0100190 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000191 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100192 char *result;
bellard83f64092006-08-01 16:21:11 +0000193 int len;
194
bellard83f64092006-08-01 16:21:11 +0000195 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100196 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000197 }
Max Reitz009b03a2019-02-01 20:29:13 +0100198
199 if (path_has_protocol(base_path)) {
200 protocol_stripped = strchr(base_path, ':');
201 if (protocol_stripped) {
202 protocol_stripped++;
203 }
204 }
205 p = protocol_stripped ?: base_path;
206
207 p1 = strrchr(base_path, '/');
208#ifdef _WIN32
209 {
210 const char *p2;
211 p2 = strrchr(base_path, '\\');
212 if (!p1 || p2 > p1) {
213 p1 = p2;
214 }
215 }
216#endif
217 if (p1) {
218 p1++;
219 } else {
220 p1 = base_path;
221 }
222 if (p1 > p) {
223 p = p1;
224 }
225 len = p - base_path;
226
227 result = g_malloc(len + strlen(filename) + 1);
228 memcpy(result, base_path, len);
229 strcpy(result + len, filename);
230
231 return result;
232}
233
Max Reitz03c320d2017-05-22 21:52:16 +0200234/*
235 * Helper function for bdrv_parse_filename() implementations to remove optional
236 * protocol prefixes (especially "file:") from a filename and for putting the
237 * stripped filename into the options QDict if there is such a prefix.
238 */
239void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
240 QDict *options)
241{
242 if (strstart(filename, prefix, &filename)) {
243 /* Stripping the explicit protocol prefix may result in a protocol
244 * prefix being (wrongly) detected (if the filename contains a colon) */
245 if (path_has_protocol(filename)) {
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100246 GString *fat_filename;
Max Reitz03c320d2017-05-22 21:52:16 +0200247
248 /* This means there is some colon before the first slash; therefore,
249 * this cannot be an absolute path */
250 assert(!path_is_absolute(filename));
251
252 /* And we can thus fix the protocol detection issue by prefixing it
253 * by "./" */
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100254 fat_filename = g_string_new("./");
255 g_string_append(fat_filename, filename);
Max Reitz03c320d2017-05-22 21:52:16 +0200256
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100257 assert(!path_has_protocol(fat_filename->str));
Max Reitz03c320d2017-05-22 21:52:16 +0200258
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100259 qdict_put(options, "filename",
260 qstring_from_gstring(fat_filename));
Max Reitz03c320d2017-05-22 21:52:16 +0200261 } else {
262 /* If no protocol prefix was detected, we can use the shortened
263 * filename as-is */
264 qdict_put_str(options, "filename", filename);
265 }
266 }
267}
268
269
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200270/* Returns whether the image file is opened as read-only. Note that this can
271 * return false and writing to the image file is still not possible because the
272 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400273bool bdrv_is_read_only(BlockDriverState *bs)
274{
Vladimir Sementsov-Ogievskiy975da072021-05-27 18:40:55 +0300275 return !(bs->open_flags & BDRV_O_RDWR);
Jeff Cody93ed5242017-04-07 16:55:28 -0400276}
277
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200278int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
279 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400280{
Jeff Codye2b82472017-04-07 16:55:26 -0400281 /* Do not set read_only if copy_on_read is enabled */
282 if (bs->copy_on_read && read_only) {
283 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
284 bdrv_get_device_or_node_name(bs));
285 return -EINVAL;
286 }
287
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400288 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200289 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
290 !ignore_allow_rdw)
291 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400292 error_setg(errp, "Node '%s' is read only",
293 bdrv_get_device_or_node_name(bs));
294 return -EPERM;
295 }
296
Jeff Cody45803a02017-04-07 16:55:29 -0400297 return 0;
298}
299
Kevin Wolfeaa24102018-10-12 11:27:41 +0200300/*
301 * Called by a driver that can only provide a read-only image.
302 *
303 * Returns 0 if the node is already read-only or it could switch the node to
304 * read-only because BDRV_O_AUTO_RDONLY is set.
305 *
306 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
307 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
308 * is not NULL, it is used as the error message for the Error object.
309 */
310int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
311 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400312{
313 int ret = 0;
314
Kevin Wolfeaa24102018-10-12 11:27:41 +0200315 if (!(bs->open_flags & BDRV_O_RDWR)) {
316 return 0;
317 }
318 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
319 goto fail;
320 }
321
322 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400323 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200324 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400325 }
326
Kevin Wolfeaa24102018-10-12 11:27:41 +0200327 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200328
Jeff Codye2b82472017-04-07 16:55:26 -0400329 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200330
331fail:
332 error_setg(errp, "%s", errmsg ?: "Image is read-only");
333 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400334}
335
Max Reitz645ae7d2019-02-01 20:29:14 +0100336/*
337 * If @backing is empty, this function returns NULL without setting
338 * @errp. In all other cases, NULL will only be returned with @errp
339 * set.
340 *
341 * Therefore, a return value of NULL without @errp set means that
342 * there is no backing file; if @errp is set, there is one but its
343 * absolute filename cannot be generated.
344 */
345char *bdrv_get_full_backing_filename_from_filename(const char *backed,
346 const char *backing,
347 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100348{
Max Reitz645ae7d2019-02-01 20:29:14 +0100349 if (backing[0] == '\0') {
350 return NULL;
351 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
352 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100353 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
354 error_setg(errp, "Cannot use relative backing file names for '%s'",
355 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100356 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100357 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100358 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100359 }
360}
361
Max Reitz9f4793d2019-02-01 20:29:16 +0100362/*
363 * If @filename is empty or NULL, this function returns NULL without
364 * setting @errp. In all other cases, NULL will only be returned with
365 * @errp set.
366 */
367static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
368 const char *filename, Error **errp)
369{
Max Reitz8df68612019-02-01 20:29:23 +0100370 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100371
Max Reitz8df68612019-02-01 20:29:23 +0100372 if (!filename || filename[0] == '\0') {
373 return NULL;
374 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
375 return g_strdup(filename);
376 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100377
Max Reitz8df68612019-02-01 20:29:23 +0100378 dir = bdrv_dirname(relative_to, errp);
379 if (!dir) {
380 return NULL;
381 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100382
Max Reitz8df68612019-02-01 20:29:23 +0100383 full_name = g_strconcat(dir, filename, NULL);
384 g_free(dir);
385 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100386}
387
Max Reitz6b6833c2019-02-01 20:29:15 +0100388char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200389{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500390 GLOBAL_STATE_CODE();
Max Reitz9f4793d2019-02-01 20:29:16 +0100391 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200392}
393
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100394void bdrv_register(BlockDriver *bdrv)
395{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100396 assert(bdrv->format_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500397 GLOBAL_STATE_CODE();
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100398 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000399}
bellardb3380822004-03-14 21:38:54 +0000400
Markus Armbrustere4e99862014-10-07 13:59:03 +0200401BlockDriverState *bdrv_new(void)
402{
403 BlockDriverState *bs;
404 int i;
405
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500406 GLOBAL_STATE_CODE();
407
Markus Armbruster5839e532014-08-19 10:31:08 +0200408 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800409 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800410 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
411 QLIST_INIT(&bs->op_blockers[i]);
412 }
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200413 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200414 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800415 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200416 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200417
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300418 qemu_co_queue_init(&bs->flush_queue);
419
Hanna Reitz0bc329f2021-08-12 10:41:44 +0200420 qemu_co_mutex_init(&bs->bsc_modify_lock);
421 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
422
Kevin Wolf0f122642018-03-28 18:29:18 +0200423 for (i = 0; i < bdrv_drain_all_count; i++) {
424 bdrv_drained_begin(bs);
425 }
426
Max Reitz2c1d04e2016-01-29 16:36:11 +0100427 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
428
bellardb3380822004-03-14 21:38:54 +0000429 return bs;
430}
431
Marc Mari88d88792016-08-12 09:27:03 -0400432static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000433{
434 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400435
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100436 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
437 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000438 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100439 }
bellardea2384d2004-08-01 21:59:26 +0000440 }
Marc Mari88d88792016-08-12 09:27:03 -0400441
bellardea2384d2004-08-01 21:59:26 +0000442 return NULL;
443}
444
Marc Mari88d88792016-08-12 09:27:03 -0400445BlockDriver *bdrv_find_format(const char *format_name)
446{
447 BlockDriver *drv1;
448 int i;
449
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500450 GLOBAL_STATE_CODE();
451
Marc Mari88d88792016-08-12 09:27:03 -0400452 drv1 = bdrv_do_find_format(format_name);
453 if (drv1) {
454 return drv1;
455 }
456
457 /* The driver isn't registered, maybe we need to load a module */
458 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
459 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
460 block_module_load_one(block_driver_modules[i].library_name);
461 break;
462 }
463 }
464
465 return bdrv_do_find_format(format_name);
466}
467
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300468static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100469{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800470 static const char *whitelist_rw[] = {
471 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200472 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800473 };
474 static const char *whitelist_ro[] = {
475 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200476 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100477 };
478 const char **p;
479
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800480 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100481 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800482 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100483
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800484 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300485 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100486 return 1;
487 }
488 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800489 if (read_only) {
490 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300491 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800492 return 1;
493 }
494 }
495 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100496 return 0;
497}
498
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300499int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
500{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500501 GLOBAL_STATE_CODE();
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300502 return bdrv_format_is_whitelisted(drv->format_name, read_only);
503}
504
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000505bool bdrv_uses_whitelist(void)
506{
507 return use_bdrv_whitelist;
508}
509
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800510typedef struct CreateCo {
511 BlockDriver *drv;
512 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800513 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800514 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200515 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800516} CreateCo;
517
518static void coroutine_fn bdrv_create_co_entry(void *opaque)
519{
Max Reitzcc84d902013-09-06 17:14:26 +0200520 Error *local_err = NULL;
521 int ret;
522
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800523 CreateCo *cco = opaque;
524 assert(cco->drv);
525
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200526 ret = cco->drv->bdrv_co_create_opts(cco->drv,
527 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300528 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200529 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800530}
531
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200532int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800533 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000534{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800535 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200536
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500537 GLOBAL_STATE_CODE();
538
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800539 Coroutine *co;
540 CreateCo cco = {
541 .drv = drv,
542 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800543 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800544 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200545 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800546 };
547
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100548 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200549 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300550 ret = -ENOTSUP;
551 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800552 }
553
554 if (qemu_in_coroutine()) {
555 /* Fast-path if already in coroutine context */
556 bdrv_create_co_entry(&cco);
557 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200558 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
559 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800560 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200561 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800562 }
563 }
564
565 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200566 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100567 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200568 error_propagate(errp, cco.err);
569 } else {
570 error_setg_errno(errp, -ret, "Could not create image");
571 }
572 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800573
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300574out:
575 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800576 return ret;
bellardea2384d2004-08-01 21:59:26 +0000577}
578
Max Reitzfd171462020-01-22 17:45:29 +0100579/**
580 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
581 * least the given @minimum_size.
582 *
583 * On success, return @blk's actual length.
584 * Otherwise, return -errno.
585 */
586static int64_t create_file_fallback_truncate(BlockBackend *blk,
587 int64_t minimum_size, Error **errp)
588{
589 Error *local_err = NULL;
590 int64_t size;
591 int ret;
592
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200593 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
594 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100595 if (ret < 0 && ret != -ENOTSUP) {
596 error_propagate(errp, local_err);
597 return ret;
598 }
599
600 size = blk_getlength(blk);
601 if (size < 0) {
602 error_free(local_err);
603 error_setg_errno(errp, -size,
604 "Failed to inquire the new image file's length");
605 return size;
606 }
607
608 if (size < minimum_size) {
609 /* Need to grow the image, but we failed to do that */
610 error_propagate(errp, local_err);
611 return -ENOTSUP;
612 }
613
614 error_free(local_err);
615 local_err = NULL;
616
617 return size;
618}
619
620/**
621 * Helper function for bdrv_create_file_fallback(): Zero the first
622 * sector to remove any potentially pre-existing image header.
623 */
624static int create_file_fallback_zero_first_sector(BlockBackend *blk,
625 int64_t current_size,
626 Error **errp)
627{
628 int64_t bytes_to_clear;
629 int ret;
630
631 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
632 if (bytes_to_clear) {
633 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
634 if (ret < 0) {
635 error_setg_errno(errp, -ret,
636 "Failed to clear the new image's first sector");
637 return ret;
638 }
639 }
640
641 return 0;
642}
643
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200644/**
645 * Simple implementation of bdrv_co_create_opts for protocol drivers
646 * which only support creation via opening a file
647 * (usually existing raw storage device)
648 */
649int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
650 const char *filename,
651 QemuOpts *opts,
652 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100653{
654 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100655 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100656 int64_t size = 0;
657 char *buf = NULL;
658 PreallocMode prealloc;
659 Error *local_err = NULL;
660 int ret;
661
662 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
663 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
664 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
665 PREALLOC_MODE_OFF, &local_err);
666 g_free(buf);
667 if (local_err) {
668 error_propagate(errp, local_err);
669 return -EINVAL;
670 }
671
672 if (prealloc != PREALLOC_MODE_OFF) {
673 error_setg(errp, "Unsupported preallocation mode '%s'",
674 PreallocMode_str(prealloc));
675 return -ENOTSUP;
676 }
677
Max Reitzeeea1fa2020-02-25 16:56:18 +0100678 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100679 qdict_put_str(options, "driver", drv->format_name);
680
681 blk = blk_new_open(filename, NULL, options,
682 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
683 if (!blk) {
684 error_prepend(errp, "Protocol driver '%s' does not support image "
685 "creation, and opening the image failed: ",
686 drv->format_name);
687 return -EINVAL;
688 }
689
690 size = create_file_fallback_truncate(blk, size, errp);
691 if (size < 0) {
692 ret = size;
693 goto out;
694 }
695
696 ret = create_file_fallback_zero_first_sector(blk, size, errp);
697 if (ret < 0) {
698 goto out;
699 }
700
701 ret = 0;
702out:
703 blk_unref(blk);
704 return ret;
705}
706
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800707int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200708{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100709 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200710 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100711 QDict *qdict;
712 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200713
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500714 GLOBAL_STATE_CODE();
715
Max Reitzb65a5e12015-02-05 13:58:12 -0500716 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200717 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000718 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200719 }
720
Stefano Garzarella729222a2021-03-08 17:12:32 +0100721 if (!drv->create_opts) {
722 error_setg(errp, "Driver '%s' does not support image creation",
723 drv->format_name);
724 return -ENOTSUP;
725 }
726
727 /*
728 * 'opts' contains a QemuOptsList with a combination of format and protocol
729 * default values.
730 *
731 * The format properly removes its options, but the default values remain
732 * in 'opts->list'. So if the protocol has options with the same name
733 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
734 * of the format, since for overlapping options, the format wins.
735 *
736 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
737 * only the set options, and then convert it back to QemuOpts, using the
738 * create_opts of the protocol. So the new QemuOpts, will contain only the
739 * protocol defaults.
740 */
741 qdict = qemu_opts_to_qdict(opts, NULL);
742 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
743 if (protocol_opts == NULL) {
744 ret = -EINVAL;
745 goto out;
746 }
747
748 ret = bdrv_create(drv, filename, protocol_opts, errp);
749out:
750 qemu_opts_del(protocol_opts);
751 qobject_unref(qdict);
752 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200753}
754
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300755int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
756{
757 Error *local_err = NULL;
758 int ret;
759
760 assert(bs != NULL);
761
762 if (!bs->drv) {
763 error_setg(errp, "Block node '%s' is not opened", bs->filename);
764 return -ENOMEDIUM;
765 }
766
767 if (!bs->drv->bdrv_co_delete_file) {
768 error_setg(errp, "Driver '%s' does not support image deletion",
769 bs->drv->format_name);
770 return -ENOTSUP;
771 }
772
773 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
774 if (ret < 0) {
775 error_propagate(errp, local_err);
776 }
777
778 return ret;
779}
780
Maxim Levitskya890f082020-12-17 19:09:03 +0200781void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
782{
783 Error *local_err = NULL;
784 int ret;
785
786 if (!bs) {
787 return;
788 }
789
790 ret = bdrv_co_delete_file(bs, &local_err);
791 /*
792 * ENOTSUP will happen if the block driver doesn't support
793 * the 'bdrv_co_delete_file' interface. This is a predictable
794 * scenario and shouldn't be reported back to the user.
795 */
796 if (ret == -ENOTSUP) {
797 error_free(local_err);
798 } else if (ret < 0) {
799 error_report_err(local_err);
800 }
801}
802
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100803/**
804 * Try to get @bs's logical and physical block size.
805 * On success, store them in @bsz struct and return 0.
806 * On failure return -errno.
807 * @bs must not be empty.
808 */
809int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
810{
811 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200812 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500813 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100814
815 if (drv && drv->bdrv_probe_blocksizes) {
816 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200817 } else if (filtered) {
818 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100819 }
820
821 return -ENOTSUP;
822}
823
824/**
825 * Try to get @bs's geometry (cyls, heads, sectors).
826 * On success, store them in @geo struct and return 0.
827 * On failure return -errno.
828 * @bs must not be empty.
829 */
830int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
831{
832 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200833 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500834 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100835
836 if (drv && drv->bdrv_probe_geometry) {
837 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200838 } else if (filtered) {
839 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100840 }
841
842 return -ENOTSUP;
843}
844
Jim Meyeringeba25052012-05-28 09:27:54 +0200845/*
846 * Create a uniquely-named empty temporary file.
847 * Return 0 upon success, otherwise a negative errno value.
848 */
849int get_tmp_filename(char *filename, int size)
850{
bellardd5249392004-08-03 21:14:23 +0000851#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000852 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200853 /* GetTempFileName requires that its output buffer (4th param)
854 have length MAX_PATH or greater. */
855 assert(size >= MAX_PATH);
856 return (GetTempPath(MAX_PATH, temp_dir)
857 && GetTempFileName(temp_dir, "qem", 0, filename)
858 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000859#else
bellardea2384d2004-08-01 21:59:26 +0000860 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000861 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000862 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530863 if (!tmpdir) {
864 tmpdir = "/var/tmp";
865 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200866 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
867 return -EOVERFLOW;
868 }
bellardea2384d2004-08-01 21:59:26 +0000869 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800870 if (fd < 0) {
871 return -errno;
872 }
873 if (close(fd) != 0) {
874 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200875 return -errno;
876 }
877 return 0;
bellardd5249392004-08-03 21:14:23 +0000878#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200879}
bellardea2384d2004-08-01 21:59:26 +0000880
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200881/*
882 * Detect host devices. By convention, /dev/cdrom[N] is always
883 * recognized as a host CDROM.
884 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200885static BlockDriver *find_hdev_driver(const char *filename)
886{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200887 int score_max = 0, score;
888 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200889
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100890 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200891 if (d->bdrv_probe_device) {
892 score = d->bdrv_probe_device(filename);
893 if (score > score_max) {
894 score_max = score;
895 drv = d;
896 }
897 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200898 }
899
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200900 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200901}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200902
Marc Mari88d88792016-08-12 09:27:03 -0400903static BlockDriver *bdrv_do_find_protocol(const char *protocol)
904{
905 BlockDriver *drv1;
906
907 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
908 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
909 return drv1;
910 }
911 }
912
913 return NULL;
914}
915
Kevin Wolf98289622013-07-10 15:47:39 +0200916BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500917 bool allow_protocol_prefix,
918 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200919{
920 BlockDriver *drv1;
921 char protocol[128];
922 int len;
923 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400924 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200925
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500926 GLOBAL_STATE_CODE();
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200927 /* TODO Drivers without bdrv_file_open must be specified explicitly */
928
Christoph Hellwig39508e72010-06-23 12:25:17 +0200929 /*
930 * XXX(hch): we really should not let host device detection
931 * override an explicit protocol specification, but moving this
932 * later breaks access to device names with colons in them.
933 * Thanks to the brain-dead persistent naming schemes on udev-
934 * based Linux systems those actually are quite common.
935 */
936 drv1 = find_hdev_driver(filename);
937 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200938 return drv1;
939 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200940
Kevin Wolf98289622013-07-10 15:47:39 +0200941 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100942 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200943 }
Kevin Wolf98289622013-07-10 15:47:39 +0200944
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000945 p = strchr(filename, ':');
946 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200947 len = p - filename;
948 if (len > sizeof(protocol) - 1)
949 len = sizeof(protocol) - 1;
950 memcpy(protocol, filename, len);
951 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400952
953 drv1 = bdrv_do_find_protocol(protocol);
954 if (drv1) {
955 return drv1;
956 }
957
958 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
959 if (block_driver_modules[i].protocol_name &&
960 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
961 block_module_load_one(block_driver_modules[i].library_name);
962 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200963 }
964 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500965
Marc Mari88d88792016-08-12 09:27:03 -0400966 drv1 = bdrv_do_find_protocol(protocol);
967 if (!drv1) {
968 error_setg(errp, "Unknown protocol '%s'", protocol);
969 }
970 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200971}
972
Markus Armbrusterc6684242014-11-20 16:27:10 +0100973/*
974 * Guess image format by probing its contents.
975 * This is not a good idea when your image is raw (CVE-2008-2004), but
976 * we do it anyway for backward compatibility.
977 *
978 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100979 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
980 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100981 * @filename is its filename.
982 *
983 * For all block drivers, call the bdrv_probe() method to get its
984 * probing score.
985 * Return the first block driver with the highest probing score.
986 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100987BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
988 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100989{
990 int score_max = 0, score;
991 BlockDriver *drv = NULL, *d;
992
993 QLIST_FOREACH(d, &bdrv_drivers, list) {
994 if (d->bdrv_probe) {
995 score = d->bdrv_probe(buf, buf_size, filename);
996 if (score > score_max) {
997 score_max = score;
998 drv = d;
999 }
1000 }
1001 }
1002
1003 return drv;
1004}
1005
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001006static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +02001007 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +00001008{
Markus Armbrusterc6684242014-11-20 16:27:10 +01001009 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +01001010 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +01001011 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001012
Kevin Wolf08a00552010-06-01 18:37:31 +02001013 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001014 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +01001015 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +02001016 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -07001017 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001018
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001019 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +00001020 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001021 error_setg_errno(errp, -ret, "Could not read image for determining its "
1022 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +02001023 *pdrv = NULL;
1024 return ret;
bellard83f64092006-08-01 16:21:11 +00001025 }
1026
Markus Armbrusterc6684242014-11-20 16:27:10 +01001027 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +02001028 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001029 error_setg(errp, "Could not determine image format: No compatible "
1030 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +02001031 ret = -ENOENT;
1032 }
1033 *pdrv = drv;
1034 return ret;
bellardea2384d2004-08-01 21:59:26 +00001035}
1036
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001037/**
1038 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001039 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001040 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001041int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001042{
1043 BlockDriver *drv = bs->drv;
1044
Max Reitzd470ad42017-11-10 21:31:09 +01001045 if (!drv) {
1046 return -ENOMEDIUM;
1047 }
1048
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001049 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001050 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001051 return 0;
1052
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001053 /* query actual device if possible, otherwise just trust the hint */
1054 if (drv->bdrv_getlength) {
1055 int64_t length = drv->bdrv_getlength(bs);
1056 if (length < 0) {
1057 return length;
1058 }
Fam Zheng7e382002013-11-06 19:48:06 +08001059 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001060 }
1061
1062 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001063
1064 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1065 return -EFBIG;
1066 }
1067
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001068 return 0;
1069}
1070
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001071/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001072 * Combines a QDict of new block driver @options with any missing options taken
1073 * from @old_options, so that leaving out an option defaults to its old value.
1074 */
1075static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1076 QDict *old_options)
1077{
1078 if (bs->drv && bs->drv->bdrv_join_options) {
1079 bs->drv->bdrv_join_options(options, old_options);
1080 } else {
1081 qdict_join(options, old_options, false);
1082 }
1083}
1084
Alberto Garcia543770b2018-09-06 12:37:09 +03001085static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1086 int open_flags,
1087 Error **errp)
1088{
1089 Error *local_err = NULL;
1090 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1091 BlockdevDetectZeroesOptions detect_zeroes =
1092 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1093 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1094 g_free(value);
1095 if (local_err) {
1096 error_propagate(errp, local_err);
1097 return detect_zeroes;
1098 }
1099
1100 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1101 !(open_flags & BDRV_O_UNMAP))
1102 {
1103 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1104 "without setting discard operation to unmap");
1105 }
1106
1107 return detect_zeroes;
1108}
1109
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001110/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001111 * Set open flags for aio engine
1112 *
1113 * Return 0 on success, -1 if the engine specified is invalid
1114 */
1115int bdrv_parse_aio(const char *mode, int *flags)
1116{
1117 if (!strcmp(mode, "threads")) {
1118 /* do nothing, default */
1119 } else if (!strcmp(mode, "native")) {
1120 *flags |= BDRV_O_NATIVE_AIO;
1121#ifdef CONFIG_LINUX_IO_URING
1122 } else if (!strcmp(mode, "io_uring")) {
1123 *flags |= BDRV_O_IO_URING;
1124#endif
1125 } else {
1126 return -1;
1127 }
1128
1129 return 0;
1130}
1131
1132/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001133 * Set open flags for a given discard mode
1134 *
1135 * Return 0 on success, -1 if the discard mode was invalid.
1136 */
1137int bdrv_parse_discard_flags(const char *mode, int *flags)
1138{
1139 *flags &= ~BDRV_O_UNMAP;
1140
1141 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1142 /* do nothing */
1143 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1144 *flags |= BDRV_O_UNMAP;
1145 } else {
1146 return -1;
1147 }
1148
1149 return 0;
1150}
1151
1152/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001153 * Set open flags for a given cache mode
1154 *
1155 * Return 0 on success, -1 if the cache mode was invalid.
1156 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001157int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001158{
1159 *flags &= ~BDRV_O_CACHE_MASK;
1160
1161 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001162 *writethrough = false;
1163 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001164 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001165 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001166 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001167 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001168 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001169 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001170 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001171 *flags |= BDRV_O_NO_FLUSH;
1172 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001173 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001174 } else {
1175 return -1;
1176 }
1177
1178 return 0;
1179}
1180
Kevin Wolfb5411552017-01-17 15:56:16 +01001181static char *bdrv_child_get_parent_desc(BdrvChild *c)
1182{
1183 BlockDriverState *parent = c->opaque;
Vladimir Sementsov-Ogievskiy2c0a3ac2021-06-01 10:52:15 +03001184 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
Kevin Wolfb5411552017-01-17 15:56:16 +01001185}
1186
Kevin Wolf20018e12016-05-23 18:46:59 +02001187static void bdrv_child_cb_drained_begin(BdrvChild *child)
1188{
1189 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001190 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001191}
1192
Kevin Wolf89bd0302018-03-22 14:11:20 +01001193static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1194{
1195 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001196 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001197}
1198
Max Reitze037c092019-07-19 11:26:14 +02001199static void bdrv_child_cb_drained_end(BdrvChild *child,
1200 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001201{
1202 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001203 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001204}
1205
Kevin Wolf38701b62017-05-04 18:52:39 +02001206static int bdrv_child_cb_inactivate(BdrvChild *child)
1207{
1208 BlockDriverState *bs = child->opaque;
1209 assert(bs->open_flags & BDRV_O_INACTIVE);
1210 return 0;
1211}
1212
Kevin Wolf5d231842019-05-06 19:17:56 +02001213static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1214 GSList **ignore, Error **errp)
1215{
1216 BlockDriverState *bs = child->opaque;
1217 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1218}
1219
Kevin Wolf53a7d042019-05-06 19:17:59 +02001220static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1221 GSList **ignore)
1222{
1223 BlockDriverState *bs = child->opaque;
1224 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1225}
1226
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001227/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001228 * Returns the options and flags that a temporary snapshot should get, based on
1229 * the originally requested flags (the originally requested image will have
1230 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001231 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001232static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1233 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001234{
Kevin Wolf73176be2016-03-07 13:02:15 +01001235 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1236
1237 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001238 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1239 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001240
Kevin Wolf3f486862019-04-04 17:04:43 +02001241 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001242 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001243 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001244
Kevin Wolf41869042016-06-16 12:59:30 +02001245 /* aio=native doesn't work for cache.direct=off, so disable it for the
1246 * temporary snapshot */
1247 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001248}
1249
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001250static void bdrv_backing_attach(BdrvChild *c)
1251{
1252 BlockDriverState *parent = c->opaque;
1253 BlockDriverState *backing_hd = c->bs;
1254
1255 assert(!parent->backing_blocker);
1256 error_setg(&parent->backing_blocker,
1257 "node is used as backing hd of '%s'",
1258 bdrv_get_device_or_node_name(parent));
1259
Max Reitzf30c66b2019-02-01 20:29:05 +01001260 bdrv_refresh_filename(backing_hd);
1261
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001262 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001263
1264 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1265 /* Otherwise we won't be able to commit or stream */
1266 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1267 parent->backing_blocker);
1268 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1269 parent->backing_blocker);
1270 /*
1271 * We do backup in 3 ways:
1272 * 1. drive backup
1273 * The target bs is new opened, and the source is top BDS
1274 * 2. blockdev backup
1275 * Both the source and the target are top BDSes.
1276 * 3. internal backup(used for block replication)
1277 * Both the source and the target are backing file
1278 *
1279 * In case 1 and 2, neither the source nor the target is the backing file.
1280 * In case 3, we will block the top BDS, so there is only one block job
1281 * for the top BDS and its backing chain.
1282 */
1283 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1284 parent->backing_blocker);
1285 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1286 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001287}
Kevin Wolfd736f112017-12-18 16:05:48 +01001288
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001289static void bdrv_backing_detach(BdrvChild *c)
1290{
1291 BlockDriverState *parent = c->opaque;
1292
1293 assert(parent->backing_blocker);
1294 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1295 error_free(parent->backing_blocker);
1296 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001297}
Kevin Wolfd736f112017-12-18 16:05:48 +01001298
Kevin Wolf6858eba2017-06-29 19:32:21 +02001299static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1300 const char *filename, Error **errp)
1301{
1302 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001303 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001304 int ret;
1305
Alberto Garciae94d3db2018-11-12 16:00:34 +02001306 if (read_only) {
1307 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001308 if (ret < 0) {
1309 return ret;
1310 }
1311 }
1312
Kevin Wolf6858eba2017-06-29 19:32:21 +02001313 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001314 base->drv ? base->drv->format_name : "",
1315 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001316 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001317 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001318 }
1319
Alberto Garciae94d3db2018-11-12 16:00:34 +02001320 if (read_only) {
1321 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001322 }
1323
Kevin Wolf6858eba2017-06-29 19:32:21 +02001324 return ret;
1325}
1326
Max Reitzfae8bd32020-05-13 13:05:20 +02001327/*
1328 * Returns the options and flags that a generic child of a BDS should
1329 * get, based on the given options and flags for the parent BDS.
1330 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001331static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1332 int *child_flags, QDict *child_options,
1333 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001334{
1335 int flags = parent_flags;
1336
1337 /*
1338 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1339 * Generally, the question to answer is: Should this child be
1340 * format-probed by default?
1341 */
1342
1343 /*
1344 * Pure and non-filtered data children of non-format nodes should
1345 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1346 * set). This only affects a very limited set of drivers (namely
1347 * quorum and blkverify when this comment was written).
1348 * Force-clear BDRV_O_PROTOCOL then.
1349 */
1350 if (!parent_is_format &&
1351 (role & BDRV_CHILD_DATA) &&
1352 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1353 {
1354 flags &= ~BDRV_O_PROTOCOL;
1355 }
1356
1357 /*
1358 * All children of format nodes (except for COW children) and all
1359 * metadata children in general should never be format-probed.
1360 * Force-set BDRV_O_PROTOCOL then.
1361 */
1362 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1363 (role & BDRV_CHILD_METADATA))
1364 {
1365 flags |= BDRV_O_PROTOCOL;
1366 }
1367
1368 /*
1369 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1370 * the parent.
1371 */
1372 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1373 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1374 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1375
1376 if (role & BDRV_CHILD_COW) {
1377 /* backing files are opened read-only by default */
1378 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1379 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1380 } else {
1381 /* Inherit the read-only option from the parent if it's not set */
1382 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1383 qdict_copy_default(child_options, parent_options,
1384 BDRV_OPT_AUTO_READ_ONLY);
1385 }
1386
1387 /*
1388 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1389 * can default to enable it on lower layers regardless of the
1390 * parent option.
1391 */
1392 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1393
1394 /* Clear flags that only apply to the top layer */
1395 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1396
1397 if (role & BDRV_CHILD_METADATA) {
1398 flags &= ~BDRV_O_NO_IO;
1399 }
1400 if (role & BDRV_CHILD_COW) {
1401 flags &= ~BDRV_O_TEMPORARY;
1402 }
1403
1404 *child_flags = flags;
1405}
1406
Max Reitzca2f1232020-05-13 13:05:22 +02001407static void bdrv_child_cb_attach(BdrvChild *child)
1408{
1409 BlockDriverState *bs = child->opaque;
1410
Hanna Reitza2253692021-11-15 15:53:58 +01001411 QLIST_INSERT_HEAD(&bs->children, child, next);
1412
Max Reitzca2f1232020-05-13 13:05:22 +02001413 if (child->role & BDRV_CHILD_COW) {
1414 bdrv_backing_attach(child);
1415 }
1416
1417 bdrv_apply_subtree_drain(child, bs);
1418}
1419
Max Reitz48e08282020-05-13 13:05:23 +02001420static void bdrv_child_cb_detach(BdrvChild *child)
1421{
1422 BlockDriverState *bs = child->opaque;
1423
1424 if (child->role & BDRV_CHILD_COW) {
1425 bdrv_backing_detach(child);
1426 }
1427
1428 bdrv_unapply_subtree_drain(child, bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001429
1430 QLIST_REMOVE(child, next);
Max Reitz48e08282020-05-13 13:05:23 +02001431}
1432
Max Reitz43483552020-05-13 13:05:24 +02001433static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1434 const char *filename, Error **errp)
1435{
1436 if (c->role & BDRV_CHILD_COW) {
1437 return bdrv_backing_update_filename(c, base, filename, errp);
1438 }
1439 return 0;
1440}
1441
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001442AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001443{
1444 BlockDriverState *bs = c->opaque;
1445
1446 return bdrv_get_aio_context(bs);
1447}
1448
Max Reitz43483552020-05-13 13:05:24 +02001449const BdrvChildClass child_of_bds = {
1450 .parent_is_bds = true,
1451 .get_parent_desc = bdrv_child_get_parent_desc,
1452 .inherit_options = bdrv_inherited_options,
1453 .drained_begin = bdrv_child_cb_drained_begin,
1454 .drained_poll = bdrv_child_cb_drained_poll,
1455 .drained_end = bdrv_child_cb_drained_end,
1456 .attach = bdrv_child_cb_attach,
1457 .detach = bdrv_child_cb_detach,
1458 .inactivate = bdrv_child_cb_inactivate,
1459 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1460 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1461 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001462 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001463};
1464
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001465AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1466{
1467 return c->klass->get_parent_aio_context(c);
1468}
1469
Kevin Wolf7b272452012-11-12 17:05:39 +01001470static int bdrv_open_flags(BlockDriverState *bs, int flags)
1471{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001472 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001473
1474 /*
1475 * Clear flags that are internal to the block layer before opening the
1476 * image.
1477 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001478 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001479
Kevin Wolf7b272452012-11-12 17:05:39 +01001480 return open_flags;
1481}
1482
Kevin Wolf91a097e2015-05-08 17:49:53 +02001483static void update_flags_from_options(int *flags, QemuOpts *opts)
1484{
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001485 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001486
Alberto Garcia57f9db92018-09-06 12:37:06 +03001487 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001488 *flags |= BDRV_O_NO_FLUSH;
1489 }
1490
Alberto Garcia57f9db92018-09-06 12:37:06 +03001491 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001492 *flags |= BDRV_O_NOCACHE;
1493 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001494
Alberto Garcia57f9db92018-09-06 12:37:06 +03001495 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001496 *flags |= BDRV_O_RDWR;
1497 }
1498
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001499 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1500 *flags |= BDRV_O_AUTO_RDONLY;
1501 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001502}
1503
1504static void update_options_from_flags(QDict *options, int flags)
1505{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001506 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001507 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001508 }
1509 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001510 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1511 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001512 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001513 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001514 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001515 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001516 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1517 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1518 flags & BDRV_O_AUTO_RDONLY);
1519 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001520}
1521
Kevin Wolf636ea372014-01-24 14:11:52 +01001522static void bdrv_assign_node_name(BlockDriverState *bs,
1523 const char *node_name,
1524 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001525{
Jeff Cody15489c72015-10-12 19:36:50 -04001526 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001527
Jeff Cody15489c72015-10-12 19:36:50 -04001528 if (!node_name) {
1529 node_name = gen_node_name = id_generate(ID_BLOCK);
1530 } else if (!id_wellformed(node_name)) {
1531 /*
1532 * Check for empty string or invalid characters, but not if it is
1533 * generated (generated names use characters not available to the user)
1534 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001535 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001536 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001537 }
1538
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001539 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001540 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001541 error_setg(errp, "node-name=%s is conflicting with a device id",
1542 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001543 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001544 }
1545
Benoît Canet6913c0c2014-01-23 21:31:33 +01001546 /* takes care of avoiding duplicates node names */
1547 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001548 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001549 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001550 }
1551
Kevin Wolf824808d2018-07-04 13:28:29 +02001552 /* Make sure that the node name isn't truncated */
1553 if (strlen(node_name) >= sizeof(bs->node_name)) {
1554 error_setg(errp, "Node name too long");
1555 goto out;
1556 }
1557
Benoît Canet6913c0c2014-01-23 21:31:33 +01001558 /* copy node name into the bs and insert it into the graph list */
1559 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1560 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001561out:
1562 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001563}
1564
Kevin Wolf01a56502017-01-18 15:51:56 +01001565static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1566 const char *node_name, QDict *options,
1567 int open_flags, Error **errp)
1568{
1569 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001570 int i, ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001571
1572 bdrv_assign_node_name(bs, node_name, &local_err);
1573 if (local_err) {
1574 error_propagate(errp, local_err);
1575 return -EINVAL;
1576 }
1577
1578 bs->drv = drv;
1579 bs->opaque = g_malloc0(drv->instance_size);
1580
1581 if (drv->bdrv_file_open) {
1582 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1583 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001584 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001585 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001586 } else {
1587 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001588 }
1589
1590 if (ret < 0) {
1591 if (local_err) {
1592 error_propagate(errp, local_err);
1593 } else if (bs->filename[0]) {
1594 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1595 } else {
1596 error_setg_errno(errp, -ret, "Could not open image");
1597 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001598 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001599 }
1600
1601 ret = refresh_total_sectors(bs, bs->total_sectors);
1602 if (ret < 0) {
1603 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001604 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001605 }
1606
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001607 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001608 if (local_err) {
1609 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001610 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001611 }
1612
1613 assert(bdrv_opt_mem_align(bs) != 0);
1614 assert(bdrv_min_mem_align(bs) != 0);
1615 assert(is_power_of_2(bs->bl.request_alignment));
1616
Kevin Wolf0f122642018-03-28 18:29:18 +02001617 for (i = 0; i < bs->quiesce_counter; i++) {
1618 if (drv->bdrv_co_drain_begin) {
1619 drv->bdrv_co_drain_begin(bs);
1620 }
1621 }
1622
Kevin Wolf01a56502017-01-18 15:51:56 +01001623 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001624open_failed:
1625 bs->drv = NULL;
1626 if (bs->file != NULL) {
1627 bdrv_unref_child(bs, bs->file);
1628 bs->file = NULL;
1629 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001630 g_free(bs->opaque);
1631 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001632 return ret;
1633}
1634
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001635/*
1636 * Create and open a block node.
1637 *
1638 * @options is a QDict of options to pass to the block drivers, or NULL for an
1639 * empty set of options. The reference to the QDict belongs to the block layer
1640 * after the call (even on failure), so if the caller intends to reuse the
1641 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1642 */
1643BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1644 const char *node_name,
1645 QDict *options, int flags,
1646 Error **errp)
Kevin Wolf680c7f92017-01-18 17:16:41 +01001647{
1648 BlockDriverState *bs;
1649 int ret;
1650
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001651 GLOBAL_STATE_CODE();
1652
Kevin Wolf680c7f92017-01-18 17:16:41 +01001653 bs = bdrv_new();
1654 bs->open_flags = flags;
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001655 bs->options = options ?: qdict_new();
1656 bs->explicit_options = qdict_clone_shallow(bs->options);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001657 bs->opaque = NULL;
1658
1659 update_options_from_flags(bs->options, flags);
1660
1661 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1662 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001663 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001664 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001665 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001666 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001667 bdrv_unref(bs);
1668 return NULL;
1669 }
1670
1671 return bs;
1672}
1673
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001674/* Create and open a block node. */
1675BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1676 int flags, Error **errp)
1677{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001678 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001679 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1680}
1681
Kevin Wolfc5f30142016-10-06 11:33:17 +02001682QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001683 .name = "bdrv_common",
1684 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1685 .desc = {
1686 {
1687 .name = "node-name",
1688 .type = QEMU_OPT_STRING,
1689 .help = "Node name of the block device node",
1690 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001691 {
1692 .name = "driver",
1693 .type = QEMU_OPT_STRING,
1694 .help = "Block driver to use for the node",
1695 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001696 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001697 .name = BDRV_OPT_CACHE_DIRECT,
1698 .type = QEMU_OPT_BOOL,
1699 .help = "Bypass software writeback cache on the host",
1700 },
1701 {
1702 .name = BDRV_OPT_CACHE_NO_FLUSH,
1703 .type = QEMU_OPT_BOOL,
1704 .help = "Ignore flush requests",
1705 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001706 {
1707 .name = BDRV_OPT_READ_ONLY,
1708 .type = QEMU_OPT_BOOL,
1709 .help = "Node is opened in read-only mode",
1710 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001711 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001712 .name = BDRV_OPT_AUTO_READ_ONLY,
1713 .type = QEMU_OPT_BOOL,
1714 .help = "Node can become read-only if opening read-write fails",
1715 },
1716 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001717 .name = "detect-zeroes",
1718 .type = QEMU_OPT_STRING,
1719 .help = "try to optimize zero writes (off, on, unmap)",
1720 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001721 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001722 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001723 .type = QEMU_OPT_STRING,
1724 .help = "discard operation (ignore/off, unmap/on)",
1725 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001726 {
1727 .name = BDRV_OPT_FORCE_SHARE,
1728 .type = QEMU_OPT_BOOL,
1729 .help = "always accept other writers (default: off)",
1730 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001731 { /* end of list */ }
1732 },
1733};
1734
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001735QemuOptsList bdrv_create_opts_simple = {
1736 .name = "simple-create-opts",
1737 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001738 .desc = {
1739 {
1740 .name = BLOCK_OPT_SIZE,
1741 .type = QEMU_OPT_SIZE,
1742 .help = "Virtual disk size"
1743 },
1744 {
1745 .name = BLOCK_OPT_PREALLOC,
1746 .type = QEMU_OPT_STRING,
1747 .help = "Preallocation mode (allowed values: off)"
1748 },
1749 { /* end of list */ }
1750 }
1751};
1752
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001753/*
Kevin Wolf57915332010-04-14 15:24:50 +02001754 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001755 *
1756 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001757 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001758static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001759 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001760{
1761 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001762 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001763 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001764 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001765 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001766 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001767 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001768 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001769 bool ro;
Kevin Wolf57915332010-04-14 15:24:50 +02001770
Paolo Bonzini64058752012-05-08 16:51:49 +02001771 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001772 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001773
Kevin Wolf62392eb2015-04-24 16:38:02 +02001774 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001775 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001776 ret = -EINVAL;
1777 goto fail_opts;
1778 }
1779
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001780 update_flags_from_options(&bs->open_flags, opts);
1781
Kevin Wolf62392eb2015-04-24 16:38:02 +02001782 driver_name = qemu_opt_get(opts, "driver");
1783 drv = bdrv_find_format(driver_name);
1784 assert(drv != NULL);
1785
Fam Zheng5a9347c2017-05-03 00:35:37 +08001786 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1787
1788 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1789 error_setg(errp,
1790 BDRV_OPT_FORCE_SHARE
1791 "=on can only be used with read-only images");
1792 ret = -EINVAL;
1793 goto fail_opts;
1794 }
1795
Kevin Wolf45673672013-04-22 17:48:40 +02001796 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001797 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001798 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001799 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001800 /*
1801 * Caution: while qdict_get_try_str() is fine, getting
1802 * non-string types would require more care. When @options
1803 * come from -blockdev or blockdev_add, its members are typed
1804 * according to the QAPI schema, but when they come from
1805 * -drive, they're all QString.
1806 */
Kevin Wolf45673672013-04-22 17:48:40 +02001807 filename = qdict_get_try_str(options, "filename");
1808 }
1809
Max Reitz4a008242017-04-13 18:06:24 +02001810 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001811 error_setg(errp, "The '%s' block driver requires a file name",
1812 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001813 ret = -EINVAL;
1814 goto fail_opts;
1815 }
1816
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001817 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1818 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001819
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001820 ro = bdrv_is_read_only(bs);
1821
1822 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1823 if (!ro && bdrv_is_whitelisted(drv, true)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001824 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1825 } else {
1826 ret = -ENOTSUP;
1827 }
1828 if (ret < 0) {
1829 error_setg(errp,
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001830 !ro && bdrv_is_whitelisted(drv, true)
Kevin Wolf8be25de2019-01-22 13:15:31 +01001831 ? "Driver '%s' can only be used for read-only devices"
1832 : "Driver '%s' is not whitelisted",
1833 drv->format_name);
1834 goto fail_opts;
1835 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001836 }
Kevin Wolf57915332010-04-14 15:24:50 +02001837
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001838 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001839 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001840
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001841 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001842 if (!ro) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001843 bdrv_enable_copy_on_read(bs);
1844 } else {
1845 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001846 ret = -EINVAL;
1847 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001848 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001849 }
1850
Alberto Garcia415bbca2018-10-03 13:23:13 +03001851 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001852 if (discard != NULL) {
1853 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1854 error_setg(errp, "Invalid discard option");
1855 ret = -EINVAL;
1856 goto fail_opts;
1857 }
1858 }
1859
Alberto Garcia543770b2018-09-06 12:37:09 +03001860 bs->detect_zeroes =
1861 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1862 if (local_err) {
1863 error_propagate(errp, local_err);
1864 ret = -EINVAL;
1865 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001866 }
1867
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001868 if (filename != NULL) {
1869 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1870 } else {
1871 bs->filename[0] = '\0';
1872 }
Max Reitz91af7012014-07-18 20:24:56 +02001873 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001874
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001875 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001876 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001877 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001878
Kevin Wolf01a56502017-01-18 15:51:56 +01001879 assert(!drv->bdrv_file_open || file == NULL);
1880 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001881 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001882 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001883 }
1884
Kevin Wolf18edf282015-04-07 17:12:56 +02001885 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001886 return 0;
1887
Kevin Wolf18edf282015-04-07 17:12:56 +02001888fail_opts:
1889 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001890 return ret;
1891}
1892
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001893static QDict *parse_json_filename(const char *filename, Error **errp)
1894{
1895 QObject *options_obj;
1896 QDict *options;
1897 int ret;
1898
1899 ret = strstart(filename, "json:", &filename);
1900 assert(ret);
1901
Markus Armbruster5577fff2017-02-28 22:26:59 +01001902 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001903 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001904 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001905 return NULL;
1906 }
1907
Max Reitz7dc847e2018-02-24 16:40:29 +01001908 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001909 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001910 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001911 error_setg(errp, "Invalid JSON object given");
1912 return NULL;
1913 }
1914
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001915 qdict_flatten(options);
1916
1917 return options;
1918}
1919
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001920static void parse_json_protocol(QDict *options, const char **pfilename,
1921 Error **errp)
1922{
1923 QDict *json_options;
1924 Error *local_err = NULL;
1925
1926 /* Parse json: pseudo-protocol */
1927 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1928 return;
1929 }
1930
1931 json_options = parse_json_filename(*pfilename, &local_err);
1932 if (local_err) {
1933 error_propagate(errp, local_err);
1934 return;
1935 }
1936
1937 /* Options given in the filename have lower priority than options
1938 * specified directly */
1939 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001940 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001941 *pfilename = NULL;
1942}
1943
Kevin Wolf57915332010-04-14 15:24:50 +02001944/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001945 * Fills in default options for opening images and converts the legacy
1946 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001947 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1948 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001949 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001950static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001951 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001952{
1953 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001954 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001955 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001956 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001957 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001958
Markus Armbruster129c7d12017-03-30 19:43:12 +02001959 /*
1960 * Caution: while qdict_get_try_str() is fine, getting non-string
1961 * types would require more care. When @options come from
1962 * -blockdev or blockdev_add, its members are typed according to
1963 * the QAPI schema, but when they come from -drive, they're all
1964 * QString.
1965 */
Max Reitz53a29512015-03-19 14:53:16 -04001966 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001967 if (drvname) {
1968 drv = bdrv_find_format(drvname);
1969 if (!drv) {
1970 error_setg(errp, "Unknown driver '%s'", drvname);
1971 return -ENOENT;
1972 }
1973 /* If the user has explicitly specified the driver, this choice should
1974 * override the BDRV_O_PROTOCOL flag */
1975 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001976 }
1977
1978 if (protocol) {
1979 *flags |= BDRV_O_PROTOCOL;
1980 } else {
1981 *flags &= ~BDRV_O_PROTOCOL;
1982 }
1983
Kevin Wolf91a097e2015-05-08 17:49:53 +02001984 /* Translate cache options from flags into options */
1985 update_options_from_flags(*options, *flags);
1986
Kevin Wolff54120f2014-05-26 11:09:59 +02001987 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001988 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001989 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001990 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001991 parse_filename = true;
1992 } else {
1993 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1994 "the same time");
1995 return -EINVAL;
1996 }
1997 }
1998
1999 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02002000 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02002001 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02002002
Max Reitz053e1572015-08-26 19:47:51 +02002003 if (!drvname && protocol) {
2004 if (filename) {
2005 drv = bdrv_find_protocol(filename, parse_filename, errp);
2006 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002007 return -EINVAL;
2008 }
Max Reitz053e1572015-08-26 19:47:51 +02002009
2010 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05002011 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02002012 } else {
2013 error_setg(errp, "Must specify either driver or file");
2014 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002015 }
2016 }
2017
Kevin Wolf17b005f2014-05-27 10:50:29 +02002018 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02002019
2020 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002021 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002022 drv->bdrv_parse_filename(filename, *options, &local_err);
2023 if (local_err) {
2024 error_propagate(errp, local_err);
2025 return -EINVAL;
2026 }
2027
2028 if (!drv->bdrv_needs_filename) {
2029 qdict_del(*options, "filename");
2030 }
2031 }
2032
2033 return 0;
2034}
2035
Kevin Wolf148eb132017-09-14 14:32:04 +02002036typedef struct BlockReopenQueueEntry {
2037 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01002038 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02002039 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002040 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02002041} BlockReopenQueueEntry;
2042
2043/*
2044 * Return the flags that @bs will have after the reopens in @q have
2045 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2046 * return the current flags.
2047 */
2048static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2049{
2050 BlockReopenQueueEntry *entry;
2051
2052 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002053 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002054 if (entry->state.bs == bs) {
2055 return entry->state.flags;
2056 }
2057 }
2058 }
2059
2060 return bs->open_flags;
2061}
2062
2063/* Returns whether the image file can be written to after the reopen queue @q
2064 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002065static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2066 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002067{
2068 int flags = bdrv_reopen_get_flags(q, bs);
2069
2070 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2071}
2072
Max Reitzcc022142018-06-06 21:37:00 +02002073/*
2074 * Return whether the BDS can be written to. This is not necessarily
2075 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2076 * be written to but do not count as read-only images.
2077 */
2078bool bdrv_is_writable(BlockDriverState *bs)
2079{
2080 return bdrv_is_writable_after_reopen(bs, NULL);
2081}
2082
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002083static char *bdrv_child_user_desc(BdrvChild *c)
2084{
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002085 return c->klass->get_parent_desc(c);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002086}
2087
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002088/*
2089 * Check that @a allows everything that @b needs. @a and @b must reference same
2090 * child node.
2091 */
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002092static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2093{
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002094 const char *child_bs_name;
2095 g_autofree char *a_user = NULL;
2096 g_autofree char *b_user = NULL;
2097 g_autofree char *perms = NULL;
2098
2099 assert(a->bs);
2100 assert(a->bs == b->bs);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002101
2102 if ((b->perm & a->shared_perm) == b->perm) {
2103 return true;
2104 }
2105
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002106 child_bs_name = bdrv_get_node_name(b->bs);
2107 a_user = bdrv_child_user_desc(a);
2108 b_user = bdrv_child_user_desc(b);
2109 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2110
2111 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2112 "both required by %s (uses node '%s' as '%s' child) and "
2113 "unshared by %s (uses node '%s' as '%s' child).",
2114 child_bs_name, perms,
2115 b_user, child_bs_name, b->name,
2116 a_user, child_bs_name, a->name);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002117
2118 return false;
2119}
2120
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002121static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002122{
2123 BdrvChild *a, *b;
2124
2125 /*
2126 * During the loop we'll look at each pair twice. That's correct because
2127 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2128 * directions.
2129 */
2130 QLIST_FOREACH(a, &bs->parents, next_parent) {
2131 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002132 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002133 continue;
2134 }
2135
2136 if (!bdrv_a_allow_b(a, b, errp)) {
2137 return true;
2138 }
2139 }
2140 }
2141
2142 return false;
2143}
2144
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002145static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002146 BdrvChild *c, BdrvChildRole role,
2147 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002148 uint64_t parent_perm, uint64_t parent_shared,
2149 uint64_t *nperm, uint64_t *nshared)
2150{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002151 assert(bs->drv && bs->drv->bdrv_child_perm);
Max Reitze5d8a402020-05-13 13:05:44 +02002152 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002153 parent_perm, parent_shared,
2154 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002155 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002156 if (child_bs && child_bs->force_share) {
2157 *nshared = BLK_PERM_ALL;
2158 }
2159}
2160
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002161/*
2162 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2163 * nodes that are already in the @list, of course) so that final list is
2164 * topologically sorted. Return the result (GSList @list object is updated, so
2165 * don't use old reference after function call).
2166 *
2167 * On function start @list must be already topologically sorted and for any node
2168 * in the @list the whole subtree of the node must be in the @list as well. The
2169 * simplest way to satisfy this criteria: use only result of
2170 * bdrv_topological_dfs() or NULL as @list parameter.
2171 */
2172static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2173 BlockDriverState *bs)
2174{
2175 BdrvChild *child;
2176 g_autoptr(GHashTable) local_found = NULL;
2177
2178 if (!found) {
2179 assert(!list);
2180 found = local_found = g_hash_table_new(NULL, NULL);
2181 }
2182
2183 if (g_hash_table_contains(found, bs)) {
2184 return list;
2185 }
2186 g_hash_table_add(found, bs);
2187
2188 QLIST_FOREACH(child, &bs->children, next) {
2189 list = bdrv_topological_dfs(list, found, child->bs);
2190 }
2191
2192 return g_slist_prepend(list, bs);
2193}
2194
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002195typedef struct BdrvChildSetPermState {
2196 BdrvChild *child;
2197 uint64_t old_perm;
2198 uint64_t old_shared_perm;
2199} BdrvChildSetPermState;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002200
2201static void bdrv_child_set_perm_abort(void *opaque)
2202{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002203 BdrvChildSetPermState *s = opaque;
2204
2205 s->child->perm = s->old_perm;
2206 s->child->shared_perm = s->old_shared_perm;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002207}
2208
2209static TransactionActionDrv bdrv_child_set_pem_drv = {
2210 .abort = bdrv_child_set_perm_abort,
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002211 .clean = g_free,
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002212};
2213
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002214static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2215 uint64_t shared, Transaction *tran)
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002216{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002217 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2218
2219 *s = (BdrvChildSetPermState) {
2220 .child = c,
2221 .old_perm = c->perm,
2222 .old_shared_perm = c->shared_perm,
2223 };
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002224
2225 c->perm = perm;
2226 c->shared_perm = shared;
2227
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002228 tran_add(tran, &bdrv_child_set_pem_drv, s);
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002229}
2230
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002231static void bdrv_drv_set_perm_commit(void *opaque)
2232{
2233 BlockDriverState *bs = opaque;
2234 uint64_t cumulative_perms, cumulative_shared_perms;
2235
2236 if (bs->drv->bdrv_set_perm) {
2237 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2238 &cumulative_shared_perms);
2239 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2240 }
2241}
2242
2243static void bdrv_drv_set_perm_abort(void *opaque)
2244{
2245 BlockDriverState *bs = opaque;
2246
2247 if (bs->drv->bdrv_abort_perm_update) {
2248 bs->drv->bdrv_abort_perm_update(bs);
2249 }
2250}
2251
2252TransactionActionDrv bdrv_drv_set_perm_drv = {
2253 .abort = bdrv_drv_set_perm_abort,
2254 .commit = bdrv_drv_set_perm_commit,
2255};
2256
2257static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2258 uint64_t shared_perm, Transaction *tran,
2259 Error **errp)
2260{
2261 if (!bs->drv) {
2262 return 0;
2263 }
2264
2265 if (bs->drv->bdrv_check_perm) {
2266 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2267 if (ret < 0) {
2268 return ret;
2269 }
2270 }
2271
2272 if (tran) {
2273 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2274 }
2275
2276 return 0;
2277}
2278
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002279typedef struct BdrvReplaceChildState {
2280 BdrvChild *child;
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002281 BdrvChild **childp;
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002282 BlockDriverState *old_bs;
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002283 bool free_empty_child;
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002284} BdrvReplaceChildState;
2285
2286static void bdrv_replace_child_commit(void *opaque)
2287{
2288 BdrvReplaceChildState *s = opaque;
2289
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002290 if (s->free_empty_child && !s->child->bs) {
2291 bdrv_child_free(s->child);
2292 }
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002293 bdrv_unref(s->old_bs);
2294}
2295
2296static void bdrv_replace_child_abort(void *opaque)
2297{
2298 BdrvReplaceChildState *s = opaque;
2299 BlockDriverState *new_bs = s->child->bs;
2300
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002301 /*
2302 * old_bs reference is transparently moved from @s to s->child.
2303 *
2304 * Pass &s->child here instead of s->childp, because:
2305 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2306 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2307 * will not modify s->child. From that perspective, it does not matter
2308 * whether we pass s->childp or &s->child.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002309 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2310 * it here.
2311 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2312 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2313 * must not pass a NULL *s->childp here.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002314 *
2315 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2316 * any case, there is no reason to pass it anyway.
2317 */
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002318 bdrv_replace_child_noperm(&s->child, s->old_bs, true);
2319 /*
2320 * The child was pre-existing, so s->old_bs must be non-NULL, and
2321 * s->child thus must not have been freed
2322 */
2323 assert(s->child != NULL);
2324 if (!new_bs) {
2325 /* As described above, *s->childp was cleared, so restore it */
2326 assert(s->childp != NULL);
2327 *s->childp = s->child;
2328 }
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002329 bdrv_unref(new_bs);
2330}
2331
2332static TransactionActionDrv bdrv_replace_child_drv = {
2333 .commit = bdrv_replace_child_commit,
2334 .abort = bdrv_replace_child_abort,
2335 .clean = g_free,
2336};
2337
2338/*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002339 * bdrv_replace_child_tran
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002340 *
2341 * Note: real unref of old_bs is done only on commit.
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002342 *
2343 * The function doesn't update permissions, caller is responsible for this.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002344 *
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002345 * (*childp)->bs must not be NULL.
2346 *
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002347 * Note that if new_bs == NULL, @childp is stored in a state object attached
2348 * to @tran, so that the old child can be reinstated in the abort handler.
2349 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2350 * transaction is committed or aborted.
2351 *
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002352 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2353 * freed (on commit). @free_empty_child should only be false if the
2354 * caller will free the BDrvChild themselves (which may be important
2355 * if this is in turn called in another transactional context).
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002356 */
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002357static void bdrv_replace_child_tran(BdrvChild **childp,
2358 BlockDriverState *new_bs,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002359 Transaction *tran,
2360 bool free_empty_child)
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002361{
2362 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2363 *s = (BdrvReplaceChildState) {
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002364 .child = *childp,
2365 .childp = new_bs == NULL ? childp : NULL,
2366 .old_bs = (*childp)->bs,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002367 .free_empty_child = free_empty_child,
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002368 };
2369 tran_add(tran, &bdrv_replace_child_drv, s);
2370
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002371 /* The abort handler relies on this */
2372 assert(s->old_bs != NULL);
2373
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002374 if (new_bs) {
2375 bdrv_ref(new_bs);
2376 }
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002377 /*
2378 * Pass free_empty_child=false, we will free the child (if
2379 * necessary) in bdrv_replace_child_commit() (if our
2380 * @free_empty_child parameter was true).
2381 */
2382 bdrv_replace_child_noperm(childp, new_bs, false);
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002383 /* old_bs reference is transparently moved from *childp to @s */
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002384}
2385
Kevin Wolf33a610c2016-12-15 13:04:20 +01002386/*
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002387 * Refresh permissions in @bs subtree. The function is intended to be called
2388 * after some graph modification that was done without permission update.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002389 */
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002390static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2391 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002392{
2393 BlockDriver *drv = bs->drv;
2394 BdrvChild *c;
2395 int ret;
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002396 uint64_t cumulative_perms, cumulative_shared_perms;
2397
2398 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002399
2400 /* Write permissions never work with read-only images */
2401 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002402 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002403 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002404 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2405 error_setg(errp, "Block node is read-only");
2406 } else {
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002407 error_setg(errp, "Read-only block node '%s' cannot support "
2408 "read-write users", bdrv_get_node_name(bs));
Max Reitz481e0ee2019-05-15 22:15:00 +02002409 }
2410
Kevin Wolf33a610c2016-12-15 13:04:20 +01002411 return -EPERM;
2412 }
2413
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002414 /*
2415 * Unaligned requests will automatically be aligned to bl.request_alignment
2416 * and without RESIZE we can't extend requests to write to space beyond the
2417 * end of the image, so it's required that the image size is aligned.
2418 */
2419 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2420 !(cumulative_perms & BLK_PERM_RESIZE))
2421 {
2422 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2423 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2424 "Image size is not a multiple of request "
2425 "alignment");
2426 return -EPERM;
2427 }
2428 }
2429
Kevin Wolf33a610c2016-12-15 13:04:20 +01002430 /* Check this node */
2431 if (!drv) {
2432 return 0;
2433 }
2434
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002435 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002436 errp);
2437 if (ret < 0) {
2438 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002439 }
2440
Kevin Wolf78e421c2016-12-20 23:25:12 +01002441 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002442 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002443 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002444 return 0;
2445 }
2446
2447 /* Check all children */
2448 QLIST_FOREACH(c, &bs->children, next) {
2449 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002450
Max Reitze5d8a402020-05-13 13:05:44 +02002451 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002452 cumulative_perms, cumulative_shared_perms,
2453 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002454 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002455 }
2456
2457 return 0;
2458}
2459
Vladimir Sementsov-Ogievskiy25409802021-04-28 18:18:00 +03002460static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2461 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002462{
2463 int ret;
2464 BlockDriverState *bs;
2465
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002466 for ( ; list; list = list->next) {
2467 bs = list->data;
2468
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002469 if (bdrv_parent_perms_conflict(bs, errp)) {
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002470 return -EINVAL;
2471 }
2472
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002473 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002474 if (ret < 0) {
2475 return ret;
2476 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002477 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002478
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002479 return 0;
2480}
2481
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002482void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2483 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002484{
2485 BdrvChild *c;
2486 uint64_t cumulative_perms = 0;
2487 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2488
2489 QLIST_FOREACH(c, &bs->parents, next_parent) {
2490 cumulative_perms |= c->perm;
2491 cumulative_shared_perms &= c->shared_perm;
2492 }
2493
2494 *perm = cumulative_perms;
2495 *shared_perm = cumulative_shared_perms;
2496}
2497
Fam Zheng51761962017-05-03 00:35:36 +08002498char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002499{
2500 struct perm_name {
2501 uint64_t perm;
2502 const char *name;
2503 } permissions[] = {
2504 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2505 { BLK_PERM_WRITE, "write" },
2506 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2507 { BLK_PERM_RESIZE, "resize" },
Kevin Wolfd0833192017-01-16 18:26:20 +01002508 { 0, NULL }
2509 };
2510
Alberto Garciae2a74232020-01-10 18:15:18 +01002511 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002512 struct perm_name *p;
2513
2514 for (p = permissions; p->name; p++) {
2515 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002516 if (result->len > 0) {
2517 g_string_append(result, ", ");
2518 }
2519 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002520 }
2521 }
2522
Alberto Garciae2a74232020-01-10 18:15:18 +01002523 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002524}
2525
Kevin Wolf33a610c2016-12-15 13:04:20 +01002526
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002527static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002528{
2529 int ret;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002530 Transaction *tran = tran_new();
2531 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002532
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002533 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2534 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002535
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002536 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002537}
2538
Kevin Wolf33a610c2016-12-15 13:04:20 +01002539int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2540 Error **errp)
2541{
Max Reitz10467792019-05-22 19:03:51 +02002542 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002543 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002544 int ret;
2545
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002546 bdrv_child_set_perm(c, perm, shared, tran);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002547
2548 ret = bdrv_refresh_perms(c->bs, &local_err);
2549
2550 tran_finalize(tran, ret);
2551
Kevin Wolf33a610c2016-12-15 13:04:20 +01002552 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002553 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2554 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002555 error_propagate(errp, local_err);
2556 } else {
2557 /*
2558 * Our caller may intend to only loosen restrictions and
2559 * does not expect this function to fail. Errors are not
2560 * fatal in such a case, so we can just hide them from our
2561 * caller.
2562 */
2563 error_free(local_err);
2564 ret = 0;
2565 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002566 }
2567
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002568 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002569}
2570
Max Reitzc1087f12019-05-22 19:03:46 +02002571int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2572{
2573 uint64_t parent_perms, parent_shared;
2574 uint64_t perms, shared;
2575
2576 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002577 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002578 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002579
2580 return bdrv_child_try_set_perm(c, perms, shared, errp);
2581}
2582
Max Reitz87278af2020-05-13 13:05:40 +02002583/*
2584 * Default implementation for .bdrv_child_perm() for block filters:
2585 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2586 * filtered child.
2587 */
2588static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002589 BdrvChildRole role,
2590 BlockReopenQueue *reopen_queue,
2591 uint64_t perm, uint64_t shared,
2592 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002593{
Kevin Wolfe444fa82019-08-02 15:59:41 +02002594 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2595 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002596}
2597
Max Reitz70082db2020-05-13 13:05:26 +02002598static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002599 BdrvChildRole role,
2600 BlockReopenQueue *reopen_queue,
2601 uint64_t perm, uint64_t shared,
2602 uint64_t *nperm, uint64_t *nshared)
2603{
Max Reitze5d8a402020-05-13 13:05:44 +02002604 assert(role & BDRV_CHILD_COW);
Max Reitz70082db2020-05-13 13:05:26 +02002605
2606 /*
2607 * We want consistent read from backing files if the parent needs it.
2608 * No other operations are performed on backing files.
2609 */
2610 perm &= BLK_PERM_CONSISTENT_READ;
2611
2612 /*
2613 * If the parent can deal with changing data, we're okay with a
2614 * writable and resizable backing file.
2615 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2616 */
2617 if (shared & BLK_PERM_WRITE) {
2618 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2619 } else {
2620 shared = 0;
2621 }
2622
Vladimir Sementsov-Ogievskiy64631f32021-09-02 12:37:54 +03002623 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
Max Reitz70082db2020-05-13 13:05:26 +02002624
2625 if (bs->open_flags & BDRV_O_INACTIVE) {
2626 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2627 }
2628
2629 *nperm = perm;
2630 *nshared = shared;
2631}
2632
Max Reitz6f838a42020-05-13 13:05:27 +02002633static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002634 BdrvChildRole role,
2635 BlockReopenQueue *reopen_queue,
2636 uint64_t perm, uint64_t shared,
2637 uint64_t *nperm, uint64_t *nshared)
2638{
2639 int flags;
2640
Max Reitze5d8a402020-05-13 13:05:44 +02002641 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002642
2643 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2644
2645 /*
2646 * Apart from the modifications below, the same permissions are
2647 * forwarded and left alone as for filters
2648 */
Max Reitze5d8a402020-05-13 13:05:44 +02002649 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002650 perm, shared, &perm, &shared);
2651
Max Reitzf8890542020-05-13 13:05:28 +02002652 if (role & BDRV_CHILD_METADATA) {
2653 /* Format drivers may touch metadata even if the guest doesn't write */
2654 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2655 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2656 }
2657
2658 /*
2659 * bs->file always needs to be consistent because of the
2660 * metadata. We can never allow other users to resize or write
2661 * to it.
2662 */
2663 if (!(flags & BDRV_O_NO_IO)) {
2664 perm |= BLK_PERM_CONSISTENT_READ;
2665 }
2666 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002667 }
2668
Max Reitzf8890542020-05-13 13:05:28 +02002669 if (role & BDRV_CHILD_DATA) {
2670 /*
2671 * Technically, everything in this block is a subset of the
2672 * BDRV_CHILD_METADATA path taken above, and so this could
2673 * be an "else if" branch. However, that is not obvious, and
2674 * this function is not performance critical, therefore we let
2675 * this be an independent "if".
2676 */
2677
2678 /*
2679 * We cannot allow other users to resize the file because the
2680 * format driver might have some assumptions about the size
2681 * (e.g. because it is stored in metadata, or because the file
2682 * is split into fixed-size data files).
2683 */
2684 shared &= ~BLK_PERM_RESIZE;
2685
2686 /*
2687 * WRITE_UNCHANGED often cannot be performed as such on the
2688 * data file. For example, the qcow2 driver may still need to
2689 * write copied clusters on copy-on-read.
2690 */
2691 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2692 perm |= BLK_PERM_WRITE;
2693 }
2694
2695 /*
2696 * If the data file is written to, the format driver may
2697 * expect to be able to resize it by writing beyond the EOF.
2698 */
2699 if (perm & BLK_PERM_WRITE) {
2700 perm |= BLK_PERM_RESIZE;
2701 }
Max Reitz6f838a42020-05-13 13:05:27 +02002702 }
Max Reitz6f838a42020-05-13 13:05:27 +02002703
2704 if (bs->open_flags & BDRV_O_INACTIVE) {
2705 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2706 }
2707
2708 *nperm = perm;
2709 *nshared = shared;
2710}
2711
Max Reitz2519f542020-05-13 13:05:29 +02002712void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002713 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002714 uint64_t perm, uint64_t shared,
2715 uint64_t *nperm, uint64_t *nshared)
2716{
Max Reitz2519f542020-05-13 13:05:29 +02002717 if (role & BDRV_CHILD_FILTERED) {
2718 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2719 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002720 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002721 perm, shared, nperm, nshared);
2722 } else if (role & BDRV_CHILD_COW) {
2723 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002724 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002725 perm, shared, nperm, nshared);
2726 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002727 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002728 perm, shared, nperm, nshared);
2729 } else {
2730 g_assert_not_reached();
2731 }
2732}
2733
Max Reitz7b1d9c42019-11-08 13:34:51 +01002734uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2735{
2736 static const uint64_t permissions[] = {
2737 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2738 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2739 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2740 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
Max Reitz7b1d9c42019-11-08 13:34:51 +01002741 };
2742
2743 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2744 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2745
2746 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2747
2748 return permissions[qapi_perm];
2749}
2750
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002751/**
2752 * Replace (*childp)->bs by @new_bs.
2753 *
2754 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2755 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2756 * BdrvChild.bs should generally immediately be followed by the
2757 * BdrvChild pointer being cleared as well.
2758 *
2759 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2760 * freed. @free_empty_child should only be false if the caller will
2761 * free the BdrvChild themselves (this may be important in a
2762 * transactional context, where it may only be freed on commit).
2763 */
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002764static void bdrv_replace_child_noperm(BdrvChild **childp,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002765 BlockDriverState *new_bs,
2766 bool free_empty_child)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002767{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002768 BdrvChild *child = *childp;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002769 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002770 int new_bs_quiesce_counter;
2771 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002772
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002773 assert(!child->frozen);
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02002774 assert(old_bs != new_bs);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002775
Fam Zhengbb2614e2017-04-07 14:54:10 +08002776 if (old_bs && new_bs) {
2777 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2778 }
Max Reitzdebc2922019-07-22 15:33:44 +02002779
2780 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2781 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2782
2783 /*
2784 * If the new child node is drained but the old one was not, flush
2785 * all outstanding requests to the old child node.
2786 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002787 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002788 bdrv_parent_drained_begin_single(child, true);
2789 drain_saldo--;
2790 }
2791
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002792 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002793 /* Detach first so that the recursive drain sections coming from @child
2794 * are already gone and we only end the drain sections that came from
2795 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002796 if (child->klass->detach) {
2797 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002798 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002799 QLIST_REMOVE(child, next_parent);
2800 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002801
2802 child->bs = new_bs;
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002803 if (!new_bs) {
2804 *childp = NULL;
2805 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002806
2807 if (new_bs) {
2808 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002809
2810 /*
2811 * Detaching the old node may have led to the new node's
2812 * quiesce_counter having been decreased. Not a problem, we
2813 * just need to recognize this here and then invoke
2814 * drained_end appropriately more often.
2815 */
2816 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2817 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002818
Kevin Wolfd736f112017-12-18 16:05:48 +01002819 /* Attach only after starting new drained sections, so that recursive
2820 * drain sections coming from @child don't get an extra .drained_begin
2821 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002822 if (child->klass->attach) {
2823 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002824 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002825 }
Max Reitzdebc2922019-07-22 15:33:44 +02002826
2827 /*
2828 * If the old child node was drained but the new one is not, allow
2829 * requests to come in only after the new node has been attached.
2830 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002831 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002832 bdrv_parent_drained_end_single(child);
2833 drain_saldo++;
2834 }
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002835
2836 if (free_empty_child && !child->bs) {
2837 bdrv_child_free(child);
2838 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002839}
2840
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002841/**
2842 * Free the given @child.
2843 *
2844 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2845 * unused (i.e. not in a children list).
2846 */
2847static void bdrv_child_free(BdrvChild *child)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002848{
2849 assert(!child->bs);
Hanna Reitza2253692021-11-15 15:53:58 +01002850 assert(!child->next.le_prev); /* not in children list */
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002851
2852 g_free(child->name);
2853 g_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002854}
2855
2856typedef struct BdrvAttachChildCommonState {
2857 BdrvChild **child;
2858 AioContext *old_parent_ctx;
2859 AioContext *old_child_ctx;
2860} BdrvAttachChildCommonState;
2861
2862static void bdrv_attach_child_common_abort(void *opaque)
2863{
2864 BdrvAttachChildCommonState *s = opaque;
2865 BdrvChild *child = *s->child;
2866 BlockDriverState *bs = child->bs;
2867
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002868 /*
2869 * Pass free_empty_child=false, because we still need the child
2870 * for the AioContext operations on the parent below; those
2871 * BdrvChildClass methods all work on a BdrvChild object, so we
2872 * need to keep it as an empty shell (after this function, it will
2873 * not be attached to any parent, and it will not have a .bs).
2874 */
2875 bdrv_replace_child_noperm(s->child, NULL, false);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002876
2877 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2878 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2879 }
2880
2881 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
Hanna Reitz26518062021-11-15 15:54:00 +01002882 GSList *ignore;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002883
Hanna Reitz26518062021-11-15 15:54:00 +01002884 /* No need to ignore `child`, because it has been detached already */
2885 ignore = NULL;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002886 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2887 &error_abort);
2888 g_slist_free(ignore);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002889
Hanna Reitz26518062021-11-15 15:54:00 +01002890 ignore = NULL;
2891 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002892 g_slist_free(ignore);
2893 }
2894
2895 bdrv_unref(bs);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002896 bdrv_child_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002897}
2898
2899static TransactionActionDrv bdrv_attach_child_common_drv = {
2900 .abort = bdrv_attach_child_common_abort,
2901 .clean = g_free,
2902};
2903
2904/*
2905 * Common part of attaching bdrv child to bs or to blk or to job
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002906 *
2907 * Resulting new child is returned through @child.
2908 * At start *@child must be NULL.
2909 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2910 * NULL on abort(). So referenced variable must live at least until transaction
2911 * end.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002912 *
2913 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002914 */
2915static int bdrv_attach_child_common(BlockDriverState *child_bs,
2916 const char *child_name,
2917 const BdrvChildClass *child_class,
2918 BdrvChildRole child_role,
2919 uint64_t perm, uint64_t shared_perm,
2920 void *opaque, BdrvChild **child,
2921 Transaction *tran, Error **errp)
2922{
2923 BdrvChild *new_child;
2924 AioContext *parent_ctx;
2925 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2926
2927 assert(child);
2928 assert(*child == NULL);
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002929 assert(child_class->get_parent_desc);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002930
2931 new_child = g_new(BdrvChild, 1);
2932 *new_child = (BdrvChild) {
2933 .bs = NULL,
2934 .name = g_strdup(child_name),
2935 .klass = child_class,
2936 .role = child_role,
2937 .perm = perm,
2938 .shared_perm = shared_perm,
2939 .opaque = opaque,
2940 };
2941
2942 /*
2943 * If the AioContexts don't match, first try to move the subtree of
2944 * child_bs into the AioContext of the new parent. If this doesn't work,
2945 * try moving the parent into the AioContext of child_bs instead.
2946 */
2947 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2948 if (child_ctx != parent_ctx) {
2949 Error *local_err = NULL;
2950 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2951
2952 if (ret < 0 && child_class->can_set_aio_ctx) {
2953 GSList *ignore = g_slist_prepend(NULL, new_child);
2954 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2955 NULL))
2956 {
2957 error_free(local_err);
2958 ret = 0;
2959 g_slist_free(ignore);
2960 ignore = g_slist_prepend(NULL, new_child);
2961 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2962 }
2963 g_slist_free(ignore);
2964 }
2965
2966 if (ret < 0) {
2967 error_propagate(errp, local_err);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002968 bdrv_child_free(new_child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002969 return ret;
2970 }
2971 }
2972
2973 bdrv_ref(child_bs);
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002974 bdrv_replace_child_noperm(&new_child, child_bs, true);
2975 /* child_bs was non-NULL, so new_child must not have been freed */
2976 assert(new_child != NULL);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002977
2978 *child = new_child;
2979
2980 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
2981 *s = (BdrvAttachChildCommonState) {
2982 .child = child,
2983 .old_parent_ctx = parent_ctx,
2984 .old_child_ctx = child_ctx,
2985 };
2986 tran_add(tran, &bdrv_attach_child_common_drv, s);
2987
2988 return 0;
2989}
2990
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002991/*
2992 * Variable referenced by @child must live at least until transaction end.
2993 * (see bdrv_attach_child_common() doc for details)
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002994 *
2995 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002996 */
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002997static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
2998 BlockDriverState *child_bs,
2999 const char *child_name,
3000 const BdrvChildClass *child_class,
3001 BdrvChildRole child_role,
3002 BdrvChild **child,
3003 Transaction *tran,
3004 Error **errp)
3005{
3006 int ret;
3007 uint64_t perm, shared_perm;
3008
3009 assert(parent_bs->drv);
3010
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02003011 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3012 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3013 child_bs->node_name, child_name, parent_bs->node_name);
3014 return -EINVAL;
3015 }
3016
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003017 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3018 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3019 perm, shared_perm, &perm, &shared_perm);
3020
3021 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3022 child_role, perm, shared_perm, parent_bs,
3023 child, tran, errp);
3024 if (ret < 0) {
3025 return ret;
3026 }
3027
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003028 return 0;
3029}
3030
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003031static void bdrv_detach_child(BdrvChild **childp)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003032{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003033 BlockDriverState *old_bs = (*childp)->bs;
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003034
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01003035 bdrv_replace_child_noperm(childp, NULL, true);
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003036
3037 if (old_bs) {
3038 /*
3039 * Update permissions for old node. We're just taking a parent away, so
3040 * we're loosening restrictions. Errors of permission update are not
3041 * fatal in this case, ignore them.
3042 */
3043 bdrv_refresh_perms(old_bs, NULL);
3044
3045 /*
3046 * When the parent requiring a non-default AioContext is removed, the
3047 * node moves back to the main AioContext
3048 */
3049 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3050 }
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003051}
3052
Alberto Garciab441dc72019-05-13 16:46:18 +03003053/*
3054 * This function steals the reference to child_bs from the caller.
3055 * That reference is later dropped by bdrv_root_unref_child().
3056 *
3057 * On failure NULL is returned, errp is set and the reference to
3058 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003059 *
3060 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3061 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003062 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003063BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3064 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003065 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003066 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003067 uint64_t perm, uint64_t shared_perm,
3068 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003069{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003070 int ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003071 BdrvChild *child = NULL;
3072 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003073
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003074 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3075 child_role, perm, shared_perm, opaque,
3076 &child, tran, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003077 if (ret < 0) {
Kevin Wolfe878bb12021-05-03 13:05:54 +02003078 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003079 }
3080
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003081 ret = bdrv_refresh_perms(child_bs, errp);
Kevin Wolfdf581792015-06-15 11:53:47 +02003082
Kevin Wolfe878bb12021-05-03 13:05:54 +02003083out:
3084 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003085 /* child is unset on failure by bdrv_attach_child_common_abort() */
3086 assert((ret < 0) == !child);
3087
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003088 bdrv_unref(child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003089 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003090}
3091
Alberto Garciab441dc72019-05-13 16:46:18 +03003092/*
3093 * This function transfers the reference to child_bs from the caller
3094 * to parent_bs. That reference is later dropped by parent_bs on
3095 * bdrv_close() or if someone calls bdrv_unref_child().
3096 *
3097 * On failure NULL is returned, errp is set and the reference to
3098 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003099 *
3100 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3101 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003102 */
Wen Congyang98292c62016-05-10 15:36:38 +08003103BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3104 BlockDriverState *child_bs,
3105 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003106 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003107 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003108 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003109{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003110 int ret;
3111 BdrvChild *child = NULL;
3112 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003113
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003114 GLOBAL_STATE_CODE();
3115
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003116 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3117 child_role, &child, tran, errp);
3118 if (ret < 0) {
3119 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003120 }
3121
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003122 ret = bdrv_refresh_perms(parent_bs, errp);
3123 if (ret < 0) {
3124 goto out;
3125 }
3126
3127out:
3128 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003129 /* child is unset on failure by bdrv_attach_child_common_abort() */
3130 assert((ret < 0) == !child);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003131
3132 bdrv_unref(child_bs);
3133
Kevin Wolff21d96d2016-03-08 13:47:46 +01003134 return child;
3135}
3136
Max Reitz7b99a262019-06-12 16:07:11 +02003137/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003138void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003139{
Kevin Wolf779020c2015-10-13 14:09:44 +02003140 BlockDriverState *child_bs;
3141
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003142 GLOBAL_STATE_CODE();
3143
Kevin Wolff21d96d2016-03-08 13:47:46 +01003144 child_bs = child->bs;
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003145 bdrv_detach_child(&child);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003146 bdrv_unref(child_bs);
3147}
3148
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003149typedef struct BdrvSetInheritsFrom {
3150 BlockDriverState *bs;
3151 BlockDriverState *old_inherits_from;
3152} BdrvSetInheritsFrom;
3153
3154static void bdrv_set_inherits_from_abort(void *opaque)
3155{
3156 BdrvSetInheritsFrom *s = opaque;
3157
3158 s->bs->inherits_from = s->old_inherits_from;
3159}
3160
3161static TransactionActionDrv bdrv_set_inherits_from_drv = {
3162 .abort = bdrv_set_inherits_from_abort,
3163 .clean = g_free,
3164};
3165
3166/* @tran is allowed to be NULL. In this case no rollback is possible */
3167static void bdrv_set_inherits_from(BlockDriverState *bs,
3168 BlockDriverState *new_inherits_from,
3169 Transaction *tran)
3170{
3171 if (tran) {
3172 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3173
3174 *s = (BdrvSetInheritsFrom) {
3175 .bs = bs,
3176 .old_inherits_from = bs->inherits_from,
3177 };
3178
3179 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3180 }
3181
3182 bs->inherits_from = new_inherits_from;
3183}
3184
Max Reitz3cf746b2019-07-03 19:28:07 +02003185/**
3186 * Clear all inherits_from pointers from children and grandchildren of
3187 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003188 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003189 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003190static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3191 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003192{
Max Reitz3cf746b2019-07-03 19:28:07 +02003193 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003194
Max Reitz3cf746b2019-07-03 19:28:07 +02003195 if (child->bs->inherits_from == root) {
3196 /*
3197 * Remove inherits_from only when the last reference between root and
3198 * child->bs goes away.
3199 */
3200 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003201 if (c != child && c->bs == child->bs) {
3202 break;
3203 }
3204 }
3205 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003206 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003207 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003208 }
3209
Max Reitz3cf746b2019-07-03 19:28:07 +02003210 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003211 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003212 }
3213}
3214
Max Reitz7b99a262019-06-12 16:07:11 +02003215/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003216void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3217{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003218 GLOBAL_STATE_CODE();
Max Reitz3cf746b2019-07-03 19:28:07 +02003219 if (child == NULL) {
3220 return;
3221 }
3222
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003223 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003224 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003225}
3226
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003227
3228static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3229{
3230 BdrvChild *c;
3231 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003232 if (c->klass->change_media) {
3233 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003234 }
3235 }
3236}
3237
Alberto Garcia0065c452018-10-31 18:16:37 +02003238/* Return true if you can reach parent going through child->inherits_from
3239 * recursively. If parent or child are NULL, return false */
3240static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3241 BlockDriverState *parent)
3242{
3243 while (child && child != parent) {
3244 child = child->inherits_from;
3245 }
3246
3247 return child != NULL;
3248}
3249
Kevin Wolf5db15a52015-09-14 15:33:33 +02003250/*
Max Reitz25191e52020-05-13 13:05:33 +02003251 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3252 * mostly used for COW backing children (role = COW), but also for
3253 * filtered children (role = FILTERED | PRIMARY).
3254 */
3255static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3256{
3257 if (bs->drv && bs->drv->is_filter) {
3258 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3259 } else {
3260 return BDRV_CHILD_COW;
3261 }
3262}
3263
3264/*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003265 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3266 * callers which don't need their own reference any more must call bdrv_unref().
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003267 *
3268 * Function doesn't update permissions, caller is responsible for this.
Kevin Wolf5db15a52015-09-14 15:33:33 +02003269 */
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003270static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3271 BlockDriverState *child_bs,
3272 bool is_backing,
3273 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003274{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003275 int ret = 0;
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003276 bool update_inherits_from =
3277 bdrv_inherits_from_recursive(child_bs, parent_bs);
3278 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3279 BdrvChildRole role;
Alberto Garcia0065c452018-10-31 18:16:37 +02003280
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003281 if (!parent_bs->drv) {
3282 /*
3283 * Node without drv is an object without a class :/. TODO: finally fix
3284 * qcow2 driver to never clear bs->drv and implement format corruption
3285 * handling in other way.
3286 */
3287 error_setg(errp, "Node corrupted");
3288 return -EINVAL;
3289 }
3290
3291 if (child && child->frozen) {
3292 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3293 child->name, parent_bs->node_name, child->bs->node_name);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003294 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003295 }
3296
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03003297 if (is_backing && !parent_bs->drv->is_filter &&
3298 !parent_bs->drv->supports_backing)
3299 {
3300 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3301 "files", parent_bs->drv->format_name, parent_bs->node_name);
3302 return -EINVAL;
3303 }
3304
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003305 if (parent_bs->drv->is_filter) {
3306 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3307 } else if (is_backing) {
3308 role = BDRV_CHILD_COW;
3309 } else {
3310 /*
3311 * We only can use same role as it is in existing child. We don't have
3312 * infrastructure to determine role of file child in generic way
3313 */
3314 if (!child) {
3315 error_setg(errp, "Cannot set file child to format node without "
3316 "file child");
3317 return -EINVAL;
3318 }
3319 role = child->role;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003320 }
3321
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003322 if (child) {
3323 bdrv_unset_inherits_from(parent_bs, child, tran);
3324 bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3325 }
3326
3327 if (!child_bs) {
Fam Zheng8d24cce2014-05-23 21:29:45 +08003328 goto out;
3329 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003330
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003331 ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3332 is_backing ? "backing" : "file",
3333 &child_of_bds, role,
3334 is_backing ? &parent_bs->backing :
3335 &parent_bs->file,
3336 tran, errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003337 if (ret < 0) {
3338 return ret;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003339 }
3340
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003341
3342 /*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003343 * If inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003344 * point directly to bs (else it will become NULL).
3345 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003346 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003347 bdrv_set_inherits_from(child_bs, parent_bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003348 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003349
Fam Zheng8d24cce2014-05-23 21:29:45 +08003350out:
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003351 bdrv_refresh_limits(parent_bs, tran, NULL);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003352
3353 return 0;
3354}
3355
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003356static int bdrv_set_backing_noperm(BlockDriverState *bs,
3357 BlockDriverState *backing_hd,
3358 Transaction *tran, Error **errp)
3359{
3360 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3361}
3362
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003363int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3364 Error **errp)
3365{
3366 int ret;
3367 Transaction *tran = tran_new();
3368
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003369 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003370 bdrv_drained_begin(bs);
3371
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003372 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3373 if (ret < 0) {
3374 goto out;
3375 }
3376
3377 ret = bdrv_refresh_perms(bs, errp);
3378out:
3379 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003380
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003381 bdrv_drained_end(bs);
3382
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003383 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003384}
3385
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003386/*
3387 * Opens the backing file for a BlockDriverState if not yet open
3388 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003389 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3390 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3391 * itself, all options starting with "${bdref_key}." are considered part of the
3392 * BlockdevRef.
3393 *
3394 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003395 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003396int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3397 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003398{
Max Reitz6b6833c2019-02-01 20:29:15 +01003399 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003400 char *bdref_key_dot;
3401 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003402 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003403 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003404 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003405 QDict *options;
3406 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003407 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003408
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003409 GLOBAL_STATE_CODE();
3410
Kevin Wolf760e0062015-06-17 14:55:21 +02003411 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003412 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003413 }
3414
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003415 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003416 if (parent_options == NULL) {
3417 tmp_parent_options = qdict_new();
3418 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003419 }
3420
Paolo Bonzini9156df12012-10-18 16:49:17 +02003421 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003422
3423 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3424 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3425 g_free(bdref_key_dot);
3426
Markus Armbruster129c7d12017-03-30 19:43:12 +02003427 /*
3428 * Caution: while qdict_get_try_str() is fine, getting non-string
3429 * types would require more care. When @parent_options come from
3430 * -blockdev or blockdev_add, its members are typed according to
3431 * the QAPI schema, but when they come from -drive, they're all
3432 * QString.
3433 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003434 reference = qdict_get_try_str(parent_options, bdref_key);
3435 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003436 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003437 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003438 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003439 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003440 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003441 if (qdict_size(options) == 0) {
3442 /* If the user specifies options that do not modify the
3443 * backing file's behavior, we might still consider it the
3444 * implicit backing file. But it's easier this way, and
3445 * just specifying some of the backing BDS's options is
3446 * only possible with -drive anyway (otherwise the QAPI
3447 * schema forces the user to specify everything). */
3448 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3449 }
3450
Max Reitz6b6833c2019-02-01 20:29:15 +01003451 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003452 if (local_err) {
3453 ret = -EINVAL;
3454 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003455 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003456 goto free_exit;
3457 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003458 }
3459
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003460 if (!bs->drv || !bs->drv->supports_backing) {
3461 ret = -EINVAL;
3462 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003463 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003464 goto free_exit;
3465 }
3466
Peter Krempa6bff5972017-10-12 16:14:10 +02003467 if (!reference &&
3468 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003469 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003470 }
3471
Max Reitz6b6833c2019-02-01 20:29:15 +01003472 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003473 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003474 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003475 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003476 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003477 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003478 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003479 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003480
Max Reitz998c2012019-02-01 20:29:08 +01003481 if (implicit_backing) {
3482 bdrv_refresh_filename(backing_hd);
3483 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3484 backing_hd->filename);
3485 }
3486
Kevin Wolf5db15a52015-09-14 15:33:33 +02003487 /* Hook up the backing file link; drop our reference, bs owns the
3488 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003489 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003490 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003491 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003492 goto free_exit;
3493 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003494
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003495 qdict_del(parent_options, bdref_key);
3496
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003497free_exit:
3498 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003499 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003500 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003501}
3502
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003503static BlockDriverState *
3504bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003505 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003506 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003507{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003508 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003509 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003510 char *bdref_key_dot;
3511 const char *reference;
3512
Max Reitzbd86fb92020-05-13 13:05:13 +02003513 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003514
Max Reitzda557aa2013-12-20 19:28:11 +01003515 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3516 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3517 g_free(bdref_key_dot);
3518
Markus Armbruster129c7d12017-03-30 19:43:12 +02003519 /*
3520 * Caution: while qdict_get_try_str() is fine, getting non-string
3521 * types would require more care. When @options come from
3522 * -blockdev or blockdev_add, its members are typed according to
3523 * the QAPI schema, but when they come from -drive, they're all
3524 * QString.
3525 */
Max Reitzda557aa2013-12-20 19:28:11 +01003526 reference = qdict_get_try_str(options, bdref_key);
3527 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003528 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003529 error_setg(errp, "A block device must be specified for \"%s\"",
3530 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003531 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003532 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003533 goto done;
3534 }
3535
Max Reitz5b363932016-05-17 16:41:31 +02003536 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003537 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003538 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003539 goto done;
3540 }
3541
Max Reitzda557aa2013-12-20 19:28:11 +01003542done:
3543 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003544 return bs;
3545}
3546
3547/*
3548 * Opens a disk image whose options are given as BlockdevRef in another block
3549 * device's options.
3550 *
3551 * If allow_none is true, no image will be opened if filename is false and no
3552 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3553 *
3554 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3555 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3556 * itself, all options starting with "${bdref_key}." are considered part of the
3557 * BlockdevRef.
3558 *
3559 * The BlockdevRef will be removed from the options QDict.
3560 */
3561BdrvChild *bdrv_open_child(const char *filename,
3562 QDict *options, const char *bdref_key,
3563 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003564 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003565 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003566 bool allow_none, Error **errp)
3567{
3568 BlockDriverState *bs;
3569
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003570 GLOBAL_STATE_CODE();
3571
Max Reitzbd86fb92020-05-13 13:05:13 +02003572 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003573 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003574 if (bs == NULL) {
3575 return NULL;
3576 }
3577
Max Reitz258b7762020-05-13 13:05:15 +02003578 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3579 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003580}
3581
Max Reitzbd86fb92020-05-13 13:05:13 +02003582/*
3583 * TODO Future callers may need to specify parent/child_class in order for
3584 * option inheritance to work. Existing callers use it for the root node.
3585 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003586BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3587{
3588 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003589 QObject *obj = NULL;
3590 QDict *qdict = NULL;
3591 const char *reference = NULL;
3592 Visitor *v = NULL;
3593
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003594 GLOBAL_STATE_CODE();
3595
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003596 if (ref->type == QTYPE_QSTRING) {
3597 reference = ref->u.reference;
3598 } else {
3599 BlockdevOptions *options = &ref->u.definition;
3600 assert(ref->type == QTYPE_QDICT);
3601
3602 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003603 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003604 visit_complete(v, &obj);
3605
Max Reitz7dc847e2018-02-24 16:40:29 +01003606 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003607 qdict_flatten(qdict);
3608
3609 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3610 * compatibility with other callers) rather than what we want as the
3611 * real defaults. Apply the defaults here instead. */
3612 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3613 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3614 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003615 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3616
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003617 }
3618
Max Reitz272c02e2020-05-13 13:05:17 +02003619 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003620 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003621 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003622 visit_free(v);
3623 return bs;
3624}
3625
Max Reitz66836182016-05-17 16:41:27 +02003626static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3627 int flags,
3628 QDict *snapshot_options,
3629 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003630{
3631 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003632 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003633 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003634 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003635 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003636 int ret;
3637
3638 /* if snapshot, we create a temporary backing file and open it
3639 instead of opening 'filename' directly */
3640
3641 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003642 total_size = bdrv_getlength(bs);
3643 if (total_size < 0) {
3644 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003645 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003646 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003647
3648 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003649 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003650 if (ret < 0) {
3651 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003652 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003653 }
3654
Max Reitzef810432014-12-02 18:32:42 +01003655 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003656 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003657 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003658 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003659 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003660 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003661 error_prepend(errp, "Could not create temporary overlay '%s': ",
3662 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003663 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003664 }
3665
Kevin Wolf73176be2016-03-07 13:02:15 +01003666 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003667 qdict_put_str(snapshot_options, "file.driver", "file");
3668 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3669 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003670
Max Reitz5b363932016-05-17 16:41:31 +02003671 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003672 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003673 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003674 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003675 }
3676
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003677 ret = bdrv_append(bs_snapshot, bs, errp);
3678 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003679 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003680 goto out;
3681 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003682
3683out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003684 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003685 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003686 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003687}
3688
Max Reitzda557aa2013-12-20 19:28:11 +01003689/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003690 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003691 *
3692 * options is a QDict of options to pass to the block drivers, or NULL for an
3693 * empty set of options. The reference to the QDict belongs to the block layer
3694 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003695 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003696 *
3697 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3698 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003699 *
3700 * The reference parameter may be used to specify an existing block device which
3701 * should be opened. If specified, neither options nor a filename may be given,
3702 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003703 */
Max Reitz5b363932016-05-17 16:41:31 +02003704static BlockDriverState *bdrv_open_inherit(const char *filename,
3705 const char *reference,
3706 QDict *options, int flags,
3707 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003708 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003709 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003710 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003711{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003712 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003713 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003714 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003715 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003716 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003717 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003718 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003719 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003720 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003721 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003722
Max Reitzbd86fb92020-05-13 13:05:13 +02003723 assert(!child_class || !flags);
3724 assert(!child_class == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01003725
Max Reitzddf56362014-02-18 18:33:06 +01003726 if (reference) {
3727 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003728 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003729
Max Reitzddf56362014-02-18 18:33:06 +01003730 if (filename || options_non_empty) {
3731 error_setg(errp, "Cannot reference an existing block device with "
3732 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003733 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003734 }
3735
3736 bs = bdrv_lookup_bs(reference, reference, errp);
3737 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003738 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003739 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003740
Max Reitzddf56362014-02-18 18:33:06 +01003741 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003742 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003743 }
3744
Max Reitz5b363932016-05-17 16:41:31 +02003745 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003746
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003747 /* NULL means an empty set of options */
3748 if (options == NULL) {
3749 options = qdict_new();
3750 }
3751
Kevin Wolf145f5982015-05-08 16:15:03 +02003752 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003753 parse_json_protocol(options, &filename, &local_err);
3754 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003755 goto fail;
3756 }
3757
Kevin Wolf145f5982015-05-08 16:15:03 +02003758 bs->explicit_options = qdict_clone_shallow(options);
3759
Max Reitzbd86fb92020-05-13 13:05:13 +02003760 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003761 bool parent_is_format;
3762
3763 if (parent->drv) {
3764 parent_is_format = parent->drv->is_format;
3765 } else {
3766 /*
3767 * parent->drv is not set yet because this node is opened for
3768 * (potential) format probing. That means that @parent is going
3769 * to be a format node.
3770 */
3771 parent_is_format = true;
3772 }
3773
Kevin Wolfbddcec32015-04-09 18:47:50 +02003774 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003775 child_class->inherit_options(child_role, parent_is_format,
3776 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003777 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003778 }
3779
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003780 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003781 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003782 goto fail;
3783 }
3784
Markus Armbruster129c7d12017-03-30 19:43:12 +02003785 /*
3786 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3787 * Caution: getting a boolean member of @options requires care.
3788 * When @options come from -blockdev or blockdev_add, members are
3789 * typed according to the QAPI schema, but when they come from
3790 * -drive, they're all QString.
3791 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003792 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3793 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3794 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3795 } else {
3796 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003797 }
3798
3799 if (flags & BDRV_O_SNAPSHOT) {
3800 snapshot_options = qdict_new();
3801 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3802 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003803 /* Let bdrv_backing_options() override "read-only" */
3804 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003805 bdrv_inherited_options(BDRV_CHILD_COW, true,
3806 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003807 }
3808
Kevin Wolf62392eb2015-04-24 16:38:02 +02003809 bs->open_flags = flags;
3810 bs->options = options;
3811 options = qdict_clone_shallow(options);
3812
Kevin Wolf76c591b2014-06-04 14:19:44 +02003813 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003814 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003815 drvname = qdict_get_try_str(options, "driver");
3816 if (drvname) {
3817 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003818 if (!drv) {
3819 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003820 goto fail;
3821 }
3822 }
3823
3824 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003825
Markus Armbruster129c7d12017-03-30 19:43:12 +02003826 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003827 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003828 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3829 (backing && *backing == '\0'))
3830 {
Max Reitz4f7be282018-02-24 16:40:33 +01003831 if (backing) {
3832 warn_report("Use of \"backing\": \"\" is deprecated; "
3833 "use \"backing\": null instead");
3834 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003835 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003836 qdict_del(bs->explicit_options, "backing");
3837 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003838 qdict_del(options, "backing");
3839 }
3840
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003841 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003842 * probing, the block drivers will do their own bdrv_open_child() for the
3843 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003844 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003845 BlockDriverState *file_bs;
3846
3847 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003848 &child_of_bds, BDRV_CHILD_IMAGE,
3849 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003850 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003851 goto fail;
3852 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003853 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003854 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3855 * looking at the header to guess the image format. This works even
3856 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003857 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003858 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003859 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003860 if (local_err) {
3861 goto fail;
3862 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003863
Eric Blake46f5ac22017-04-27 16:58:17 -05003864 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003865 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003866 }
3867
Kevin Wolf76c591b2014-06-04 14:19:44 +02003868 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003869 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003870 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003871 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003872 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003873 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003874 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003875 /*
3876 * This option update would logically belong in bdrv_fill_options(),
3877 * but we first need to open bs->file for the probing to work, while
3878 * opening bs->file already requires the (mostly) final set of options
3879 * so that cache mode etc. can be inherited.
3880 *
3881 * Adding the driver later is somewhat ugly, but it's not an option
3882 * that would ever be inherited, so it's correct. We just need to make
3883 * sure to update both bs->options (which has the full effective
3884 * options for bs) and options (which has file.* already removed).
3885 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003886 qdict_put_str(bs->options, "driver", drv->format_name);
3887 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003888 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003889 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003890 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003891 }
3892
Max Reitz53a29512015-03-19 14:53:16 -04003893 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3894 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3895 /* file must be NULL if a protocol BDS is about to be created
3896 * (the inverse results in an error message from bdrv_open_common()) */
3897 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3898
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003899 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003900 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003901 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003902 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003903 }
3904
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003905 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003906 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003907 file = NULL;
3908 }
3909
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003910 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003911 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003912 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003913 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003914 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003915 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003916 }
3917
Alberto Garcia50196d72018-09-06 12:37:03 +03003918 /* Remove all children options and references
3919 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003920 QLIST_FOREACH(child, &bs->children, next) {
3921 char *child_key_dot;
3922 child_key_dot = g_strdup_printf("%s.", child->name);
3923 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3924 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003925 qdict_del(bs->explicit_options, child->name);
3926 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003927 g_free(child_key_dot);
3928 }
3929
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003930 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003931 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003932 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003933 if (flags & BDRV_O_PROTOCOL) {
3934 error_setg(errp, "Block protocol '%s' doesn't support the option "
3935 "'%s'", drv->format_name, entry->key);
3936 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003937 error_setg(errp,
3938 "Block format '%s' does not support the option '%s'",
3939 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003940 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003941
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003942 goto close_and_fail;
3943 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003944
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003945 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003946
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003947 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003948 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003949
3950 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3951 * temporary snapshot afterwards. */
3952 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003953 BlockDriverState *snapshot_bs;
3954 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3955 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003956 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003957 if (local_err) {
3958 goto close_and_fail;
3959 }
Max Reitz5b363932016-05-17 16:41:31 +02003960 /* We are not going to return bs but the overlay on top of it
3961 * (snapshot_bs); thus, we have to drop the strong reference to bs
3962 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3963 * though, because the overlay still has a reference to it. */
3964 bdrv_unref(bs);
3965 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003966 }
3967
Max Reitz5b363932016-05-17 16:41:31 +02003968 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003969
Kevin Wolf8bfea152014-04-11 19:16:36 +02003970fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003971 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003972 qobject_unref(snapshot_options);
3973 qobject_unref(bs->explicit_options);
3974 qobject_unref(bs->options);
3975 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003976 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003977 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003978 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003979 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003980 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003981
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003982close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02003983 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003984 qobject_unref(snapshot_options);
3985 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003986 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003987 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003988}
3989
Max Reitz5b363932016-05-17 16:41:31 +02003990BlockDriverState *bdrv_open(const char *filename, const char *reference,
3991 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02003992{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003993 GLOBAL_STATE_CODE();
3994
Max Reitz5b363932016-05-17 16:41:31 +02003995 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02003996 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003997}
3998
Alberto Garciafaf116b2019-03-12 18:48:49 +02003999/* Return true if the NULL-terminated @list contains @str */
4000static bool is_str_in_list(const char *str, const char *const *list)
4001{
4002 if (str && list) {
4003 int i;
4004 for (i = 0; list[i] != NULL; i++) {
4005 if (!strcmp(str, list[i])) {
4006 return true;
4007 }
4008 }
4009 }
4010 return false;
4011}
4012
4013/*
4014 * Check that every option set in @bs->options is also set in
4015 * @new_opts.
4016 *
4017 * Options listed in the common_options list and in
4018 * @bs->drv->mutable_opts are skipped.
4019 *
4020 * Return 0 on success, otherwise return -EINVAL and set @errp.
4021 */
4022static int bdrv_reset_options_allowed(BlockDriverState *bs,
4023 const QDict *new_opts, Error **errp)
4024{
4025 const QDictEntry *e;
4026 /* These options are common to all block drivers and are handled
4027 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4028 const char *const common_options[] = {
4029 "node-name", "discard", "cache.direct", "cache.no-flush",
4030 "read-only", "auto-read-only", "detect-zeroes", NULL
4031 };
4032
4033 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4034 if (!qdict_haskey(new_opts, e->key) &&
4035 !is_str_in_list(e->key, common_options) &&
4036 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4037 error_setg(errp, "Option '%s' cannot be reset "
4038 "to its default value", e->key);
4039 return -EINVAL;
4040 }
4041 }
4042
4043 return 0;
4044}
4045
Jeff Codye971aa12012-09-20 15:13:19 -04004046/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004047 * Returns true if @child can be reached recursively from @bs
4048 */
4049static bool bdrv_recurse_has_child(BlockDriverState *bs,
4050 BlockDriverState *child)
4051{
4052 BdrvChild *c;
4053
4054 if (bs == child) {
4055 return true;
4056 }
4057
4058 QLIST_FOREACH(c, &bs->children, next) {
4059 if (bdrv_recurse_has_child(c->bs, child)) {
4060 return true;
4061 }
4062 }
4063
4064 return false;
4065}
4066
4067/*
Jeff Codye971aa12012-09-20 15:13:19 -04004068 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4069 * reopen of multiple devices.
4070 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004071 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04004072 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4073 * be created and initialized. This newly created BlockReopenQueue should be
4074 * passed back in for subsequent calls that are intended to be of the same
4075 * atomic 'set'.
4076 *
4077 * bs is the BlockDriverState to add to the reopen queue.
4078 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004079 * options contains the changed options for the associated bs
4080 * (the BlockReopenQueue takes ownership)
4081 *
Jeff Codye971aa12012-09-20 15:13:19 -04004082 * flags contains the open flags for the associated bs
4083 *
4084 * returns a pointer to bs_queue, which is either the newly allocated
4085 * bs_queue, or the existing bs_queue being used.
4086 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004087 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004088 */
Kevin Wolf28518102015-05-08 17:07:31 +02004089static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4090 BlockDriverState *bs,
4091 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02004092 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02004093 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004094 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02004095 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004096 int parent_flags,
4097 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04004098{
4099 assert(bs != NULL);
4100
4101 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02004102 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004103 QDict *old_options, *explicit_options, *options_copy;
4104 int flags;
4105 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004106
Kevin Wolf1a63a902017-12-06 20:24:44 +01004107 /* Make sure that the caller remembered to use a drained section. This is
4108 * important to avoid graph changes between the recursive queuing here and
4109 * bdrv_reopen_multiple(). */
4110 assert(bs->quiesce_counter > 0);
4111
Jeff Codye971aa12012-09-20 15:13:19 -04004112 if (bs_queue == NULL) {
4113 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004114 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04004115 }
4116
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004117 if (!options) {
4118 options = qdict_new();
4119 }
4120
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004121 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004122 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004123 if (bs == bs_entry->state.bs) {
4124 break;
4125 }
4126 }
4127
Kevin Wolf28518102015-05-08 17:07:31 +02004128 /*
4129 * Precedence of options:
4130 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004131 * 2. Retained from explicitly set options of bs
4132 * 3. Inherited from parent node
4133 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004134 */
4135
Kevin Wolf145f5982015-05-08 16:15:03 +02004136 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004137 if (bs_entry || keep_old_opts) {
4138 old_options = qdict_clone_shallow(bs_entry ?
4139 bs_entry->state.explicit_options :
4140 bs->explicit_options);
4141 bdrv_join_options(bs, options, old_options);
4142 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004143 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004144
4145 explicit_options = qdict_clone_shallow(options);
4146
Kevin Wolf28518102015-05-08 17:07:31 +02004147 /* Inherit from parent node */
4148 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004149 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004150 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004151 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004152 } else {
4153 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004154 }
4155
Alberto Garcia077e8e22019-03-12 18:48:44 +02004156 if (keep_old_opts) {
4157 /* Old values are used for options that aren't set yet */
4158 old_options = qdict_clone_shallow(bs->options);
4159 bdrv_join_options(bs, options, old_options);
4160 qobject_unref(old_options);
4161 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004162
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004163 /* We have the final set of options so let's update the flags */
4164 options_copy = qdict_clone_shallow(options);
4165 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4166 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4167 update_flags_from_options(&flags, opts);
4168 qemu_opts_del(opts);
4169 qobject_unref(options_copy);
4170
Kevin Wolffd452022017-08-03 17:02:59 +02004171 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004172 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004173 if (flags & BDRV_O_RDWR) {
4174 flags |= BDRV_O_ALLOW_RDWR;
4175 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004176
Kevin Wolf1857c972017-09-14 14:53:46 +02004177 if (!bs_entry) {
4178 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004179 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004180 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004181 qobject_unref(bs_entry->state.options);
4182 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004183 }
4184
4185 bs_entry->state.bs = bs;
4186 bs_entry->state.options = options;
4187 bs_entry->state.explicit_options = explicit_options;
4188 bs_entry->state.flags = flags;
4189
Alberto Garcia85466322019-03-12 18:48:45 +02004190 /*
4191 * If keep_old_opts is false then it means that unspecified
4192 * options must be reset to their original value. We don't allow
4193 * resetting 'backing' but we need to know if the option is
4194 * missing in order to decide if we have to return an error.
4195 */
4196 if (!keep_old_opts) {
4197 bs_entry->state.backing_missing =
4198 !qdict_haskey(options, "backing") &&
4199 !qdict_haskey(options, "backing.driver");
4200 }
4201
Kevin Wolf67251a32015-04-09 18:54:04 +02004202 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004203 QDict *new_child_options = NULL;
4204 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004205
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004206 /* reopen can only change the options of block devices that were
4207 * implicitly created and inherited options. For other (referenced)
4208 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004209 if (child->bs->inherits_from != bs) {
4210 continue;
4211 }
4212
Alberto Garcia85466322019-03-12 18:48:45 +02004213 /* Check if the options contain a child reference */
4214 if (qdict_haskey(options, child->name)) {
4215 const char *childref = qdict_get_try_str(options, child->name);
4216 /*
4217 * The current child must not be reopened if the child
4218 * reference is null or points to a different node.
4219 */
4220 if (g_strcmp0(childref, child->bs->node_name)) {
4221 continue;
4222 }
4223 /*
4224 * If the child reference points to the current child then
4225 * reopen it with its existing set of options (note that
4226 * it can still inherit new options from the parent).
4227 */
4228 child_keep_old = true;
4229 } else {
4230 /* Extract child options ("child-name.*") */
4231 char *child_key_dot = g_strdup_printf("%s.", child->name);
4232 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4233 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4234 g_free(child_key_dot);
4235 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004236
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004237 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004238 child->klass, child->role, bs->drv->is_format,
4239 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004240 }
4241
Jeff Codye971aa12012-09-20 15:13:19 -04004242 return bs_queue;
4243}
4244
Kevin Wolf28518102015-05-08 17:07:31 +02004245BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4246 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004247 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004248{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004249 GLOBAL_STATE_CODE();
4250
Max Reitz3cdc69d2020-05-13 13:05:18 +02004251 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4252 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004253}
4254
Alberto Garciaab5b52282021-07-08 13:47:05 +02004255void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4256{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004257 GLOBAL_STATE_CODE();
Alberto Garciaab5b52282021-07-08 13:47:05 +02004258 if (bs_queue) {
4259 BlockReopenQueueEntry *bs_entry, *next;
4260 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4261 qobject_unref(bs_entry->state.explicit_options);
4262 qobject_unref(bs_entry->state.options);
4263 g_free(bs_entry);
4264 }
4265 g_free(bs_queue);
4266 }
4267}
4268
Jeff Codye971aa12012-09-20 15:13:19 -04004269/*
4270 * Reopen multiple BlockDriverStates atomically & transactionally.
4271 *
4272 * The queue passed in (bs_queue) must have been built up previous
4273 * via bdrv_reopen_queue().
4274 *
4275 * Reopens all BDS specified in the queue, with the appropriate
4276 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004277 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004278 * data cleaned up.
4279 *
4280 * If all devices prepare successfully, then the changes are committed
4281 * to all devices.
4282 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004283 * All affected nodes must be drained between bdrv_reopen_queue() and
4284 * bdrv_reopen_multiple().
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004285 *
4286 * To be called from the main thread, with all other AioContexts unlocked.
Jeff Codye971aa12012-09-20 15:13:19 -04004287 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004288int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004289{
4290 int ret = -1;
4291 BlockReopenQueueEntry *bs_entry, *next;
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004292 AioContext *ctx;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004293 Transaction *tran = tran_new();
4294 g_autoptr(GHashTable) found = NULL;
4295 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004296
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004297 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Jeff Codye971aa12012-09-20 15:13:19 -04004298 assert(bs_queue != NULL);
4299
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004300 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004301 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4302 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004303 ret = bdrv_flush(bs_entry->state.bs);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004304 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004305 if (ret < 0) {
4306 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004307 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004308 }
4309 }
4310
4311 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004312 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004313 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4314 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004315 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004316 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004317 if (ret < 0) {
4318 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004319 }
4320 bs_entry->prepared = true;
4321 }
4322
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004323 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004324 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004325 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004326
4327 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4328 if (state->old_backing_bs) {
4329 refresh_list = bdrv_topological_dfs(refresh_list, found,
4330 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004331 }
Alberto Garciaecd30d22021-06-10 15:05:36 +03004332 if (state->old_file_bs) {
4333 refresh_list = bdrv_topological_dfs(refresh_list, found,
4334 state->old_file_bs);
4335 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004336 }
4337
4338 /*
4339 * Note that file-posix driver rely on permission update done during reopen
4340 * (even if no permission changed), because it wants "new" permissions for
4341 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4342 * in raw_reopen_prepare() which is called with "old" permissions.
4343 */
4344 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4345 if (ret < 0) {
4346 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004347 }
4348
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004349 /*
4350 * If we reach this point, we have success and just need to apply the
4351 * changes.
4352 *
4353 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4354 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4355 * children are usually goes after parents in reopen-queue, so go from last
4356 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004357 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004358 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004359 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4360 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004361 bdrv_reopen_commit(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004362 aio_context_release(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004363 }
4364
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004365 tran_commit(tran);
4366
4367 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4368 BlockDriverState *bs = bs_entry->state.bs;
4369
4370 if (bs->drv->bdrv_reopen_commit_post) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004371 ctx = bdrv_get_aio_context(bs);
4372 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004373 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004374 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004375 }
4376 }
4377
Jeff Codye971aa12012-09-20 15:13:19 -04004378 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004379 goto cleanup;
4380
4381abort:
4382 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004383 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004384 if (bs_entry->prepared) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004385 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4386 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004387 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004388 aio_context_release(ctx);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004389 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004390 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004391
Jeff Codye971aa12012-09-20 15:13:19 -04004392cleanup:
Alberto Garciaab5b52282021-07-08 13:47:05 +02004393 bdrv_reopen_queue_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004394
Jeff Codye971aa12012-09-20 15:13:19 -04004395 return ret;
4396}
4397
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004398int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4399 Error **errp)
4400{
4401 AioContext *ctx = bdrv_get_aio_context(bs);
4402 BlockReopenQueue *queue;
4403 int ret;
4404
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004405 GLOBAL_STATE_CODE();
4406
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004407 bdrv_subtree_drained_begin(bs);
4408 if (ctx != qemu_get_aio_context()) {
4409 aio_context_release(ctx);
4410 }
4411
4412 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4413 ret = bdrv_reopen_multiple(queue, errp);
4414
4415 if (ctx != qemu_get_aio_context()) {
4416 aio_context_acquire(ctx);
4417 }
4418 bdrv_subtree_drained_end(bs);
4419
4420 return ret;
4421}
4422
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004423int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4424 Error **errp)
4425{
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004426 QDict *opts = qdict_new();
4427
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004428 GLOBAL_STATE_CODE();
4429
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004430 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4431
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004432 return bdrv_reopen(bs, opts, true, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004433}
4434
Jeff Codye971aa12012-09-20 15:13:19 -04004435/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004436 * Take a BDRVReopenState and check if the value of 'backing' in the
4437 * reopen_state->options QDict is valid or not.
4438 *
4439 * If 'backing' is missing from the QDict then return 0.
4440 *
4441 * If 'backing' contains the node name of the backing file of
4442 * reopen_state->bs then return 0.
4443 *
4444 * If 'backing' contains a different node name (or is null) then check
4445 * whether the current backing file can be replaced with the new one.
4446 * If that's the case then reopen_state->replace_backing_bs is set to
4447 * true and reopen_state->new_backing_bs contains a pointer to the new
4448 * backing BlockDriverState (or NULL).
4449 *
4450 * Return 0 on success, otherwise return < 0 and set @errp.
4451 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004452static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4453 bool is_backing, Transaction *tran,
4454 Error **errp)
Alberto Garciacb828c32019-03-12 18:48:47 +02004455{
4456 BlockDriverState *bs = reopen_state->bs;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004457 BlockDriverState *new_child_bs;
4458 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4459 child_bs(bs->file);
4460 const char *child_name = is_backing ? "backing" : "file";
Alberto Garciacb828c32019-03-12 18:48:47 +02004461 QObject *value;
4462 const char *str;
4463
Alberto Garciaecd30d22021-06-10 15:05:36 +03004464 value = qdict_get(reopen_state->options, child_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004465 if (value == NULL) {
4466 return 0;
4467 }
4468
4469 switch (qobject_type(value)) {
4470 case QTYPE_QNULL:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004471 assert(is_backing); /* The 'file' option does not allow a null value */
4472 new_child_bs = NULL;
Alberto Garciacb828c32019-03-12 18:48:47 +02004473 break;
4474 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004475 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciaecd30d22021-06-10 15:05:36 +03004476 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4477 if (new_child_bs == NULL) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004478 return -EINVAL;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004479 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4480 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4481 "cycle", str, child_name, bs->node_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004482 return -EINVAL;
4483 }
4484 break;
4485 default:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004486 /*
4487 * The options QDict has been flattened, so 'backing' and 'file'
4488 * do not allow any other data type here.
4489 */
Alberto Garciacb828c32019-03-12 18:48:47 +02004490 g_assert_not_reached();
4491 }
4492
Alberto Garciaecd30d22021-06-10 15:05:36 +03004493 if (old_child_bs == new_child_bs) {
4494 return 0;
4495 }
4496
4497 if (old_child_bs) {
4498 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004499 return 0;
4500 }
4501
Alberto Garciaecd30d22021-06-10 15:05:36 +03004502 if (old_child_bs->implicit) {
4503 error_setg(errp, "Cannot replace implicit %s child of %s",
4504 child_name, bs->node_name);
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004505 return -EPERM;
4506 }
4507 }
4508
Alberto Garciaecd30d22021-06-10 15:05:36 +03004509 if (bs->drv->is_filter && !old_child_bs) {
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004510 /*
4511 * Filters always have a file or a backing child, so we are trying to
4512 * change wrong child
4513 */
4514 error_setg(errp, "'%s' is a %s filter node that does not support a "
Alberto Garciaecd30d22021-06-10 15:05:36 +03004515 "%s child", bs->node_name, bs->drv->format_name, child_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004516 return -EINVAL;
4517 }
4518
Alberto Garciaecd30d22021-06-10 15:05:36 +03004519 if (is_backing) {
4520 reopen_state->old_backing_bs = old_child_bs;
4521 } else {
4522 reopen_state->old_file_bs = old_child_bs;
4523 }
4524
4525 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4526 tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004527}
4528
4529/*
Jeff Codye971aa12012-09-20 15:13:19 -04004530 * Prepares a BlockDriverState for reopen. All changes are staged in the
4531 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4532 * the block driver layer .bdrv_reopen_prepare()
4533 *
4534 * bs is the BlockDriverState to reopen
4535 * flags are the new open flags
4536 * queue is the reopen queue
4537 *
4538 * Returns 0 on success, non-zero on error. On error errp will be set
4539 * as well.
4540 *
4541 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4542 * It is the responsibility of the caller to then call the abort() or
4543 * commit() for any other BDS that have been left in a prepare() state
4544 *
4545 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004546static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004547 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +03004548 Transaction *change_child_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004549{
4550 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004551 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004552 Error *local_err = NULL;
4553 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004554 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004555 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004556 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004557 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004558 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004559
4560 assert(reopen_state != NULL);
4561 assert(reopen_state->bs->drv != NULL);
4562 drv = reopen_state->bs->drv;
4563
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004564 /* This function and each driver's bdrv_reopen_prepare() remove
4565 * entries from reopen_state->options as they are processed, so
4566 * we need to make a copy of the original QDict. */
4567 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4568
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004569 /* Process generic block layer options */
4570 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004571 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004572 ret = -EINVAL;
4573 goto error;
4574 }
4575
Alberto Garciae6d79c42018-11-12 16:00:47 +02004576 /* This was already called in bdrv_reopen_queue_child() so the flags
4577 * are up-to-date. This time we simply want to remove the options from
4578 * QemuOpts in order to indicate that they have been processed. */
4579 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004580 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004581 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004582
Alberto Garcia415bbca2018-10-03 13:23:13 +03004583 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004584 if (discard != NULL) {
4585 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4586 error_setg(errp, "Invalid discard option");
4587 ret = -EINVAL;
4588 goto error;
4589 }
4590 }
4591
Alberto Garcia543770b2018-09-06 12:37:09 +03004592 reopen_state->detect_zeroes =
4593 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4594 if (local_err) {
4595 error_propagate(errp, local_err);
4596 ret = -EINVAL;
4597 goto error;
4598 }
4599
Alberto Garcia57f9db92018-09-06 12:37:06 +03004600 /* All other options (including node-name and driver) must be unchanged.
4601 * Put them back into the QDict, so that they are checked at the end
4602 * of this function. */
4603 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004604
Jeff Cody3d8ce172017-04-07 16:55:30 -04004605 /* If we are to stay read-only, do not allow permission change
4606 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4607 * not set, or if the BDS still has copy_on_read enabled */
4608 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004609 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004610 if (local_err) {
4611 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004612 goto error;
4613 }
4614
Jeff Codye971aa12012-09-20 15:13:19 -04004615 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004616 /*
4617 * If a driver-specific option is missing, it means that we
4618 * should reset it to its default value.
4619 * But not all options allow that, so we need to check it first.
4620 */
4621 ret = bdrv_reset_options_allowed(reopen_state->bs,
4622 reopen_state->options, errp);
4623 if (ret) {
4624 goto error;
4625 }
4626
Jeff Codye971aa12012-09-20 15:13:19 -04004627 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4628 if (ret) {
4629 if (local_err != NULL) {
4630 error_propagate(errp, local_err);
4631 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004632 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004633 error_setg(errp, "failed while preparing to reopen image '%s'",
4634 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004635 }
4636 goto error;
4637 }
4638 } else {
4639 /* It is currently mandatory to have a bdrv_reopen_prepare()
4640 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004641 error_setg(errp, "Block format '%s' used by node '%s' "
4642 "does not support reopening files", drv->format_name,
4643 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004644 ret = -1;
4645 goto error;
4646 }
4647
Max Reitz9ad08c42018-11-16 17:45:24 +01004648 drv_prepared = true;
4649
Alberto Garciabacd9b82019-03-12 18:48:46 +02004650 /*
4651 * We must provide the 'backing' option if the BDS has a backing
4652 * file or if the image file has a backing file name as part of
4653 * its metadata. Otherwise the 'backing' option can be omitted.
4654 */
4655 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004656 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004657 error_setg(errp, "backing is missing for '%s'",
4658 reopen_state->bs->node_name);
4659 ret = -EINVAL;
4660 goto error;
4661 }
4662
Alberto Garciacb828c32019-03-12 18:48:47 +02004663 /*
4664 * Allow changing the 'backing' option. The new value can be
4665 * either a reference to an existing node (using its node name)
4666 * or NULL to simply detach the current backing file.
4667 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004668 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4669 change_child_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004670 if (ret < 0) {
4671 goto error;
4672 }
4673 qdict_del(reopen_state->options, "backing");
4674
Alberto Garciaecd30d22021-06-10 15:05:36 +03004675 /* Allow changing the 'file' option. In this case NULL is not allowed */
4676 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4677 change_child_tran, errp);
4678 if (ret < 0) {
4679 goto error;
4680 }
4681 qdict_del(reopen_state->options, "file");
4682
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004683 /* Options that are not handled are only okay if they are unchanged
4684 * compared to the old state. It is expected that some options are only
4685 * used for the initial open, but not reopen (e.g. filename) */
4686 if (qdict_size(reopen_state->options)) {
4687 const QDictEntry *entry = qdict_first(reopen_state->options);
4688
4689 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004690 QObject *new = entry->value;
4691 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004692
Alberto Garciadb905282018-09-06 12:37:05 +03004693 /* Allow child references (child_name=node_name) as long as they
4694 * point to the current child (i.e. everything stays the same). */
4695 if (qobject_type(new) == QTYPE_QSTRING) {
4696 BdrvChild *child;
4697 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4698 if (!strcmp(child->name, entry->key)) {
4699 break;
4700 }
4701 }
4702
4703 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004704 if (!strcmp(child->bs->node_name,
4705 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004706 continue; /* Found child with this name, skip option */
4707 }
4708 }
4709 }
4710
Max Reitz54fd1b02017-11-14 19:01:26 +01004711 /*
4712 * TODO: When using -drive to specify blockdev options, all values
4713 * will be strings; however, when using -blockdev, blockdev-add or
4714 * filenames using the json:{} pseudo-protocol, they will be
4715 * correctly typed.
4716 * In contrast, reopening options are (currently) always strings
4717 * (because you can only specify them through qemu-io; all other
4718 * callers do not specify any options).
4719 * Therefore, when using anything other than -drive to create a BDS,
4720 * this cannot detect non-string options as unchanged, because
4721 * qobject_is_equal() always returns false for objects of different
4722 * type. In the future, this should be remedied by correctly typing
4723 * all options. For now, this is not too big of an issue because
4724 * the user can simply omit options which cannot be changed anyway,
4725 * so they will stay unchanged.
4726 */
4727 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004728 error_setg(errp, "Cannot change the option '%s'", entry->key);
4729 ret = -EINVAL;
4730 goto error;
4731 }
4732 } while ((entry = qdict_next(reopen_state->options, entry)));
4733 }
4734
Jeff Codye971aa12012-09-20 15:13:19 -04004735 ret = 0;
4736
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004737 /* Restore the original reopen_state->options QDict */
4738 qobject_unref(reopen_state->options);
4739 reopen_state->options = qobject_ref(orig_reopen_opts);
4740
Jeff Codye971aa12012-09-20 15:13:19 -04004741error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004742 if (ret < 0 && drv_prepared) {
4743 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4744 * call drv->bdrv_reopen_abort() before signaling an error
4745 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4746 * when the respective bdrv_reopen_prepare() has failed) */
4747 if (drv->bdrv_reopen_abort) {
4748 drv->bdrv_reopen_abort(reopen_state);
4749 }
4750 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004751 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004752 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004753 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004754 return ret;
4755}
4756
4757/*
4758 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4759 * makes them final by swapping the staging BlockDriverState contents into
4760 * the active BlockDriverState contents.
4761 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004762static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004763{
4764 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004765 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004766 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004767
4768 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004769 bs = reopen_state->bs;
4770 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004771 assert(drv != NULL);
4772
4773 /* If there are any driver level actions to take */
4774 if (drv->bdrv_reopen_commit) {
4775 drv->bdrv_reopen_commit(reopen_state);
4776 }
4777
4778 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004779 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004780 qobject_unref(bs->options);
Alberto Garciaab5b52282021-07-08 13:47:05 +02004781 qobject_ref(reopen_state->explicit_options);
4782 qobject_ref(reopen_state->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004783
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004784 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004785 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004786 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004787 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004788
Alberto Garcia50196d72018-09-06 12:37:03 +03004789 /* Remove child references from bs->options and bs->explicit_options.
4790 * Child options were already removed in bdrv_reopen_queue_child() */
4791 QLIST_FOREACH(child, &bs->children, next) {
4792 qdict_del(bs->explicit_options, child->name);
4793 qdict_del(bs->options, child->name);
4794 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004795 /* backing is probably removed, so it's not handled by previous loop */
4796 qdict_del(bs->explicit_options, "backing");
4797 qdict_del(bs->options, "backing");
4798
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004799 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004800}
4801
4802/*
4803 * Abort the reopen, and delete and free the staged changes in
4804 * reopen_state
4805 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004806static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004807{
4808 BlockDriver *drv;
4809
4810 assert(reopen_state != NULL);
4811 drv = reopen_state->bs->drv;
4812 assert(drv != NULL);
4813
4814 if (drv->bdrv_reopen_abort) {
4815 drv->bdrv_reopen_abort(reopen_state);
4816 }
4817}
4818
4819
Max Reitz64dff522016-01-29 16:36:10 +01004820static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004821{
Max Reitz33384422014-06-20 21:57:33 +02004822 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004823 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004824
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004825 GLOBAL_STATE_CODE();
Max Reitz30f55fb2016-05-17 16:41:32 +02004826 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004827
Paolo Bonzinifc272912015-12-23 11:48:24 +01004828 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004829 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004830 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004831
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004832 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004833 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004834 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004835 bs->drv->bdrv_close(bs);
4836 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004837 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004838 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004839
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004840 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004841 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004842 }
4843
Alberto Garciadd4118c2019-05-13 16:46:17 +03004844 bs->backing = NULL;
4845 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004846 g_free(bs->opaque);
4847 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004848 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004849 bs->backing_file[0] = '\0';
4850 bs->backing_format[0] = '\0';
4851 bs->total_sectors = 0;
4852 bs->encrypted = false;
4853 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004854 qobject_unref(bs->options);
4855 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004856 bs->options = NULL;
4857 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004858 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004859 bs->full_open_options = NULL;
Hanna Reitz0bc329f2021-08-12 10:41:44 +02004860 g_free(bs->block_status_cache);
4861 bs->block_status_cache = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004862
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004863 bdrv_release_named_dirty_bitmaps(bs);
4864 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4865
Max Reitz33384422014-06-20 21:57:33 +02004866 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4867 g_free(ban);
4868 }
4869 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004870 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004871
4872 /*
4873 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4874 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4875 * gets called.
4876 */
4877 if (bs->quiesce_counter) {
4878 bdrv_drain_all_end_quiesce(bs);
4879 }
bellardb3380822004-03-14 21:38:54 +00004880}
4881
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004882void bdrv_close_all(void)
4883{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004884 assert(job_next(NULL) == NULL);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004885 GLOBAL_STATE_CODE();
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004886
Max Reitzca9bd242016-01-29 16:36:14 +01004887 /* Drop references from requests still in flight, such as canceled block
4888 * jobs whose AIO context has not been polled yet */
4889 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004890
Max Reitzca9bd242016-01-29 16:36:14 +01004891 blk_remove_all_bs();
4892 blockdev_close_all_bdrv_states();
4893
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004894 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004895}
4896
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004897static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004898{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004899 GQueue *queue;
4900 GHashTable *found;
4901 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004902
Max Reitzbd86fb92020-05-13 13:05:13 +02004903 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004904 return false;
4905 }
4906
Max Reitzec9f10f2018-06-13 20:18:15 +02004907 /* If the child @c belongs to the BDS @to, replacing the current
4908 * c->bs by @to would mean to create a loop.
4909 *
4910 * Such a case occurs when appending a BDS to a backing chain.
4911 * For instance, imagine the following chain:
4912 *
4913 * guest device -> node A -> further backing chain...
4914 *
4915 * Now we create a new BDS B which we want to put on top of this
4916 * chain, so we first attach A as its backing node:
4917 *
4918 * node B
4919 * |
4920 * v
4921 * guest device -> node A -> further backing chain...
4922 *
4923 * Finally we want to replace A by B. When doing that, we want to
4924 * replace all pointers to A by pointers to B -- except for the
4925 * pointer from B because (1) that would create a loop, and (2)
4926 * that pointer should simply stay intact:
4927 *
4928 * guest device -> node B
4929 * |
4930 * v
4931 * node A -> further backing chain...
4932 *
4933 * In general, when replacing a node A (c->bs) by a node B (@to),
4934 * if A is a child of B, that means we cannot replace A by B there
4935 * because that would create a loop. Silently detaching A from B
4936 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004937 * place there is the most sensible choice.
4938 *
4939 * We would also create a loop in any cases where @c is only
4940 * indirectly referenced by @to. Prevent this by returning false
4941 * if @c is found (by breadth-first search) anywhere in the whole
4942 * subtree of @to.
4943 */
4944
4945 ret = true;
4946 found = g_hash_table_new(NULL, NULL);
4947 g_hash_table_add(found, to);
4948 queue = g_queue_new();
4949 g_queue_push_tail(queue, to);
4950
4951 while (!g_queue_is_empty(queue)) {
4952 BlockDriverState *v = g_queue_pop_head(queue);
4953 BdrvChild *c2;
4954
4955 QLIST_FOREACH(c2, &v->children, next) {
4956 if (c2 == c) {
4957 ret = false;
4958 break;
4959 }
4960
4961 if (g_hash_table_contains(found, c2->bs)) {
4962 continue;
4963 }
4964
4965 g_queue_push_tail(queue, c2->bs);
4966 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004967 }
4968 }
4969
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004970 g_queue_free(queue);
4971 g_hash_table_destroy(found);
4972
4973 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004974}
4975
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004976typedef struct BdrvRemoveFilterOrCowChild {
4977 BdrvChild *child;
Hanna Reitz82b54cf2021-11-15 15:54:04 +01004978 BlockDriverState *bs;
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004979 bool is_backing;
4980} BdrvRemoveFilterOrCowChild;
4981
4982static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
4983{
4984 BdrvRemoveFilterOrCowChild *s = opaque;
4985 BlockDriverState *parent_bs = s->child->opaque;
4986
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004987 if (s->is_backing) {
4988 parent_bs->backing = s->child;
4989 } else {
4990 parent_bs->file = s->child;
4991 }
4992
4993 /*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004994 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004995 * because that function is transactionable and it registered own completion
4996 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
4997 * called automatically.
4998 */
4999}
5000
5001static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
5002{
5003 BdrvRemoveFilterOrCowChild *s = opaque;
5004
5005 bdrv_child_free(s->child);
5006}
5007
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005008static void bdrv_remove_filter_or_cow_child_clean(void *opaque)
5009{
5010 BdrvRemoveFilterOrCowChild *s = opaque;
5011
5012 /* Drop the bs reference after the transaction is done */
5013 bdrv_unref(s->bs);
5014 g_free(s);
5015}
5016
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005017static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
5018 .abort = bdrv_remove_filter_or_cow_child_abort,
5019 .commit = bdrv_remove_filter_or_cow_child_commit,
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005020 .clean = bdrv_remove_filter_or_cow_child_clean,
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005021};
5022
5023/*
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005024 * A function to remove backing or file child of @bs.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03005025 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005026 */
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005027static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
5028 BdrvChild *child,
5029 Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005030{
Hanna Reitz562bda82021-11-15 15:54:02 +01005031 BdrvChild **childp;
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005032 BdrvRemoveFilterOrCowChild *s;
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005033
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005034 if (!child) {
5035 return;
5036 }
5037
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005038 /*
5039 * Keep a reference to @bs so @childp will stay valid throughout the
5040 * transaction (required by bdrv_replace_child_tran())
5041 */
5042 bdrv_ref(bs);
Hanna Reitz562bda82021-11-15 15:54:02 +01005043 if (child == bs->backing) {
5044 childp = &bs->backing;
5045 } else if (child == bs->file) {
5046 childp = &bs->file;
5047 } else {
5048 g_assert_not_reached();
5049 }
5050
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005051 if (child->bs) {
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005052 /*
5053 * Pass free_empty_child=false, we will free the child in
5054 * bdrv_remove_filter_or_cow_child_commit()
5055 */
5056 bdrv_replace_child_tran(childp, NULL, tran, false);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005057 }
5058
5059 s = g_new(BdrvRemoveFilterOrCowChild, 1);
5060 *s = (BdrvRemoveFilterOrCowChild) {
5061 .child = child,
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005062 .bs = bs,
Hanna Reitz562bda82021-11-15 15:54:02 +01005063 .is_backing = (childp == &bs->backing),
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005064 };
5065 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005066}
5067
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005068/*
5069 * A function to remove backing-chain child of @bs if exists: cow child for
5070 * format nodes (always .backing) and filter child for filters (may be .file or
5071 * .backing)
5072 */
5073static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
5074 Transaction *tran)
5075{
5076 bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
5077}
5078
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005079static int bdrv_replace_node_noperm(BlockDriverState *from,
5080 BlockDriverState *to,
5081 bool auto_skip, Transaction *tran,
5082 Error **errp)
5083{
5084 BdrvChild *c, *next;
5085
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005086 assert(to != NULL);
5087
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005088 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5089 assert(c->bs == from);
5090 if (!should_update_child(c, to)) {
5091 if (auto_skip) {
5092 continue;
5093 }
5094 error_setg(errp, "Should not change '%s' link to '%s'",
5095 c->name, from->node_name);
5096 return -EINVAL;
5097 }
5098 if (c->frozen) {
5099 error_setg(errp, "Cannot change '%s' link to '%s'",
5100 c->name, from->node_name);
5101 return -EPERM;
5102 }
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005103
5104 /*
5105 * Passing a pointer to the local variable @c is fine here, because
5106 * @to is not NULL, and so &c will not be attached to the transaction.
5107 */
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005108 bdrv_replace_child_tran(&c, to, tran, true);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005109 }
5110
5111 return 0;
5112}
5113
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005114/*
5115 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5116 * if it creates a parent-child relation loop or if parent is block-job.
5117 *
5118 * With auto_skip=false the error is returned if from has a parent which should
5119 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005120 *
5121 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5122 * case backing link of the cow-parent of @to is removed.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005123 *
5124 * @to must not be NULL.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005125 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005126static int bdrv_replace_node_common(BlockDriverState *from,
5127 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005128 bool auto_skip, bool detach_subchain,
5129 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005130{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005131 Transaction *tran = tran_new();
5132 g_autoptr(GHashTable) found = NULL;
5133 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04005134 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005135 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005136
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005137 assert(to != NULL);
5138
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005139 if (detach_subchain) {
5140 assert(bdrv_chain_contains(from, to));
5141 assert(from != to);
5142 for (to_cow_parent = from;
5143 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5144 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5145 {
5146 ;
5147 }
5148 }
5149
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005150 /* Make sure that @from doesn't go away until we have successfully attached
5151 * all of its parents to @to. */
5152 bdrv_ref(from);
5153
Kevin Wolff871abd2019-05-21 19:00:25 +02005154 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01005155 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02005156 bdrv_drained_begin(from);
5157
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005158 /*
5159 * Do the replacement without permission update.
5160 * Replacement may influence the permissions, we should calculate new
5161 * permissions based on new graph. If we fail, we'll roll-back the
5162 * replacement.
5163 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005164 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5165 if (ret < 0) {
5166 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005167 }
5168
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005169 if (detach_subchain) {
5170 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
5171 }
5172
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005173 found = g_hash_table_new(NULL, NULL);
5174
5175 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5176 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5177
5178 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005179 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005180 goto out;
5181 }
5182
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005183 ret = 0;
5184
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005185out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005186 tran_finalize(tran, ret);
5187
Kevin Wolff871abd2019-05-21 19:00:25 +02005188 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005189 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005190
5191 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005192}
5193
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005194/**
5195 * Replace node @from by @to (where neither may be NULL).
5196 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005197int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5198 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005199{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005200 GLOBAL_STATE_CODE();
5201
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005202 return bdrv_replace_node_common(from, to, true, false, errp);
5203}
5204
5205int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5206{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005207 GLOBAL_STATE_CODE();
5208
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005209 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5210 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005211}
5212
Jeff Cody8802d1f2012-02-28 15:54:06 -05005213/*
5214 * Add new bs contents at the top of an image chain while the chain is
5215 * live, while keeping required fields on the top layer.
5216 *
5217 * This will modify the BlockDriverState fields, and swap contents
5218 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5219 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005220 * bs_new must not be attached to a BlockBackend and must not have backing
5221 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005222 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005223 * This function does not create any image files.
5224 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005225int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5226 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005227{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005228 int ret;
5229 Transaction *tran = tran_new();
5230
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005231 GLOBAL_STATE_CODE();
5232
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005233 assert(!bs_new->backing);
5234
5235 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5236 &child_of_bds, bdrv_backing_role(bs_new),
5237 &bs_new->backing, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005238 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005239 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005240 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005241
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005242 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005243 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005244 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005245 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005246
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005247 ret = bdrv_refresh_perms(bs_new, errp);
5248out:
5249 tran_finalize(tran, ret);
5250
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005251 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005252
5253 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005254}
5255
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005256/* Not for empty child */
5257int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5258 Error **errp)
5259{
5260 int ret;
5261 Transaction *tran = tran_new();
5262 g_autoptr(GHashTable) found = NULL;
5263 g_autoptr(GSList) refresh_list = NULL;
5264 BlockDriverState *old_bs = child->bs;
5265
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005266 GLOBAL_STATE_CODE();
5267
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005268 bdrv_ref(old_bs);
5269 bdrv_drained_begin(old_bs);
5270 bdrv_drained_begin(new_bs);
5271
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005272 bdrv_replace_child_tran(&child, new_bs, tran, true);
5273 /* @new_bs must have been non-NULL, so @child must not have been freed */
5274 assert(child != NULL);
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005275
5276 found = g_hash_table_new(NULL, NULL);
5277 refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5278 refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5279
5280 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5281
5282 tran_finalize(tran, ret);
5283
5284 bdrv_drained_end(old_bs);
5285 bdrv_drained_end(new_bs);
5286 bdrv_unref(old_bs);
5287
5288 return ret;
5289}
5290
Fam Zheng4f6fd342013-08-23 09:14:47 +08005291static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005292{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005293 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005294 assert(!bs->refcnt);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005295 GLOBAL_STATE_CODE();
Markus Armbruster18846de2010-06-29 16:58:30 +02005296
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005297 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005298 if (bs->node_name[0] != '\0') {
5299 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5300 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005301 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5302
Anton Kuchin30c321f2019-05-07 11:12:56 +03005303 bdrv_close(bs);
5304
Anthony Liguori7267c092011-08-20 22:09:37 -05005305 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005306}
5307
Vladimir Sementsov-Ogievskiy96796fa2021-09-20 14:55:36 +03005308
5309/*
5310 * Replace @bs by newly created block node.
5311 *
5312 * @options is a QDict of options to pass to the block drivers, or NULL for an
5313 * empty set of options. The reference to the QDict belongs to the block layer
5314 * after the call (even on failure), so if the caller intends to reuse the
5315 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5316 */
5317BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005318 int flags, Error **errp)
5319{
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005320 ERRP_GUARD();
5321 int ret;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005322 BlockDriverState *new_node_bs = NULL;
5323 const char *drvname, *node_name;
5324 BlockDriver *drv;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005325
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005326 drvname = qdict_get_try_str(options, "driver");
5327 if (!drvname) {
5328 error_setg(errp, "driver is not specified");
5329 goto fail;
5330 }
5331
5332 drv = bdrv_find_format(drvname);
5333 if (!drv) {
5334 error_setg(errp, "Unknown driver: '%s'", drvname);
5335 goto fail;
5336 }
5337
5338 node_name = qdict_get_try_str(options, "node-name");
5339
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005340 GLOBAL_STATE_CODE();
5341
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005342 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5343 errp);
5344 options = NULL; /* bdrv_new_open_driver() eats options */
5345 if (!new_node_bs) {
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005346 error_prepend(errp, "Could not create node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005347 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005348 }
5349
5350 bdrv_drained_begin(bs);
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005351 ret = bdrv_replace_node(bs, new_node_bs, errp);
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005352 bdrv_drained_end(bs);
5353
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005354 if (ret < 0) {
5355 error_prepend(errp, "Could not replace node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005356 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005357 }
5358
5359 return new_node_bs;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005360
5361fail:
5362 qobject_unref(options);
5363 bdrv_unref(new_node_bs);
5364 return NULL;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005365}
5366
aliguorie97fc192009-04-21 23:11:50 +00005367/*
5368 * Run consistency checks on an image
5369 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005370 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005371 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005372 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005373 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005374int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5375 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005376{
Max Reitz908bcd52014-08-07 22:47:55 +02005377 if (bs->drv == NULL) {
5378 return -ENOMEDIUM;
5379 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005380 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005381 return -ENOTSUP;
5382 }
5383
Kevin Wolfe076f332010-06-29 11:43:13 +02005384 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005385 return bs->drv->bdrv_co_check(bs, res, fix);
5386}
5387
Kevin Wolf756e6732010-01-12 12:55:17 +01005388/*
5389 * Return values:
5390 * 0 - success
5391 * -EINVAL - backing format specified, but no file
5392 * -ENOSPC - can't update the backing file because no space is left in the
5393 * image file header
5394 * -ENOTSUP - format driver doesn't support changing the backing file
5395 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005396int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
Eric Blake497a30d2021-05-03 14:36:00 -07005397 const char *backing_fmt, bool require)
Kevin Wolf756e6732010-01-12 12:55:17 +01005398{
5399 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005400 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005401
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005402 GLOBAL_STATE_CODE();
5403
Max Reitzd470ad42017-11-10 21:31:09 +01005404 if (!drv) {
5405 return -ENOMEDIUM;
5406 }
5407
Paolo Bonzini5f377792012-04-12 14:01:01 +02005408 /* Backing file format doesn't make sense without a backing file */
5409 if (backing_fmt && !backing_file) {
5410 return -EINVAL;
5411 }
5412
Eric Blake497a30d2021-05-03 14:36:00 -07005413 if (require && backing_file && !backing_fmt) {
5414 return -EINVAL;
Eric Blakee54ee1b2020-07-06 15:39:53 -05005415 }
5416
Kevin Wolf756e6732010-01-12 12:55:17 +01005417 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005418 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005419 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005420 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005421 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005422
5423 if (ret == 0) {
5424 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5425 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005426 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5427 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005428 }
5429 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005430}
5431
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005432/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005433 * Finds the first non-filter node above bs in the chain between
5434 * active and bs. The returned node is either an immediate parent of
5435 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005436 *
5437 * Returns NULL if bs is not found in active's image chain,
5438 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005439 *
5440 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005441 */
5442BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5443 BlockDriverState *bs)
5444{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005445
5446 GLOBAL_STATE_CODE();
5447
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005448 bs = bdrv_skip_filters(bs);
5449 active = bdrv_skip_filters(active);
5450
5451 while (active) {
5452 BlockDriverState *next = bdrv_backing_chain_next(active);
5453 if (bs == next) {
5454 return active;
5455 }
5456 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005457 }
5458
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005459 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005460}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005461
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005462/* Given a BDS, searches for the base layer. */
5463BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5464{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005465 GLOBAL_STATE_CODE();
5466
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005467 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005468}
5469
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005470/*
Max Reitz7b99a262019-06-12 16:07:11 +02005471 * Return true if at least one of the COW (backing) and filter links
5472 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005473 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005474 */
5475bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5476 Error **errp)
5477{
5478 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005479 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005480
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005481 GLOBAL_STATE_CODE();
5482
Max Reitz7b99a262019-06-12 16:07:11 +02005483 for (i = bs; i != base; i = child_bs(child)) {
5484 child = bdrv_filter_or_cow_child(i);
5485
5486 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005487 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005488 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005489 return true;
5490 }
5491 }
5492
5493 return false;
5494}
5495
5496/*
Max Reitz7b99a262019-06-12 16:07:11 +02005497 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005498 * If any of the links is already frozen the operation is aborted and
5499 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005500 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005501 * Returns 0 on success. On failure returns < 0 and sets @errp.
5502 */
5503int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5504 Error **errp)
5505{
5506 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005507 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005508
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005509 GLOBAL_STATE_CODE();
5510
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005511 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5512 return -EPERM;
5513 }
5514
Max Reitz7b99a262019-06-12 16:07:11 +02005515 for (i = bs; i != base; i = child_bs(child)) {
5516 child = bdrv_filter_or_cow_child(i);
5517 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005518 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005519 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005520 return -EPERM;
5521 }
5522 }
5523
Max Reitz7b99a262019-06-12 16:07:11 +02005524 for (i = bs; i != base; i = child_bs(child)) {
5525 child = bdrv_filter_or_cow_child(i);
5526 if (child) {
5527 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005528 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005529 }
5530
5531 return 0;
5532}
5533
5534/*
Max Reitz7b99a262019-06-12 16:07:11 +02005535 * Unfreeze all COW (backing) and filter links between @bs and @base.
5536 * The caller must ensure that all links are frozen before using this
5537 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005538 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005539 */
5540void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5541{
5542 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005543 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005544
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005545 GLOBAL_STATE_CODE();
5546
Max Reitz7b99a262019-06-12 16:07:11 +02005547 for (i = bs; i != base; i = child_bs(child)) {
5548 child = bdrv_filter_or_cow_child(i);
5549 if (child) {
5550 assert(child->frozen);
5551 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005552 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005553 }
5554}
5555
5556/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005557 * Drops images above 'base' up to and including 'top', and sets the image
5558 * above 'top' to have base as its backing file.
5559 *
5560 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5561 * information in 'bs' can be properly updated.
5562 *
5563 * E.g., this will convert the following chain:
5564 * bottom <- base <- intermediate <- top <- active
5565 *
5566 * to
5567 *
5568 * bottom <- base <- active
5569 *
5570 * It is allowed for bottom==base, in which case it converts:
5571 *
5572 * base <- intermediate <- top <- active
5573 *
5574 * to
5575 *
5576 * base <- active
5577 *
Jeff Cody54e26902014-06-25 15:40:10 -04005578 * If backing_file_str is non-NULL, it will be used when modifying top's
5579 * overlay image metadata.
5580 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005581 * Error conditions:
5582 * if active == top, that is considered an error
5583 *
5584 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005585int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5586 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005587{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005588 BlockDriverState *explicit_top = top;
5589 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005590 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005591 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005592 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005593 g_autoptr(GSList) updated_children = NULL;
5594 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005595
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005596 GLOBAL_STATE_CODE();
5597
Kevin Wolf6858eba2017-06-29 19:32:21 +02005598 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005599 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005600
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005601 if (!top->drv || !base->drv) {
5602 goto exit;
5603 }
5604
Kevin Wolf5db15a52015-09-14 15:33:33 +02005605 /* Make sure that base is in the backing chain of top */
5606 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005607 goto exit;
5608 }
5609
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005610 /* If 'base' recursively inherits from 'top' then we should set
5611 * base->inherits_from to top->inherits_from after 'top' and all
5612 * other intermediate nodes have been dropped.
5613 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5614 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005615 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005616 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5617
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005618 /* success - we can delete the intermediate states, and link top->base */
Max Reitzf30c66b2019-02-01 20:29:05 +01005619 if (!backing_file_str) {
5620 bdrv_refresh_filename(base);
5621 backing_file_str = base->filename;
5622 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005623
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005624 QLIST_FOREACH(c, &top->parents, next_parent) {
5625 updated_children = g_slist_prepend(updated_children, c);
5626 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005627
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005628 /*
5629 * It seems correct to pass detach_subchain=true here, but it triggers
5630 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5631 * another drained section, which modify the graph (for example, removing
5632 * the child, which we keep in updated_children list). So, it's a TODO.
5633 *
5634 * Note, bug triggered if pass detach_subchain=true here and run
5635 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5636 * That's a FIXME.
5637 */
5638 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005639 if (local_err) {
5640 error_report_err(local_err);
5641 goto exit;
5642 }
5643
5644 for (p = updated_children; p; p = p->next) {
5645 c = p->data;
5646
Max Reitzbd86fb92020-05-13 13:05:13 +02005647 if (c->klass->update_filename) {
5648 ret = c->klass->update_filename(c, base, backing_file_str,
5649 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005650 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005651 /*
5652 * TODO: Actually, we want to rollback all previous iterations
5653 * of this loop, and (which is almost impossible) previous
5654 * bdrv_replace_node()...
5655 *
5656 * Note, that c->klass->update_filename may lead to permission
5657 * update, so it's a bad idea to call it inside permission
5658 * update transaction of bdrv_replace_node.
5659 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005660 error_report_err(local_err);
5661 goto exit;
5662 }
5663 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005664 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005665
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005666 if (update_inherits_from) {
5667 base->inherits_from = explicit_top->inherits_from;
5668 }
5669
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005670 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005671exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005672 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005673 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005674 return ret;
5675}
5676
bellard83f64092006-08-01 16:21:11 +00005677/**
Max Reitz081e4652019-06-12 18:14:13 +02005678 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5679 * sums the size of all data-bearing children. (This excludes backing
5680 * children.)
5681 */
5682static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5683{
5684 BdrvChild *child;
5685 int64_t child_size, sum = 0;
5686
5687 QLIST_FOREACH(child, &bs->children, next) {
5688 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5689 BDRV_CHILD_FILTERED))
5690 {
5691 child_size = bdrv_get_allocated_file_size(child->bs);
5692 if (child_size < 0) {
5693 return child_size;
5694 }
5695 sum += child_size;
5696 }
5697 }
5698
5699 return sum;
5700}
5701
5702/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005703 * Length of a allocated file in bytes. Sparse files are counted by actual
5704 * allocated space. Return < 0 if error or unknown.
5705 */
5706int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5707{
5708 BlockDriver *drv = bs->drv;
5709 if (!drv) {
5710 return -ENOMEDIUM;
5711 }
5712 if (drv->bdrv_get_allocated_file_size) {
5713 return drv->bdrv_get_allocated_file_size(bs);
5714 }
Max Reitz081e4652019-06-12 18:14:13 +02005715
5716 if (drv->bdrv_file_open) {
5717 /*
5718 * Protocol drivers default to -ENOTSUP (most of their data is
5719 * not stored in any of their children (if they even have any),
5720 * so there is no generic way to figure it out).
5721 */
5722 return -ENOTSUP;
5723 } else if (drv->is_filter) {
5724 /* Filter drivers default to the size of their filtered child */
5725 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5726 } else {
5727 /* Other drivers default to summing their children's sizes */
5728 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005729 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005730}
5731
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005732/*
5733 * bdrv_measure:
5734 * @drv: Format driver
5735 * @opts: Creation options for new image
5736 * @in_bs: Existing image containing data for new image (may be NULL)
5737 * @errp: Error object
5738 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5739 * or NULL on error
5740 *
5741 * Calculate file size required to create a new image.
5742 *
5743 * If @in_bs is given then space for allocated clusters and zero clusters
5744 * from that image are included in the calculation. If @opts contains a
5745 * backing file that is shared by @in_bs then backing clusters may be omitted
5746 * from the calculation.
5747 *
5748 * If @in_bs is NULL then the calculation includes no allocated clusters
5749 * unless a preallocation option is given in @opts.
5750 *
5751 * Note that @in_bs may use a different BlockDriver from @drv.
5752 *
5753 * If an error occurs the @errp pointer is set.
5754 */
5755BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5756 BlockDriverState *in_bs, Error **errp)
5757{
5758 if (!drv->bdrv_measure) {
5759 error_setg(errp, "Block driver '%s' does not support size measurement",
5760 drv->format_name);
5761 return NULL;
5762 }
5763
5764 return drv->bdrv_measure(opts, in_bs, errp);
5765}
5766
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005767/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005768 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005769 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005770int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005771{
5772 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005773
bellard83f64092006-08-01 16:21:11 +00005774 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005775 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005776
Kevin Wolfb94a2612013-10-29 12:18:58 +01005777 if (drv->has_variable_length) {
5778 int ret = refresh_total_sectors(bs, bs->total_sectors);
5779 if (ret < 0) {
5780 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005781 }
bellard83f64092006-08-01 16:21:11 +00005782 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005783 return bs->total_sectors;
5784}
5785
5786/**
5787 * Return length in bytes on success, -errno on error.
5788 * The length is always a multiple of BDRV_SECTOR_SIZE.
5789 */
5790int64_t bdrv_getlength(BlockDriverState *bs)
5791{
5792 int64_t ret = bdrv_nb_sectors(bs);
5793
Eric Blake122860b2020-11-05 09:51:22 -06005794 if (ret < 0) {
5795 return ret;
5796 }
5797 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5798 return -EFBIG;
5799 }
5800 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005801}
5802
bellard19cb3732006-08-19 11:45:59 +00005803/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005804void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005805{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005806 int64_t nb_sectors = bdrv_nb_sectors(bs);
5807
5808 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005809}
bellardcf989512004-02-16 21:56:36 +00005810
Eric Blake54115412016-06-23 16:37:26 -06005811bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005812{
5813 return bs->sg;
5814}
5815
Max Reitzae23f782019-06-12 22:57:15 +02005816/**
5817 * Return whether the given node supports compressed writes.
5818 */
5819bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5820{
5821 BlockDriverState *filtered;
5822
5823 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5824 return false;
5825 }
5826
5827 filtered = bdrv_filter_bs(bs);
5828 if (filtered) {
5829 /*
5830 * Filters can only forward compressed writes, so we have to
5831 * check the child.
5832 */
5833 return bdrv_supports_compressed_writes(filtered);
5834 }
5835
5836 return true;
5837}
5838
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005839const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005840{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005841 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005842}
5843
Stefan Hajnocziada42402014-08-27 12:08:55 +01005844static int qsort_strcmp(const void *a, const void *b)
5845{
Max Reitzceff5bd2016-10-12 22:49:05 +02005846 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005847}
5848
ths5fafdf22007-09-16 21:08:06 +00005849void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005850 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005851{
5852 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005853 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005854 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005855 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005856
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005857 GLOBAL_STATE_CODE();
5858
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005859 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005860 if (drv->format_name) {
5861 bool found = false;
5862 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005863
5864 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5865 continue;
5866 }
5867
Jeff Codye855e4f2014-04-28 18:29:54 -04005868 while (formats && i && !found) {
5869 found = !strcmp(formats[--i], drv->format_name);
5870 }
5871
5872 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005873 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005874 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005875 }
5876 }
bellardea2384d2004-08-01 21:59:26 +00005877 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005878
Max Reitzeb0df692016-10-12 22:49:06 +02005879 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5880 const char *format_name = block_driver_modules[i].format_name;
5881
5882 if (format_name) {
5883 bool found = false;
5884 int j = count;
5885
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005886 if (use_bdrv_whitelist &&
5887 !bdrv_format_is_whitelisted(format_name, read_only)) {
5888 continue;
5889 }
5890
Max Reitzeb0df692016-10-12 22:49:06 +02005891 while (formats && j && !found) {
5892 found = !strcmp(formats[--j], format_name);
5893 }
5894
5895 if (!found) {
5896 formats = g_renew(const char *, formats, count + 1);
5897 formats[count++] = format_name;
5898 }
5899 }
5900 }
5901
Stefan Hajnocziada42402014-08-27 12:08:55 +01005902 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5903
5904 for (i = 0; i < count; i++) {
5905 it(opaque, formats[i]);
5906 }
5907
Jeff Codye855e4f2014-04-28 18:29:54 -04005908 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005909}
5910
Benoît Canetdc364f42014-01-23 21:31:32 +01005911/* This function is to find a node in the bs graph */
5912BlockDriverState *bdrv_find_node(const char *node_name)
5913{
5914 BlockDriverState *bs;
5915
5916 assert(node_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005917 GLOBAL_STATE_CODE();
Benoît Canetdc364f42014-01-23 21:31:32 +01005918
5919 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5920 if (!strcmp(node_name, bs->node_name)) {
5921 return bs;
5922 }
5923 }
5924 return NULL;
5925}
5926
Benoît Canetc13163f2014-01-23 21:31:34 +01005927/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005928BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5929 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005930{
Eric Blake9812e712020-10-27 00:05:47 -05005931 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005932 BlockDriverState *bs;
5933
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005934 GLOBAL_STATE_CODE();
5935
Benoît Canetc13163f2014-01-23 21:31:34 +01005936 list = NULL;
5937 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005938 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005939 if (!info) {
5940 qapi_free_BlockDeviceInfoList(list);
5941 return NULL;
5942 }
Eric Blake9812e712020-10-27 00:05:47 -05005943 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005944 }
5945
5946 return list;
5947}
5948
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005949typedef struct XDbgBlockGraphConstructor {
5950 XDbgBlockGraph *graph;
5951 GHashTable *graph_nodes;
5952} XDbgBlockGraphConstructor;
5953
5954static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5955{
5956 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5957
5958 gr->graph = g_new0(XDbgBlockGraph, 1);
5959 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5960
5961 return gr;
5962}
5963
5964static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5965{
5966 XDbgBlockGraph *graph = gr->graph;
5967
5968 g_hash_table_destroy(gr->graph_nodes);
5969 g_free(gr);
5970
5971 return graph;
5972}
5973
5974static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5975{
5976 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5977
5978 if (ret != 0) {
5979 return ret;
5980 }
5981
5982 /*
5983 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5984 * answer of g_hash_table_lookup.
5985 */
5986 ret = g_hash_table_size(gr->graph_nodes) + 1;
5987 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5988
5989 return ret;
5990}
5991
5992static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5993 XDbgBlockGraphNodeType type, const char *name)
5994{
5995 XDbgBlockGraphNode *n;
5996
5997 n = g_new0(XDbgBlockGraphNode, 1);
5998
5999 n->id = xdbg_graph_node_num(gr, node);
6000 n->type = type;
6001 n->name = g_strdup(name);
6002
Eric Blake9812e712020-10-27 00:05:47 -05006003 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006004}
6005
6006static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6007 const BdrvChild *child)
6008{
Max Reitzcdb1cec2019-11-08 13:34:52 +01006009 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006010 XDbgBlockGraphEdge *edge;
6011
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006012 edge = g_new0(XDbgBlockGraphEdge, 1);
6013
6014 edge->parent = xdbg_graph_node_num(gr, parent);
6015 edge->child = xdbg_graph_node_num(gr, child->bs);
6016 edge->name = g_strdup(child->name);
6017
Max Reitzcdb1cec2019-11-08 13:34:52 +01006018 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6019 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6020
6021 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006022 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006023 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01006024 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006025 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006026 }
6027 }
6028
Eric Blake9812e712020-10-27 00:05:47 -05006029 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006030}
6031
6032
6033XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6034{
6035 BlockBackend *blk;
6036 BlockJob *job;
6037 BlockDriverState *bs;
6038 BdrvChild *child;
6039 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6040
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006041 GLOBAL_STATE_CODE();
6042
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006043 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6044 char *allocated_name = NULL;
6045 const char *name = blk_name(blk);
6046
6047 if (!*name) {
6048 name = allocated_name = blk_get_attached_dev_id(blk);
6049 }
6050 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6051 name);
6052 g_free(allocated_name);
6053 if (blk_root(blk)) {
6054 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6055 }
6056 }
6057
6058 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
6059 GSList *el;
6060
6061 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6062 job->job.id);
6063 for (el = job->nodes; el; el = el->next) {
6064 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6065 }
6066 }
6067
6068 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6069 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6070 bs->node_name);
6071 QLIST_FOREACH(child, &bs->children, next) {
6072 xdbg_graph_add_edge(gr, bs, child);
6073 }
6074 }
6075
6076 return xdbg_graph_finalize(gr);
6077}
6078
Benoît Canet12d3ba82014-01-23 21:31:35 +01006079BlockDriverState *bdrv_lookup_bs(const char *device,
6080 const char *node_name,
6081 Error **errp)
6082{
Markus Armbruster7f06d472014-10-07 13:59:12 +02006083 BlockBackend *blk;
6084 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006085
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006086 GLOBAL_STATE_CODE();
6087
Benoît Canet12d3ba82014-01-23 21:31:35 +01006088 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02006089 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006090
Markus Armbruster7f06d472014-10-07 13:59:12 +02006091 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006092 bs = blk_bs(blk);
6093 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02006094 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02006095 }
6096
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006097 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006098 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006099 }
6100
Benoît Canetdd67fa52014-02-12 17:15:06 +01006101 if (node_name) {
6102 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006103
Benoît Canetdd67fa52014-02-12 17:15:06 +01006104 if (bs) {
6105 return bs;
6106 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006107 }
6108
Connor Kuehl785ec4b2021-03-05 09:19:28 -06006109 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01006110 device ? device : "",
6111 node_name ? node_name : "");
6112 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006113}
6114
Jeff Cody5a6684d2014-06-25 15:40:09 -04006115/* If 'base' is in the same chain as 'top', return true. Otherwise,
6116 * return false. If either argument is NULL, return false. */
6117bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6118{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006119
6120 GLOBAL_STATE_CODE();
6121
Jeff Cody5a6684d2014-06-25 15:40:09 -04006122 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006123 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04006124 }
6125
6126 return top != NULL;
6127}
6128
Fam Zheng04df7652014-10-31 11:32:54 +08006129BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6130{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006131 GLOBAL_STATE_CODE();
Fam Zheng04df7652014-10-31 11:32:54 +08006132 if (!bs) {
6133 return QTAILQ_FIRST(&graph_bdrv_states);
6134 }
6135 return QTAILQ_NEXT(bs, node_list);
6136}
6137
Kevin Wolf0f122642018-03-28 18:29:18 +02006138BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6139{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006140 GLOBAL_STATE_CODE();
Kevin Wolf0f122642018-03-28 18:29:18 +02006141 if (!bs) {
6142 return QTAILQ_FIRST(&all_bdrv_states);
6143 }
6144 return QTAILQ_NEXT(bs, bs_list);
6145}
6146
Fam Zheng20a9e772014-10-31 11:32:55 +08006147const char *bdrv_get_node_name(const BlockDriverState *bs)
6148{
6149 return bs->node_name;
6150}
6151
Kevin Wolf1f0c4612016-03-22 18:38:44 +01006152const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006153{
6154 BdrvChild *c;
6155 const char *name;
6156
6157 /* If multiple parents have a name, just pick the first one. */
6158 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006159 if (c->klass->get_name) {
6160 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006161 if (name && *name) {
6162 return name;
6163 }
6164 }
6165 }
6166
6167 return NULL;
6168}
6169
Markus Armbruster7f06d472014-10-07 13:59:12 +02006170/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02006171const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00006172{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006173 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00006174}
6175
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006176/* This can be used to identify nodes that might not have a device
6177 * name associated. Since node and device names live in the same
6178 * namespace, the result is unambiguous. The exception is if both are
6179 * absent, then this returns an empty (non-null) string. */
6180const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6181{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006182 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006183}
6184
Markus Armbrusterc8433282012-06-05 16:49:24 +02006185int bdrv_get_flags(BlockDriverState *bs)
6186{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006187 GLOBAL_STATE_CODE();
Markus Armbrusterc8433282012-06-05 16:49:24 +02006188 return bs->open_flags;
6189}
6190
Peter Lieven3ac21622013-06-28 12:47:42 +02006191int bdrv_has_zero_init_1(BlockDriverState *bs)
6192{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006193 GLOBAL_STATE_CODE();
Peter Lieven3ac21622013-06-28 12:47:42 +02006194 return 1;
6195}
6196
Kevin Wolff2feebb2010-04-14 17:30:35 +02006197int bdrv_has_zero_init(BlockDriverState *bs)
6198{
Max Reitz93393e62019-06-12 17:03:38 +02006199 BlockDriverState *filtered;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006200 GLOBAL_STATE_CODE();
Max Reitz93393e62019-06-12 17:03:38 +02006201
Max Reitzd470ad42017-11-10 21:31:09 +01006202 if (!bs->drv) {
6203 return 0;
6204 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006205
Paolo Bonzini11212d82013-09-04 19:00:27 +02006206 /* If BS is a copy on write image, it is initialized to
6207 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02006208 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02006209 return 0;
6210 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02006211 if (bs->drv->bdrv_has_zero_init) {
6212 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02006213 }
Max Reitz93393e62019-06-12 17:03:38 +02006214
6215 filtered = bdrv_filter_bs(bs);
6216 if (filtered) {
6217 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006218 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006219
Peter Lieven3ac21622013-06-28 12:47:42 +02006220 /* safe default */
6221 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02006222}
6223
Peter Lieven4ce78692013-10-24 12:06:54 +02006224bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6225{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03006226 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02006227 return false;
6228 }
6229
Eric Blakee24d8132018-01-26 13:34:39 -06006230 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02006231}
6232
ths5fafdf22007-09-16 21:08:06 +00006233void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00006234 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00006235{
Kevin Wolf3574c602011-10-26 11:02:11 +02006236 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00006237}
6238
bellardfaea38e2006-08-05 21:31:00 +00006239int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6240{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006241 int ret;
bellardfaea38e2006-08-05 21:31:00 +00006242 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006243 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6244 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00006245 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006246 }
6247 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02006248 BlockDriverState *filtered = bdrv_filter_bs(bs);
6249 if (filtered) {
6250 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006251 }
bellardfaea38e2006-08-05 21:31:00 +00006252 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006253 }
bellardfaea38e2006-08-05 21:31:00 +00006254 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006255 ret = drv->bdrv_get_info(bs, bdi);
6256 if (ret < 0) {
6257 return ret;
6258 }
6259
6260 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6261 return -EINVAL;
6262 }
6263
6264 return 0;
bellardfaea38e2006-08-05 21:31:00 +00006265}
6266
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006267ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6268 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02006269{
6270 BlockDriver *drv = bs->drv;
6271 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006272 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02006273 }
6274 return NULL;
6275}
6276
Anton Nefedovd9245592019-09-23 15:17:37 +03006277BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6278{
6279 BlockDriver *drv = bs->drv;
6280 if (!drv || !drv->bdrv_get_specific_stats) {
6281 return NULL;
6282 }
6283 return drv->bdrv_get_specific_stats(bs);
6284}
6285
Eric Blakea31939e2015-11-18 01:52:54 -07006286void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006287{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006288 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006289 return;
6290 }
6291
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006292 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006293}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006294
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006295static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01006296{
6297 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02006298 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006299 }
6300
6301 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006302 assert(bs->drv->bdrv_debug_remove_breakpoint);
6303 return bs;
6304 }
6305
6306 return NULL;
6307}
6308
6309int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6310 const char *tag)
6311{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006312 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006313 bs = bdrv_find_debug_node(bs);
6314 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006315 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6316 }
6317
6318 return -ENOTSUP;
6319}
6320
Fam Zheng4cc70e92013-11-20 10:01:54 +08006321int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6322{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006323 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006324 bs = bdrv_find_debug_node(bs);
6325 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006326 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6327 }
6328
6329 return -ENOTSUP;
6330}
6331
Kevin Wolf41c695c2012-12-06 14:32:58 +01006332int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6333{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006334 GLOBAL_STATE_CODE();
Max Reitz938789e2014-03-10 23:44:08 +01006335 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006336 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006337 }
6338
6339 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6340 return bs->drv->bdrv_debug_resume(bs, tag);
6341 }
6342
6343 return -ENOTSUP;
6344}
6345
6346bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6347{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006348 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006349 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006350 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006351 }
6352
6353 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6354 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6355 }
6356
6357 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006358}
6359
Jeff Codyb1b1d782012-10-16 15:49:09 -04006360/* backing_file can either be relative, or absolute, or a protocol. If it is
6361 * relative, it must be relative to the chain. So, passing in bs->filename
6362 * from a BDS as backing_file should not be done, as that may be relative to
6363 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006364BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6365 const char *backing_file)
6366{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006367 char *filename_full = NULL;
6368 char *backing_file_full = NULL;
6369 char *filename_tmp = NULL;
6370 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006371 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006372 BlockDriverState *curr_bs = NULL;
6373 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006374 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006375
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006376 GLOBAL_STATE_CODE();
6377
Jeff Codyb1b1d782012-10-16 15:49:09 -04006378 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006379 return NULL;
6380 }
6381
Jeff Codyb1b1d782012-10-16 15:49:09 -04006382 filename_full = g_malloc(PATH_MAX);
6383 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006384
6385 is_protocol = path_has_protocol(backing_file);
6386
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006387 /*
6388 * Being largely a legacy function, skip any filters here
6389 * (because filters do not have normal filenames, so they cannot
6390 * match anyway; and allowing json:{} filenames is a bit out of
6391 * scope).
6392 */
6393 for (curr_bs = bdrv_skip_filters(bs);
6394 bdrv_cow_child(curr_bs) != NULL;
6395 curr_bs = bs_below)
6396 {
6397 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006398
Max Reitz0b877d02018-08-01 20:34:11 +02006399 if (bdrv_backing_overridden(curr_bs)) {
6400 /*
6401 * If the backing file was overridden, we can only compare
6402 * directly against the backing node's filename.
6403 */
6404
6405 if (!filenames_refreshed) {
6406 /*
6407 * This will automatically refresh all of the
6408 * filenames in the rest of the backing chain, so we
6409 * only need to do this once.
6410 */
6411 bdrv_refresh_filename(bs_below);
6412 filenames_refreshed = true;
6413 }
6414
6415 if (strcmp(backing_file, bs_below->filename) == 0) {
6416 retval = bs_below;
6417 break;
6418 }
6419 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6420 /*
6421 * If either of the filename paths is actually a protocol, then
6422 * compare unmodified paths; otherwise make paths relative.
6423 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006424 char *backing_file_full_ret;
6425
Jeff Codyb1b1d782012-10-16 15:49:09 -04006426 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006427 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006428 break;
6429 }
Jeff Cody418661e2017-01-25 20:08:20 -05006430 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006431 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6432 NULL);
6433 if (backing_file_full_ret) {
6434 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6435 g_free(backing_file_full_ret);
6436 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006437 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006438 break;
6439 }
Jeff Cody418661e2017-01-25 20:08:20 -05006440 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006441 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006442 /* If not an absolute filename path, make it relative to the current
6443 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006444 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6445 NULL);
6446 /* We are going to compare canonicalized absolute pathnames */
6447 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6448 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006449 continue;
6450 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006451 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006452
6453 /* We need to make sure the backing filename we are comparing against
6454 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006455 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6456 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6457 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006458 continue;
6459 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006460 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006461
6462 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006463 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006464 break;
6465 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006466 }
6467 }
6468
Jeff Codyb1b1d782012-10-16 15:49:09 -04006469 g_free(filename_full);
6470 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006471 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006472}
6473
bellardea2384d2004-08-01 21:59:26 +00006474void bdrv_init(void)
6475{
Kevin Wolfe5f05f82021-07-09 18:41:41 +02006476#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6477 use_bdrv_whitelist = 1;
6478#endif
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006479 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006480}
pbrookce1a14d2006-08-07 02:38:06 +00006481
Markus Armbrustereb852012009-10-27 18:41:44 +01006482void bdrv_init_with_whitelist(void)
6483{
6484 use_bdrv_whitelist = 1;
6485 bdrv_init();
6486}
6487
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006488int bdrv_activate(BlockDriverState *bs, Error **errp)
6489{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006490 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006491 Error *local_err = NULL;
6492 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006493 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006494
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006495 GLOBAL_STATE_CODE();
6496
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006497 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006498 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006499 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006500
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006501 QLIST_FOREACH(child, &bs->children, next) {
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006502 bdrv_activate(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006503 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006504 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006505 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006506 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006507 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006508
Kevin Wolfdafe0962017-11-16 13:00:01 +01006509 /*
6510 * Update permissions, they may differ for inactive nodes.
6511 *
6512 * Note that the required permissions of inactive images are always a
6513 * subset of the permissions required after activating the image. This
6514 * allows us to just get the permissions upfront without restricting
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006515 * bdrv_co_invalidate_cache().
Kevin Wolfdafe0962017-11-16 13:00:01 +01006516 *
6517 * It also means that in error cases, we don't have to try and revert to
6518 * the old permissions (which is an operation that could fail, too). We can
6519 * just keep the extended permissions for the next time that an activation
6520 * of the image is tried.
6521 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006522 if (bs->open_flags & BDRV_O_INACTIVE) {
6523 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006524 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006525 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006526 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006527 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006528 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006529
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006530 ret = bdrv_invalidate_cache(bs, errp);
6531 if (ret < 0) {
6532 bs->open_flags |= BDRV_O_INACTIVE;
6533 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006534 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006535
Kevin Wolf7bb49412019-12-17 15:06:38 +01006536 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6537 bdrv_dirty_bitmap_skip_store(bm, false);
6538 }
6539
6540 ret = refresh_total_sectors(bs, bs->total_sectors);
6541 if (ret < 0) {
6542 bs->open_flags |= BDRV_O_INACTIVE;
6543 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006544 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006545 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006546 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006547
6548 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006549 if (parent->klass->activate) {
6550 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006551 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006552 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006553 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006554 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006555 }
6556 }
6557 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006558
6559 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006560}
6561
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006562int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6563{
6564 Error *local_err = NULL;
6565
6566 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6567
6568 if (bs->drv->bdrv_co_invalidate_cache) {
6569 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6570 if (local_err) {
6571 error_propagate(errp, local_err);
6572 return -EINVAL;
6573 }
6574 }
6575
6576 return 0;
6577}
6578
Emanuele Giuseppe Esposito3b717192022-02-09 05:54:51 -05006579void bdrv_activate_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006580{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006581 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006582 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006583
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006584 GLOBAL_STATE_CODE();
6585
Kevin Wolf88be7b42016-05-20 18:49:07 +02006586 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006587 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006588 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006589
6590 aio_context_acquire(aio_context);
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006591 ret = bdrv_activate(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006592 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006593 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006594 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006595 return;
6596 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006597 }
6598}
6599
Kevin Wolf9e372712018-11-23 15:11:14 +01006600static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6601{
6602 BdrvChild *parent;
6603
6604 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006605 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006606 BlockDriverState *parent_bs = parent->opaque;
6607 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6608 return true;
6609 }
6610 }
6611 }
6612
6613 return false;
6614}
6615
6616static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006617{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006618 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006619 int ret;
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006620 uint64_t cumulative_perms, cumulative_shared_perms;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006621
Max Reitzd470ad42017-11-10 21:31:09 +01006622 if (!bs->drv) {
6623 return -ENOMEDIUM;
6624 }
6625
Kevin Wolf9e372712018-11-23 15:11:14 +01006626 /* Make sure that we don't inactivate a child before its parent.
6627 * It will be covered by recursion from the yet active parent. */
6628 if (bdrv_has_bds_parent(bs, true)) {
6629 return 0;
6630 }
6631
6632 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6633
6634 /* Inactivate this node */
6635 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006636 ret = bs->drv->bdrv_inactivate(bs);
6637 if (ret < 0) {
6638 return ret;
6639 }
6640 }
6641
Kevin Wolf9e372712018-11-23 15:11:14 +01006642 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006643 if (parent->klass->inactivate) {
6644 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006645 if (ret < 0) {
6646 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006647 }
6648 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006649 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006650
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006651 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6652 &cumulative_shared_perms);
6653 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6654 /* Our inactive parents still need write access. Inactivation failed. */
6655 return -EPERM;
6656 }
6657
Kevin Wolf9e372712018-11-23 15:11:14 +01006658 bs->open_flags |= BDRV_O_INACTIVE;
6659
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006660 /*
6661 * Update permissions, they may differ for inactive nodes.
6662 * We only tried to loosen restrictions, so errors are not fatal, ignore
6663 * them.
6664 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006665 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006666
6667 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006668 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006669 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006670 if (ret < 0) {
6671 return ret;
6672 }
6673 }
6674
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006675 return 0;
6676}
6677
6678int bdrv_inactivate_all(void)
6679{
Max Reitz79720af2016-03-16 19:54:44 +01006680 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006681 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006682 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006683 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006684
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006685 GLOBAL_STATE_CODE();
6686
Kevin Wolf88be7b42016-05-20 18:49:07 +02006687 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006688 AioContext *aio_context = bdrv_get_aio_context(bs);
6689
6690 if (!g_slist_find(aio_ctxs, aio_context)) {
6691 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6692 aio_context_acquire(aio_context);
6693 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006694 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006695
Kevin Wolf9e372712018-11-23 15:11:14 +01006696 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6697 /* Nodes with BDS parents are covered by recursion from the last
6698 * parent that gets inactivated. Don't inactivate them a second
6699 * time if that has already happened. */
6700 if (bdrv_has_bds_parent(bs, false)) {
6701 continue;
6702 }
6703 ret = bdrv_inactivate_recurse(bs);
6704 if (ret < 0) {
6705 bdrv_next_cleanup(&it);
6706 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006707 }
6708 }
6709
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006710out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006711 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6712 AioContext *aio_context = ctx->data;
6713 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006714 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006715 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006716
6717 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006718}
6719
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006720/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006721/* removable device support */
6722
6723/**
6724 * Return TRUE if the media is present
6725 */
Max Reitze031f752015-10-19 17:53:11 +02006726bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006727{
6728 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006729 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006730
Max Reitze031f752015-10-19 17:53:11 +02006731 if (!drv) {
6732 return false;
6733 }
Max Reitz28d7a782015-10-19 17:53:13 +02006734 if (drv->bdrv_is_inserted) {
6735 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006736 }
Max Reitz28d7a782015-10-19 17:53:13 +02006737 QLIST_FOREACH(child, &bs->children, next) {
6738 if (!bdrv_is_inserted(child->bs)) {
6739 return false;
6740 }
6741 }
6742 return true;
bellard19cb3732006-08-19 11:45:59 +00006743}
6744
6745/**
bellard19cb3732006-08-19 11:45:59 +00006746 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6747 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006748void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006749{
6750 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006751
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006752 if (drv && drv->bdrv_eject) {
6753 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006754 }
bellard19cb3732006-08-19 11:45:59 +00006755}
6756
bellard19cb3732006-08-19 11:45:59 +00006757/**
6758 * Lock or unlock the media (if it is locked, the user won't be able
6759 * to eject it manually).
6760 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006761void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006762{
6763 BlockDriver *drv = bs->drv;
6764
Markus Armbruster025e8492011-09-06 18:58:47 +02006765 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006766
Markus Armbruster025e8492011-09-06 18:58:47 +02006767 if (drv && drv->bdrv_lock_medium) {
6768 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006769 }
6770}
ths985a03b2007-12-24 16:10:43 +00006771
Fam Zheng9fcb0252013-08-23 09:14:46 +08006772/* Get a reference to bs */
6773void bdrv_ref(BlockDriverState *bs)
6774{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006775 GLOBAL_STATE_CODE();
Fam Zheng9fcb0252013-08-23 09:14:46 +08006776 bs->refcnt++;
6777}
6778
6779/* Release a previously grabbed reference to bs.
6780 * If after releasing, reference count is zero, the BlockDriverState is
6781 * deleted. */
6782void bdrv_unref(BlockDriverState *bs)
6783{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006784 GLOBAL_STATE_CODE();
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006785 if (!bs) {
6786 return;
6787 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006788 assert(bs->refcnt > 0);
6789 if (--bs->refcnt == 0) {
6790 bdrv_delete(bs);
6791 }
6792}
6793
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006794struct BdrvOpBlocker {
6795 Error *reason;
6796 QLIST_ENTRY(BdrvOpBlocker) list;
6797};
6798
6799bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6800{
6801 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006802 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006803 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6804 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6805 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006806 error_propagate_prepend(errp, error_copy(blocker->reason),
6807 "Node '%s' is busy: ",
6808 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006809 return true;
6810 }
6811 return false;
6812}
6813
6814void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6815{
6816 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006817 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006818 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6819
Markus Armbruster5839e532014-08-19 10:31:08 +02006820 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006821 blocker->reason = reason;
6822 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6823}
6824
6825void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6826{
6827 BdrvOpBlocker *blocker, *next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006828 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006829 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6830 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6831 if (blocker->reason == reason) {
6832 QLIST_REMOVE(blocker, list);
6833 g_free(blocker);
6834 }
6835 }
6836}
6837
6838void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6839{
6840 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006841 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006842 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6843 bdrv_op_block(bs, i, reason);
6844 }
6845}
6846
6847void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6848{
6849 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006850 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006851 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6852 bdrv_op_unblock(bs, i, reason);
6853 }
6854}
6855
6856bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6857{
6858 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006859 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006860 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6861 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6862 return false;
6863 }
6864 }
6865 return true;
6866}
6867
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006868void bdrv_img_create(const char *filename, const char *fmt,
6869 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006870 char *options, uint64_t img_size, int flags, bool quiet,
6871 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006872{
Chunyan Liu83d05212014-06-05 17:20:51 +08006873 QemuOptsList *create_opts = NULL;
6874 QemuOpts *opts = NULL;
6875 const char *backing_fmt, *backing_file;
6876 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006877 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006878 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006879 int ret = 0;
6880
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006881 GLOBAL_STATE_CODE();
6882
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006883 /* Find driver and parse its options */
6884 drv = bdrv_find_format(fmt);
6885 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006886 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006887 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006888 }
6889
Max Reitzb65a5e12015-02-05 13:58:12 -05006890 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006891 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006892 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006893 }
6894
Max Reitzc6149722014-12-02 18:32:45 +01006895 if (!drv->create_opts) {
6896 error_setg(errp, "Format driver '%s' does not support image creation",
6897 drv->format_name);
6898 return;
6899 }
6900
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006901 if (!proto_drv->create_opts) {
6902 error_setg(errp, "Protocol driver '%s' does not support image creation",
6903 proto_drv->format_name);
6904 return;
6905 }
6906
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006907 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006908 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006909 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006910
Chunyan Liu83d05212014-06-05 17:20:51 +08006911 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006912
6913 /* Parse -o options */
6914 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006915 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006916 goto out;
6917 }
6918 }
6919
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006920 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6921 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6922 } else if (img_size != UINT64_C(-1)) {
6923 error_setg(errp, "The image size must be specified only once");
6924 goto out;
6925 }
6926
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006927 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006928 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006929 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006930 error_setg(errp, "Backing file not supported for file format '%s'",
6931 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006932 goto out;
6933 }
6934 }
6935
6936 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006937 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006938 error_setg(errp, "Backing file format not supported for file "
6939 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006940 goto out;
6941 }
6942 }
6943
Chunyan Liu83d05212014-06-05 17:20:51 +08006944 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6945 if (backing_file) {
6946 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006947 error_setg(errp, "Error: Trying to create an image with the "
6948 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006949 goto out;
6950 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006951 if (backing_file[0] == '\0') {
6952 error_setg(errp, "Expected backing file name, got empty string");
6953 goto out;
6954 }
Jes Sorensen792da932010-12-16 13:52:17 +01006955 }
6956
Chunyan Liu83d05212014-06-05 17:20:51 +08006957 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006958
John Snow6e6e55f2017-07-17 20:34:22 -04006959 /* The size for the image must always be specified, unless we have a backing
6960 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006961 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006962 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6963 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006964 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006965 int back_flags;
6966 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006967
Max Reitz645ae7d2019-02-01 20:29:14 +01006968 full_backing =
6969 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6970 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006971 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006972 goto out;
6973 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006974 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006975
Max Reitzd5b23992021-06-22 16:00:30 +02006976 /*
6977 * No need to do I/O here, which allows us to open encrypted
6978 * backing images without needing the secret
6979 */
John Snow6e6e55f2017-07-17 20:34:22 -04006980 back_flags = flags;
6981 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02006982 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04006983
Fam Zhengcc954f02017-12-15 16:04:45 +08006984 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006985 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006986 qdict_put_str(backing_options, "driver", backing_fmt);
6987 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006988 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006989
6990 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6991 &local_err);
6992 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006993 if (!bs) {
6994 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006995 goto out;
6996 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006997 if (!backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07006998 error_setg(&local_err,
6999 "Backing file specified without backing format");
7000 error_append_hint(&local_err, "Detected format of %s.",
7001 bs->drv->format_name);
7002 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007003 }
John Snow6e6e55f2017-07-17 20:34:22 -04007004 if (size == -1) {
7005 /* Opened BS, have no size */
7006 size = bdrv_getlength(bs);
7007 if (size < 0) {
7008 error_setg_errno(errp, -size, "Could not get size of '%s'",
7009 backing_file);
7010 bdrv_unref(bs);
7011 goto out;
7012 }
7013 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7014 }
7015 bdrv_unref(bs);
7016 }
Eric Blaked9f059a2020-07-06 15:39:54 -05007017 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7018 } else if (backing_file && !backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007019 error_setg(&local_err,
7020 "Backing file specified without backing format");
7021 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007022 }
John Snow6e6e55f2017-07-17 20:34:22 -04007023
7024 if (size == -1) {
7025 error_setg(errp, "Image creation needs a size parameter");
7026 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007027 }
7028
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007029 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02007030 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08007031 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007032 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05007033 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007034 }
Chunyan Liu83d05212014-06-05 17:20:51 +08007035
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007036 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08007037
Max Reitzcc84d902013-09-06 17:14:26 +02007038 if (ret == -EFBIG) {
7039 /* This is generally a better message than whatever the driver would
7040 * deliver (especially because of the cluster_size_hint), since that
7041 * is most probably not much different from "image too large". */
7042 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08007043 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02007044 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007045 }
Max Reitzcc84d902013-09-06 17:14:26 +02007046 error_setg(errp, "The image size is too large for file format '%s'"
7047 "%s", fmt, cluster_size_hint);
7048 error_free(local_err);
7049 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007050 }
7051
7052out:
Chunyan Liu83d05212014-06-05 17:20:51 +08007053 qemu_opts_del(opts);
7054 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03007055 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007056}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007057
7058AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7059{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00007060 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007061}
7062
Kevin Wolfe336fd42020-10-05 17:58:53 +02007063AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7064{
7065 Coroutine *self = qemu_coroutine_self();
7066 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7067 AioContext *new_ctx;
7068
7069 /*
7070 * Increase bs->in_flight to ensure that this operation is completed before
7071 * moving the node to a different AioContext. Read new_ctx only afterwards.
7072 */
7073 bdrv_inc_in_flight(bs);
7074
7075 new_ctx = bdrv_get_aio_context(bs);
7076 aio_co_reschedule_self(new_ctx);
7077 return old_ctx;
7078}
7079
7080void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7081{
7082 aio_co_reschedule_self(old_ctx);
7083 bdrv_dec_in_flight(bs);
7084}
7085
Kevin Wolf18c6ac12020-10-05 17:58:54 +02007086void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7087{
7088 AioContext *ctx = bdrv_get_aio_context(bs);
7089
7090 /* In the main thread, bs->aio_context won't change concurrently */
7091 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7092
7093 /*
7094 * We're in coroutine context, so we already hold the lock of the main
7095 * loop AioContext. Don't lock it twice to avoid deadlocks.
7096 */
7097 assert(qemu_in_coroutine());
7098 if (ctx != qemu_get_aio_context()) {
7099 aio_context_acquire(ctx);
7100 }
7101}
7102
7103void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7104{
7105 AioContext *ctx = bdrv_get_aio_context(bs);
7106
7107 assert(qemu_in_coroutine());
7108 if (ctx != qemu_get_aio_context()) {
7109 aio_context_release(ctx);
7110 }
7111}
7112
Fam Zheng052a7572017-04-10 20:09:25 +08007113void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7114{
7115 aio_co_enter(bdrv_get_aio_context(bs), co);
7116}
7117
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007118static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7119{
7120 QLIST_REMOVE(ban, list);
7121 g_free(ban);
7122}
7123
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007124static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007125{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007126 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007127
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007128 assert(!bs->walking_aio_notifiers);
7129 bs->walking_aio_notifiers = true;
7130 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7131 if (baf->deleted) {
7132 bdrv_do_remove_aio_context_notifier(baf);
7133 } else {
7134 baf->detach_aio_context(baf->opaque);
7135 }
Max Reitz33384422014-06-20 21:57:33 +02007136 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007137 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7138 * remove remaining aio notifiers if we aren't called again.
7139 */
7140 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02007141
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007142 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007143 bs->drv->bdrv_detach_aio_context(bs);
7144 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007145
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007146 if (bs->quiesce_counter) {
7147 aio_enable_external(bs->aio_context);
7148 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007149 bs->aio_context = NULL;
7150}
7151
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007152static void bdrv_attach_aio_context(BlockDriverState *bs,
7153 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007154{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007155 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007156
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007157 if (bs->quiesce_counter) {
7158 aio_disable_external(new_context);
7159 }
7160
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007161 bs->aio_context = new_context;
7162
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007163 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007164 bs->drv->bdrv_attach_aio_context(bs, new_context);
7165 }
Max Reitz33384422014-06-20 21:57:33 +02007166
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007167 assert(!bs->walking_aio_notifiers);
7168 bs->walking_aio_notifiers = true;
7169 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7170 if (ban->deleted) {
7171 bdrv_do_remove_aio_context_notifier(ban);
7172 } else {
7173 ban->attached_aio_context(new_context, ban->opaque);
7174 }
Max Reitz33384422014-06-20 21:57:33 +02007175 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007176 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007177}
7178
Kevin Wolf42a65f02019-05-07 18:31:38 +02007179/*
7180 * Changes the AioContext used for fd handlers, timers, and BHs by this
7181 * BlockDriverState and all its children and parents.
7182 *
Max Reitz43eaaae2019-07-22 15:30:54 +02007183 * Must be called from the main AioContext.
7184 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02007185 * The caller must own the AioContext lock for the old AioContext of bs, but it
7186 * must not own the AioContext lock for new_context (unless new_context is the
7187 * same as the current context of bs).
7188 *
7189 * @ignore will accumulate all visited BdrvChild object. The caller is
7190 * responsible for freeing the list afterwards.
7191 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02007192void bdrv_set_aio_context_ignore(BlockDriverState *bs,
7193 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007194{
Max Reitze037c092019-07-19 11:26:14 +02007195 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007196 GSList *children_to_process = NULL;
7197 GSList *parents_to_process = NULL;
7198 GSList *entry;
7199 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02007200
Max Reitz43eaaae2019-07-22 15:30:54 +02007201 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7202
Max Reitze037c092019-07-19 11:26:14 +02007203 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03007204 return;
7205 }
7206
Kevin Wolfd70d5952019-02-08 16:53:37 +01007207 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02007208
7209 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007210 if (g_slist_find(*ignore, child)) {
7211 continue;
7212 }
7213 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007214 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02007215 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007216
7217 QLIST_FOREACH(parent, &bs->parents, next_parent) {
7218 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007219 continue;
7220 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007221 *ignore = g_slist_prepend(*ignore, parent);
7222 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02007223 }
7224
Sergio Lopez722d8e72021-02-01 13:50:31 +01007225 for (entry = children_to_process;
7226 entry != NULL;
7227 entry = g_slist_next(entry)) {
7228 child = entry->data;
7229 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
7230 }
7231 g_slist_free(children_to_process);
7232
7233 for (entry = parents_to_process;
7234 entry != NULL;
7235 entry = g_slist_next(entry)) {
7236 parent = entry->data;
7237 assert(parent->klass->set_aio_ctx);
7238 parent->klass->set_aio_ctx(parent, new_context, ignore);
7239 }
7240 g_slist_free(parents_to_process);
7241
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007242 bdrv_detach_aio_context(bs);
7243
Max Reitze037c092019-07-19 11:26:14 +02007244 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02007245 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007246 aio_context_acquire(new_context);
7247 }
7248
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007249 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02007250
7251 /*
7252 * If this function was recursively called from
7253 * bdrv_set_aio_context_ignore(), there may be nodes in the
7254 * subtree that have not yet been moved to the new AioContext.
7255 * Release the old one so bdrv_drained_end() can poll them.
7256 */
Max Reitz43eaaae2019-07-22 15:30:54 +02007257 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007258 aio_context_release(old_context);
7259 }
7260
Kevin Wolfd70d5952019-02-08 16:53:37 +01007261 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02007262
Max Reitz43eaaae2019-07-22 15:30:54 +02007263 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007264 aio_context_acquire(old_context);
7265 }
Max Reitz43eaaae2019-07-22 15:30:54 +02007266 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007267 aio_context_release(new_context);
7268 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007269}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02007270
Kevin Wolf5d231842019-05-06 19:17:56 +02007271static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7272 GSList **ignore, Error **errp)
7273{
7274 if (g_slist_find(*ignore, c)) {
7275 return true;
7276 }
7277 *ignore = g_slist_prepend(*ignore, c);
7278
Max Reitzbd86fb92020-05-13 13:05:13 +02007279 /*
7280 * A BdrvChildClass that doesn't handle AioContext changes cannot
7281 * tolerate any AioContext changes
7282 */
7283 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007284 char *user = bdrv_child_user_desc(c);
7285 error_setg(errp, "Changing iothreads is not supported by %s", user);
7286 g_free(user);
7287 return false;
7288 }
Max Reitzbd86fb92020-05-13 13:05:13 +02007289 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007290 assert(!errp || *errp);
7291 return false;
7292 }
7293 return true;
7294}
7295
7296bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7297 GSList **ignore, Error **errp)
7298{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007299 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007300 if (g_slist_find(*ignore, c)) {
7301 return true;
7302 }
7303 *ignore = g_slist_prepend(*ignore, c);
7304 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
7305}
7306
7307/* @ignore will accumulate all visited BdrvChild object. The caller is
7308 * responsible for freeing the list afterwards. */
7309bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7310 GSList **ignore, Error **errp)
7311{
7312 BdrvChild *c;
7313
7314 if (bdrv_get_aio_context(bs) == ctx) {
7315 return true;
7316 }
7317
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007318 GLOBAL_STATE_CODE();
7319
Kevin Wolf5d231842019-05-06 19:17:56 +02007320 QLIST_FOREACH(c, &bs->parents, next_parent) {
7321 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
7322 return false;
7323 }
7324 }
7325 QLIST_FOREACH(c, &bs->children, next) {
7326 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
7327 return false;
7328 }
7329 }
7330
7331 return true;
7332}
7333
7334int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7335 BdrvChild *ignore_child, Error **errp)
7336{
7337 GSList *ignore;
7338 bool ret;
7339
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007340 GLOBAL_STATE_CODE();
7341
Kevin Wolf5d231842019-05-06 19:17:56 +02007342 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7343 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7344 g_slist_free(ignore);
7345
7346 if (!ret) {
7347 return -EPERM;
7348 }
7349
Kevin Wolf53a7d042019-05-06 19:17:59 +02007350 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7351 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7352 g_slist_free(ignore);
7353
Kevin Wolf5d231842019-05-06 19:17:56 +02007354 return 0;
7355}
7356
7357int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7358 Error **errp)
7359{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007360 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007361 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7362}
7363
Max Reitz33384422014-06-20 21:57:33 +02007364void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7365 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7366 void (*detach_aio_context)(void *opaque), void *opaque)
7367{
7368 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7369 *ban = (BdrvAioNotifier){
7370 .attached_aio_context = attached_aio_context,
7371 .detach_aio_context = detach_aio_context,
7372 .opaque = opaque
7373 };
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007374 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007375
7376 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7377}
7378
7379void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7380 void (*attached_aio_context)(AioContext *,
7381 void *),
7382 void (*detach_aio_context)(void *),
7383 void *opaque)
7384{
7385 BdrvAioNotifier *ban, *ban_next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007386 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007387
7388 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7389 if (ban->attached_aio_context == attached_aio_context &&
7390 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007391 ban->opaque == opaque &&
7392 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007393 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007394 if (bs->walking_aio_notifiers) {
7395 ban->deleted = true;
7396 } else {
7397 bdrv_do_remove_aio_context_notifier(ban);
7398 }
Max Reitz33384422014-06-20 21:57:33 +02007399 return;
7400 }
7401 }
7402
7403 abort();
7404}
7405
Max Reitz77485432014-10-27 11:12:50 +01007406int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007407 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007408 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007409 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007410{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007411 GLOBAL_STATE_CODE();
Max Reitzd470ad42017-11-10 21:31:09 +01007412 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007413 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007414 return -ENOMEDIUM;
7415 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007416 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007417 error_setg(errp, "Block driver '%s' does not support option amendment",
7418 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007419 return -ENOTSUP;
7420 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007421 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7422 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007423}
Benoît Canetf6186f42013-10-02 14:33:48 +02007424
Max Reitz5d69b5a2020-02-18 11:34:41 +01007425/*
7426 * This function checks whether the given @to_replace is allowed to be
7427 * replaced by a node that always shows the same data as @bs. This is
7428 * used for example to verify whether the mirror job can replace
7429 * @to_replace by the target mirrored from @bs.
7430 * To be replaceable, @bs and @to_replace may either be guaranteed to
7431 * always show the same data (because they are only connected through
7432 * filters), or some driver may allow replacing one of its children
7433 * because it can guarantee that this child's data is not visible at
7434 * all (for example, for dissenting quorum children that have no other
7435 * parents).
7436 */
7437bool bdrv_recurse_can_replace(BlockDriverState *bs,
7438 BlockDriverState *to_replace)
7439{
Max Reitz93393e62019-06-12 17:03:38 +02007440 BlockDriverState *filtered;
7441
Max Reitz5d69b5a2020-02-18 11:34:41 +01007442 if (!bs || !bs->drv) {
7443 return false;
7444 }
7445
7446 if (bs == to_replace) {
7447 return true;
7448 }
7449
7450 /* See what the driver can do */
7451 if (bs->drv->bdrv_recurse_can_replace) {
7452 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7453 }
7454
7455 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007456 filtered = bdrv_filter_bs(bs);
7457 if (filtered) {
7458 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007459 }
7460
7461 /* Safe default */
7462 return false;
7463}
7464
Max Reitz810803a2020-02-18 11:34:44 +01007465/*
7466 * Check whether the given @node_name can be replaced by a node that
7467 * has the same data as @parent_bs. If so, return @node_name's BDS;
7468 * NULL otherwise.
7469 *
7470 * @node_name must be a (recursive) *child of @parent_bs (or this
7471 * function will return NULL).
7472 *
7473 * The result (whether the node can be replaced or not) is only valid
7474 * for as long as no graph or permission changes occur.
7475 */
Wen Congyange12f3782015-07-17 10:12:22 +08007476BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7477 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007478{
7479 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007480 AioContext *aio_context;
7481
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007482 GLOBAL_STATE_CODE();
7483
Benoît Canet09158f02014-06-27 18:25:25 +02007484 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007485 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007486 return NULL;
7487 }
7488
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007489 aio_context = bdrv_get_aio_context(to_replace_bs);
7490 aio_context_acquire(aio_context);
7491
Benoît Canet09158f02014-06-27 18:25:25 +02007492 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007493 to_replace_bs = NULL;
7494 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007495 }
7496
7497 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7498 * most non filter in order to prevent data corruption.
7499 * Another benefit is that this tests exclude backing files which are
7500 * blocked by the backing blockers.
7501 */
Max Reitz810803a2020-02-18 11:34:44 +01007502 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7503 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7504 "because it cannot be guaranteed that doing so would not "
7505 "lead to an abrupt change of visible data",
7506 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007507 to_replace_bs = NULL;
7508 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007509 }
7510
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007511out:
7512 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007513 return to_replace_bs;
7514}
Ming Lei448ad912014-07-04 18:04:33 +08007515
Max Reitz97e2f022019-02-01 20:29:27 +01007516/**
7517 * Iterates through the list of runtime option keys that are said to
7518 * be "strong" for a BDS. An option is called "strong" if it changes
7519 * a BDS's data. For example, the null block driver's "size" and
7520 * "read-zeroes" options are strong, but its "latency-ns" option is
7521 * not.
7522 *
7523 * If a key returned by this function ends with a dot, all options
7524 * starting with that prefix are strong.
7525 */
7526static const char *const *strong_options(BlockDriverState *bs,
7527 const char *const *curopt)
7528{
7529 static const char *const global_options[] = {
7530 "driver", "filename", NULL
7531 };
7532
7533 if (!curopt) {
7534 return &global_options[0];
7535 }
7536
7537 curopt++;
7538 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7539 curopt = bs->drv->strong_runtime_opts;
7540 }
7541
7542 return (curopt && *curopt) ? curopt : NULL;
7543}
7544
7545/**
7546 * Copies all strong runtime options from bs->options to the given
7547 * QDict. The set of strong option keys is determined by invoking
7548 * strong_options().
7549 *
7550 * Returns true iff any strong option was present in bs->options (and
7551 * thus copied to the target QDict) with the exception of "filename"
7552 * and "driver". The caller is expected to use this value to decide
7553 * whether the existence of strong options prevents the generation of
7554 * a plain filename.
7555 */
7556static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7557{
7558 bool found_any = false;
7559 const char *const *option_name = NULL;
7560
7561 if (!bs->drv) {
7562 return false;
7563 }
7564
7565 while ((option_name = strong_options(bs, option_name))) {
7566 bool option_given = false;
7567
7568 assert(strlen(*option_name) > 0);
7569 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7570 QObject *entry = qdict_get(bs->options, *option_name);
7571 if (!entry) {
7572 continue;
7573 }
7574
7575 qdict_put_obj(d, *option_name, qobject_ref(entry));
7576 option_given = true;
7577 } else {
7578 const QDictEntry *entry;
7579 for (entry = qdict_first(bs->options); entry;
7580 entry = qdict_next(bs->options, entry))
7581 {
7582 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7583 qdict_put_obj(d, qdict_entry_key(entry),
7584 qobject_ref(qdict_entry_value(entry)));
7585 option_given = true;
7586 }
7587 }
7588 }
7589
7590 /* While "driver" and "filename" need to be included in a JSON filename,
7591 * their existence does not prohibit generation of a plain filename. */
7592 if (!found_any && option_given &&
7593 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7594 {
7595 found_any = true;
7596 }
7597 }
7598
Max Reitz62a01a272019-02-01 20:29:34 +01007599 if (!qdict_haskey(d, "driver")) {
7600 /* Drivers created with bdrv_new_open_driver() may not have a
7601 * @driver option. Add it here. */
7602 qdict_put_str(d, "driver", bs->drv->format_name);
7603 }
7604
Max Reitz97e2f022019-02-01 20:29:27 +01007605 return found_any;
7606}
7607
Max Reitz90993622019-02-01 20:29:09 +01007608/* Note: This function may return false positives; it may return true
7609 * even if opening the backing file specified by bs's image header
7610 * would result in exactly bs->backing. */
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -05007611static bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007612{
7613 if (bs->backing) {
7614 return strcmp(bs->auto_backing_file,
7615 bs->backing->bs->filename);
7616 } else {
7617 /* No backing BDS, so if the image header reports any backing
7618 * file, it must have been suppressed */
7619 return bs->auto_backing_file[0] != '\0';
7620 }
7621}
7622
Max Reitz91af7012014-07-18 20:24:56 +02007623/* Updates the following BDS fields:
7624 * - exact_filename: A filename which may be used for opening a block device
7625 * which (mostly) equals the given BDS (even without any
7626 * other options; so reading and writing must return the same
7627 * results, but caching etc. may be different)
7628 * - full_open_options: Options which, when given when opening a block device
7629 * (without a filename), result in a BDS (mostly)
7630 * equalling the given one
7631 * - filename: If exact_filename is set, it is copied here. Otherwise,
7632 * full_open_options is converted to a JSON object, prefixed with
7633 * "json:" (for use through the JSON pseudo protocol) and put here.
7634 */
7635void bdrv_refresh_filename(BlockDriverState *bs)
7636{
7637 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007638 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007639 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007640 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007641 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007642 bool generate_json_filename; /* Whether our default implementation should
7643 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007644
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007645 GLOBAL_STATE_CODE();
7646
Max Reitz91af7012014-07-18 20:24:56 +02007647 if (!drv) {
7648 return;
7649 }
7650
Max Reitze24518e2019-02-01 20:29:06 +01007651 /* This BDS's file name may depend on any of its children's file names, so
7652 * refresh those first */
7653 QLIST_FOREACH(child, &bs->children, next) {
7654 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007655 }
7656
Max Reitzbb808d52019-02-01 20:29:07 +01007657 if (bs->implicit) {
7658 /* For implicit nodes, just copy everything from the single child */
7659 child = QLIST_FIRST(&bs->children);
7660 assert(QLIST_NEXT(child, next) == NULL);
7661
7662 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7663 child->bs->exact_filename);
7664 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7665
Pan Nengyuancb895612020-01-16 16:56:00 +08007666 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007667 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7668
7669 return;
7670 }
7671
Max Reitz90993622019-02-01 20:29:09 +01007672 backing_overridden = bdrv_backing_overridden(bs);
7673
7674 if (bs->open_flags & BDRV_O_NO_IO) {
7675 /* Without I/O, the backing file does not change anything.
7676 * Therefore, in such a case (primarily qemu-img), we can
7677 * pretend the backing file has not been overridden even if
7678 * it technically has been. */
7679 backing_overridden = false;
7680 }
7681
Max Reitz97e2f022019-02-01 20:29:27 +01007682 /* Gather the options QDict */
7683 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007684 generate_json_filename = append_strong_runtime_options(opts, bs);
7685 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007686
7687 if (drv->bdrv_gather_child_options) {
7688 /* Some block drivers may not want to present all of their children's
7689 * options, or name them differently from BdrvChild.name */
7690 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7691 } else {
7692 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007693 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007694 /* We can skip the backing BDS if it has not been overridden */
7695 continue;
7696 }
7697
7698 qdict_put(opts, child->name,
7699 qobject_ref(child->bs->full_open_options));
7700 }
7701
7702 if (backing_overridden && !bs->backing) {
7703 /* Force no backing file */
7704 qdict_put_null(opts, "backing");
7705 }
7706 }
7707
7708 qobject_unref(bs->full_open_options);
7709 bs->full_open_options = opts;
7710
Max Reitz52f72d62019-06-12 17:43:03 +02007711 primary_child_bs = bdrv_primary_bs(bs);
7712
Max Reitz998b3a12019-02-01 20:29:28 +01007713 if (drv->bdrv_refresh_filename) {
7714 /* Obsolete information is of no use here, so drop the old file name
7715 * information before refreshing it */
7716 bs->exact_filename[0] = '\0';
7717
7718 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007719 } else if (primary_child_bs) {
7720 /*
7721 * Try to reconstruct valid information from the underlying
7722 * file -- this only works for format nodes (filter nodes
7723 * cannot be probed and as such must be selected by the user
7724 * either through an options dict, or through a special
7725 * filename which the filter driver must construct in its
7726 * .bdrv_refresh_filename() implementation).
7727 */
Max Reitz998b3a12019-02-01 20:29:28 +01007728
7729 bs->exact_filename[0] = '\0';
7730
Max Reitzfb695c72019-02-01 20:29:29 +01007731 /*
7732 * We can use the underlying file's filename if:
7733 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007734 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007735 * - the file is a protocol BDS, and
7736 * - opening that file (as this BDS's format) will automatically create
7737 * the BDS tree we have right now, that is:
7738 * - the user did not significantly change this BDS's behavior with
7739 * some explicit (strong) options
7740 * - no non-file child of this BDS has been overridden by the user
7741 * Both of these conditions are represented by generate_json_filename.
7742 */
Max Reitz52f72d62019-06-12 17:43:03 +02007743 if (primary_child_bs->exact_filename[0] &&
7744 primary_child_bs->drv->bdrv_file_open &&
7745 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007746 {
Max Reitz52f72d62019-06-12 17:43:03 +02007747 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007748 }
7749 }
7750
Max Reitz91af7012014-07-18 20:24:56 +02007751 if (bs->exact_filename[0]) {
7752 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007753 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007754 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007755 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007756 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007757 /* Give user a hint if we truncated things. */
7758 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7759 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007760 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007761 }
7762}
Wen Congyange06018a2016-05-10 15:36:37 +08007763
Max Reitz1e89d0f2019-02-01 20:29:18 +01007764char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7765{
7766 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007767 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007768
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007769 GLOBAL_STATE_CODE();
7770
Max Reitz1e89d0f2019-02-01 20:29:18 +01007771 if (!drv) {
7772 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7773 return NULL;
7774 }
7775
7776 if (drv->bdrv_dirname) {
7777 return drv->bdrv_dirname(bs, errp);
7778 }
7779
Max Reitz52f72d62019-06-12 17:43:03 +02007780 child_bs = bdrv_primary_bs(bs);
7781 if (child_bs) {
7782 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007783 }
7784
7785 bdrv_refresh_filename(bs);
7786 if (bs->exact_filename[0] != '\0') {
7787 return path_combine(bs->exact_filename, "");
7788 }
7789
7790 error_setg(errp, "Cannot generate a base directory for %s nodes",
7791 drv->format_name);
7792 return NULL;
7793}
7794
Wen Congyange06018a2016-05-10 15:36:37 +08007795/*
7796 * Hot add/remove a BDS's child. So the user can take a child offline when
7797 * it is broken and take a new child online
7798 */
7799void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7800 Error **errp)
7801{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007802 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007803 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7804 error_setg(errp, "The node %s does not support adding a child",
7805 bdrv_get_device_or_node_name(parent_bs));
7806 return;
7807 }
7808
7809 if (!QLIST_EMPTY(&child_bs->parents)) {
7810 error_setg(errp, "The node %s already has a parent",
7811 child_bs->node_name);
7812 return;
7813 }
7814
7815 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7816}
7817
7818void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7819{
7820 BdrvChild *tmp;
7821
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007822 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007823 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7824 error_setg(errp, "The node %s does not support removing a child",
7825 bdrv_get_device_or_node_name(parent_bs));
7826 return;
7827 }
7828
7829 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7830 if (tmp == child) {
7831 break;
7832 }
7833 }
7834
7835 if (!tmp) {
7836 error_setg(errp, "The node %s does not have a child named %s",
7837 bdrv_get_device_or_node_name(parent_bs),
7838 bdrv_get_device_or_node_name(child->bs));
7839 return;
7840 }
7841
7842 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7843}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007844
7845int bdrv_make_empty(BdrvChild *c, Error **errp)
7846{
7847 BlockDriver *drv = c->bs->drv;
7848 int ret;
7849
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007850 GLOBAL_STATE_CODE();
Max Reitz6f7a3b52020-04-29 16:11:23 +02007851 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7852
7853 if (!drv->bdrv_make_empty) {
7854 error_setg(errp, "%s does not support emptying nodes",
7855 drv->format_name);
7856 return -ENOTSUP;
7857 }
7858
7859 ret = drv->bdrv_make_empty(c->bs);
7860 if (ret < 0) {
7861 error_setg_errno(errp, -ret, "Failed to empty %s",
7862 c->bs->filename);
7863 return ret;
7864 }
7865
7866 return 0;
7867}
Max Reitz9a6fc882019-05-31 15:23:11 +02007868
7869/*
7870 * Return the child that @bs acts as an overlay for, and from which data may be
7871 * copied in COW or COR operations. Usually this is the backing file.
7872 */
7873BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7874{
7875 if (!bs || !bs->drv) {
7876 return NULL;
7877 }
7878
7879 if (bs->drv->is_filter) {
7880 return NULL;
7881 }
7882
7883 if (!bs->backing) {
7884 return NULL;
7885 }
7886
7887 assert(bs->backing->role & BDRV_CHILD_COW);
7888 return bs->backing;
7889}
7890
7891/*
7892 * If @bs acts as a filter for exactly one of its children, return
7893 * that child.
7894 */
7895BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7896{
7897 BdrvChild *c;
7898
7899 if (!bs || !bs->drv) {
7900 return NULL;
7901 }
7902
7903 if (!bs->drv->is_filter) {
7904 return NULL;
7905 }
7906
7907 /* Only one of @backing or @file may be used */
7908 assert(!(bs->backing && bs->file));
7909
7910 c = bs->backing ?: bs->file;
7911 if (!c) {
7912 return NULL;
7913 }
7914
7915 assert(c->role & BDRV_CHILD_FILTERED);
7916 return c;
7917}
7918
7919/*
7920 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7921 * whichever is non-NULL.
7922 *
7923 * Return NULL if both are NULL.
7924 */
7925BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7926{
7927 BdrvChild *cow_child = bdrv_cow_child(bs);
7928 BdrvChild *filter_child = bdrv_filter_child(bs);
7929
7930 /* Filter nodes cannot have COW backing files */
7931 assert(!(cow_child && filter_child));
7932
7933 return cow_child ?: filter_child;
7934}
7935
7936/*
7937 * Return the primary child of this node: For filters, that is the
7938 * filtered child. For other nodes, that is usually the child storing
7939 * metadata.
7940 * (A generally more helpful description is that this is (usually) the
7941 * child that has the same filename as @bs.)
7942 *
7943 * Drivers do not necessarily have a primary child; for example quorum
7944 * does not.
7945 */
7946BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7947{
7948 BdrvChild *c, *found = NULL;
7949
7950 QLIST_FOREACH(c, &bs->children, next) {
7951 if (c->role & BDRV_CHILD_PRIMARY) {
7952 assert(!found);
7953 found = c;
7954 }
7955 }
7956
7957 return found;
7958}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007959
7960static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7961 bool stop_on_explicit_filter)
7962{
7963 BdrvChild *c;
7964
7965 if (!bs) {
7966 return NULL;
7967 }
7968
7969 while (!(stop_on_explicit_filter && !bs->implicit)) {
7970 c = bdrv_filter_child(bs);
7971 if (!c) {
7972 /*
7973 * A filter that is embedded in a working block graph must
7974 * have a child. Assert this here so this function does
7975 * not return a filter node that is not expected by the
7976 * caller.
7977 */
7978 assert(!bs->drv || !bs->drv->is_filter);
7979 break;
7980 }
7981 bs = c->bs;
7982 }
7983 /*
7984 * Note that this treats nodes with bs->drv == NULL as not being
7985 * filters (bs->drv == NULL should be replaced by something else
7986 * anyway).
7987 * The advantage of this behavior is that this function will thus
7988 * always return a non-NULL value (given a non-NULL @bs).
7989 */
7990
7991 return bs;
7992}
7993
7994/*
7995 * Return the first BDS that has not been added implicitly or that
7996 * does not have a filtered child down the chain starting from @bs
7997 * (including @bs itself).
7998 */
7999BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8000{
8001 return bdrv_do_skip_filters(bs, true);
8002}
8003
8004/*
8005 * Return the first BDS that does not have a filtered child down the
8006 * chain starting from @bs (including @bs itself).
8007 */
8008BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8009{
8010 return bdrv_do_skip_filters(bs, false);
8011}
8012
8013/*
8014 * For a backing chain, return the first non-filter backing image of
8015 * the first non-filter image.
8016 */
8017BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8018{
8019 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8020}
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008021
8022/**
8023 * Check whether [offset, offset + bytes) overlaps with the cached
8024 * block-status data region.
8025 *
8026 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8027 * which is what bdrv_bsc_is_data()'s interface needs.
8028 * Otherwise, *pnum is not touched.
8029 */
8030static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8031 int64_t offset, int64_t bytes,
8032 int64_t *pnum)
8033{
8034 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8035 bool overlaps;
8036
8037 overlaps =
8038 qatomic_read(&bsc->valid) &&
8039 ranges_overlap(offset, bytes, bsc->data_start,
8040 bsc->data_end - bsc->data_start);
8041
8042 if (overlaps && pnum) {
8043 *pnum = bsc->data_end - offset;
8044 }
8045
8046 return overlaps;
8047}
8048
8049/**
8050 * See block_int.h for this function's documentation.
8051 */
8052bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8053{
8054 RCU_READ_LOCK_GUARD();
8055
8056 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8057}
8058
8059/**
8060 * See block_int.h for this function's documentation.
8061 */
8062void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8063 int64_t offset, int64_t bytes)
8064{
8065 RCU_READ_LOCK_GUARD();
8066
8067 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8068 qatomic_set(&bs->block_status_cache->valid, false);
8069 }
8070}
8071
8072/**
8073 * See block_int.h for this function's documentation.
8074 */
8075void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8076{
8077 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8078 BdrvBlockStatusCache *old_bsc;
8079
8080 *new_bsc = (BdrvBlockStatusCache) {
8081 .valid = true,
8082 .data_start = offset,
8083 .data_end = offset + bytes,
8084 };
8085
8086 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8087
8088 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8089 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8090 if (old_bsc) {
8091 g_free_rcu(old_bsc, rcu);
8092 }
8093}