blob: 2f80b7e09449cb6eb3abd2ed045caaa6a5d3344b [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 Reitzbe64bbb2021-11-15 15:54:01 +010093static void bdrv_replace_child_noperm(BdrvChild **child,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +030094 BlockDriverState *new_bs);
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +030095static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
96 BdrvChild *child,
97 Transaction *tran);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +030098static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
99 Transaction *tran);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +0300100
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +0300101static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
102 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +0300103 Transaction *change_child_tran, Error **errp);
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +0300104static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
105static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
106
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -0500107static bool bdrv_backing_overridden(BlockDriverState *bs);
108
Markus Armbrustereb852012009-10-27 18:41:44 +0100109/* If non-zero, use only whitelisted block drivers */
110static int use_bdrv_whitelist;
111
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000112#ifdef _WIN32
113static int is_windows_drive_prefix(const char *filename)
114{
115 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
116 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
117 filename[1] == ':');
118}
119
120int is_windows_drive(const char *filename)
121{
122 if (is_windows_drive_prefix(filename) &&
123 filename[2] == '\0')
124 return 1;
125 if (strstart(filename, "\\\\.\\", NULL) ||
126 strstart(filename, "//./", NULL))
127 return 1;
128 return 0;
129}
130#endif
131
Kevin Wolf339064d2013-11-28 10:23:32 +0100132size_t bdrv_opt_mem_align(BlockDriverState *bs)
133{
134 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300135 /* page size or 4k (hdd sector size) should be on the safe side */
Marc-André Lureau8e3b0cb2022-03-23 19:57:22 +0400136 return MAX(4096, qemu_real_host_page_size());
Kevin Wolf339064d2013-11-28 10:23:32 +0100137 }
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500138 IO_CODE();
Kevin Wolf339064d2013-11-28 10:23:32 +0100139
140 return bs->bl.opt_mem_alignment;
141}
142
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300143size_t bdrv_min_mem_align(BlockDriverState *bs)
144{
145 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300146 /* page size or 4k (hdd sector size) should be on the safe side */
Marc-André Lureau8e3b0cb2022-03-23 19:57:22 +0400147 return MAX(4096, qemu_real_host_page_size());
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300148 }
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500149 IO_CODE();
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300150
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{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500275 IO_CODE();
Vladimir Sementsov-Ogievskiy975da072021-05-27 18:40:55 +0300276 return !(bs->open_flags & BDRV_O_RDWR);
Jeff Cody93ed5242017-04-07 16:55:28 -0400277}
278
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200279int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
280 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400281{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500282 IO_CODE();
283
Jeff Codye2b82472017-04-07 16:55:26 -0400284 /* Do not set read_only if copy_on_read is enabled */
285 if (bs->copy_on_read && read_only) {
286 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
287 bdrv_get_device_or_node_name(bs));
288 return -EINVAL;
289 }
290
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400291 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200292 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
293 !ignore_allow_rdw)
294 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400295 error_setg(errp, "Node '%s' is read only",
296 bdrv_get_device_or_node_name(bs));
297 return -EPERM;
298 }
299
Jeff Cody45803a02017-04-07 16:55:29 -0400300 return 0;
301}
302
Kevin Wolfeaa24102018-10-12 11:27:41 +0200303/*
304 * Called by a driver that can only provide a read-only image.
305 *
306 * Returns 0 if the node is already read-only or it could switch the node to
307 * read-only because BDRV_O_AUTO_RDONLY is set.
308 *
309 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
310 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
311 * is not NULL, it is used as the error message for the Error object.
312 */
313int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
314 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400315{
316 int ret = 0;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500317 IO_CODE();
Jeff Cody45803a02017-04-07 16:55:29 -0400318
Kevin Wolfeaa24102018-10-12 11:27:41 +0200319 if (!(bs->open_flags & BDRV_O_RDWR)) {
320 return 0;
321 }
322 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
323 goto fail;
324 }
325
326 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400327 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200328 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400329 }
330
Kevin Wolfeaa24102018-10-12 11:27:41 +0200331 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200332
Jeff Codye2b82472017-04-07 16:55:26 -0400333 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200334
335fail:
336 error_setg(errp, "%s", errmsg ?: "Image is read-only");
337 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400338}
339
Max Reitz645ae7d2019-02-01 20:29:14 +0100340/*
341 * If @backing is empty, this function returns NULL without setting
342 * @errp. In all other cases, NULL will only be returned with @errp
343 * set.
344 *
345 * Therefore, a return value of NULL without @errp set means that
346 * there is no backing file; if @errp is set, there is one but its
347 * absolute filename cannot be generated.
348 */
349char *bdrv_get_full_backing_filename_from_filename(const char *backed,
350 const char *backing,
351 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100352{
Max Reitz645ae7d2019-02-01 20:29:14 +0100353 if (backing[0] == '\0') {
354 return NULL;
355 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
356 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100357 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
358 error_setg(errp, "Cannot use relative backing file names for '%s'",
359 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100360 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100361 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100362 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100363 }
364}
365
Max Reitz9f4793d2019-02-01 20:29:16 +0100366/*
367 * If @filename is empty or NULL, this function returns NULL without
368 * setting @errp. In all other cases, NULL will only be returned with
369 * @errp set.
370 */
371static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
372 const char *filename, Error **errp)
373{
Max Reitz8df68612019-02-01 20:29:23 +0100374 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100375
Max Reitz8df68612019-02-01 20:29:23 +0100376 if (!filename || filename[0] == '\0') {
377 return NULL;
378 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
379 return g_strdup(filename);
380 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100381
Max Reitz8df68612019-02-01 20:29:23 +0100382 dir = bdrv_dirname(relative_to, errp);
383 if (!dir) {
384 return NULL;
385 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100386
Max Reitz8df68612019-02-01 20:29:23 +0100387 full_name = g_strconcat(dir, filename, NULL);
388 g_free(dir);
389 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100390}
391
Max Reitz6b6833c2019-02-01 20:29:15 +0100392char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200393{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500394 GLOBAL_STATE_CODE();
Max Reitz9f4793d2019-02-01 20:29:16 +0100395 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200396}
397
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100398void bdrv_register(BlockDriver *bdrv)
399{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100400 assert(bdrv->format_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500401 GLOBAL_STATE_CODE();
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100402 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000403}
bellardb3380822004-03-14 21:38:54 +0000404
Markus Armbrustere4e99862014-10-07 13:59:03 +0200405BlockDriverState *bdrv_new(void)
406{
407 BlockDriverState *bs;
408 int i;
409
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500410 GLOBAL_STATE_CODE();
411
Markus Armbruster5839e532014-08-19 10:31:08 +0200412 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800413 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800414 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
415 QLIST_INIT(&bs->op_blockers[i]);
416 }
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200417 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200418 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800419 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200420 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200421
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300422 qemu_co_queue_init(&bs->flush_queue);
423
Hanna Reitz0bc329f2021-08-12 10:41:44 +0200424 qemu_co_mutex_init(&bs->bsc_modify_lock);
425 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
426
Kevin Wolf0f122642018-03-28 18:29:18 +0200427 for (i = 0; i < bdrv_drain_all_count; i++) {
428 bdrv_drained_begin(bs);
429 }
430
Max Reitz2c1d04e2016-01-29 16:36:11 +0100431 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
432
bellardb3380822004-03-14 21:38:54 +0000433 return bs;
434}
435
Marc Mari88d88792016-08-12 09:27:03 -0400436static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000437{
438 BlockDriver *drv1;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500439 GLOBAL_STATE_CODE();
Marc Mari88d88792016-08-12 09:27:03 -0400440
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100441 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
442 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000443 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100444 }
bellardea2384d2004-08-01 21:59:26 +0000445 }
Marc Mari88d88792016-08-12 09:27:03 -0400446
bellardea2384d2004-08-01 21:59:26 +0000447 return NULL;
448}
449
Marc Mari88d88792016-08-12 09:27:03 -0400450BlockDriver *bdrv_find_format(const char *format_name)
451{
452 BlockDriver *drv1;
453 int i;
454
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500455 GLOBAL_STATE_CODE();
456
Marc Mari88d88792016-08-12 09:27:03 -0400457 drv1 = bdrv_do_find_format(format_name);
458 if (drv1) {
459 return drv1;
460 }
461
462 /* The driver isn't registered, maybe we need to load a module */
463 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
464 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
465 block_module_load_one(block_driver_modules[i].library_name);
466 break;
467 }
468 }
469
470 return bdrv_do_find_format(format_name);
471}
472
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300473static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100474{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800475 static const char *whitelist_rw[] = {
476 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200477 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800478 };
479 static const char *whitelist_ro[] = {
480 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200481 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100482 };
483 const char **p;
484
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800485 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100486 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800487 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100488
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800489 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300490 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100491 return 1;
492 }
493 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800494 if (read_only) {
495 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300496 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800497 return 1;
498 }
499 }
500 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100501 return 0;
502}
503
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300504int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
505{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500506 GLOBAL_STATE_CODE();
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300507 return bdrv_format_is_whitelisted(drv->format_name, read_only);
508}
509
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000510bool bdrv_uses_whitelist(void)
511{
512 return use_bdrv_whitelist;
513}
514
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800515typedef struct CreateCo {
516 BlockDriver *drv;
517 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800518 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800519 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200520 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800521} CreateCo;
522
523static void coroutine_fn bdrv_create_co_entry(void *opaque)
524{
Max Reitzcc84d902013-09-06 17:14:26 +0200525 Error *local_err = NULL;
526 int ret;
527
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800528 CreateCo *cco = opaque;
529 assert(cco->drv);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -0500530 GLOBAL_STATE_CODE();
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800531
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200532 ret = cco->drv->bdrv_co_create_opts(cco->drv,
533 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300534 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200535 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800536}
537
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200538int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800539 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000540{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800541 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200542
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500543 GLOBAL_STATE_CODE();
544
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800545 Coroutine *co;
546 CreateCo cco = {
547 .drv = drv,
548 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800549 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800550 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200551 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800552 };
553
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100554 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200555 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300556 ret = -ENOTSUP;
557 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800558 }
559
560 if (qemu_in_coroutine()) {
561 /* Fast-path if already in coroutine context */
562 bdrv_create_co_entry(&cco);
563 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200564 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
565 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800566 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200567 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800568 }
569 }
570
571 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200572 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100573 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200574 error_propagate(errp, cco.err);
575 } else {
576 error_setg_errno(errp, -ret, "Could not create image");
577 }
578 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800579
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300580out:
581 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800582 return ret;
bellardea2384d2004-08-01 21:59:26 +0000583}
584
Max Reitzfd171462020-01-22 17:45:29 +0100585/**
586 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
587 * least the given @minimum_size.
588 *
589 * On success, return @blk's actual length.
590 * Otherwise, return -errno.
591 */
592static int64_t create_file_fallback_truncate(BlockBackend *blk,
593 int64_t minimum_size, Error **errp)
594{
595 Error *local_err = NULL;
596 int64_t size;
597 int ret;
598
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500599 GLOBAL_STATE_CODE();
600
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200601 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
602 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100603 if (ret < 0 && ret != -ENOTSUP) {
604 error_propagate(errp, local_err);
605 return ret;
606 }
607
608 size = blk_getlength(blk);
609 if (size < 0) {
610 error_free(local_err);
611 error_setg_errno(errp, -size,
612 "Failed to inquire the new image file's length");
613 return size;
614 }
615
616 if (size < minimum_size) {
617 /* Need to grow the image, but we failed to do that */
618 error_propagate(errp, local_err);
619 return -ENOTSUP;
620 }
621
622 error_free(local_err);
623 local_err = NULL;
624
625 return size;
626}
627
628/**
629 * Helper function for bdrv_create_file_fallback(): Zero the first
630 * sector to remove any potentially pre-existing image header.
631 */
Paolo Bonzini881a4c52022-09-22 10:49:00 +0200632static int coroutine_fn
633create_file_fallback_zero_first_sector(BlockBackend *blk,
634 int64_t current_size,
635 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100636{
637 int64_t bytes_to_clear;
638 int ret;
639
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500640 GLOBAL_STATE_CODE();
641
Max Reitzfd171462020-01-22 17:45:29 +0100642 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
643 if (bytes_to_clear) {
644 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
645 if (ret < 0) {
646 error_setg_errno(errp, -ret,
647 "Failed to clear the new image's first sector");
648 return ret;
649 }
650 }
651
652 return 0;
653}
654
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200655/**
656 * Simple implementation of bdrv_co_create_opts for protocol drivers
657 * which only support creation via opening a file
658 * (usually existing raw storage device)
659 */
660int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
661 const char *filename,
662 QemuOpts *opts,
663 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100664{
665 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100666 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100667 int64_t size = 0;
668 char *buf = NULL;
669 PreallocMode prealloc;
670 Error *local_err = NULL;
671 int ret;
672
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -0500673 GLOBAL_STATE_CODE();
674
Max Reitzfd171462020-01-22 17:45:29 +0100675 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
676 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
677 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
678 PREALLOC_MODE_OFF, &local_err);
679 g_free(buf);
680 if (local_err) {
681 error_propagate(errp, local_err);
682 return -EINVAL;
683 }
684
685 if (prealloc != PREALLOC_MODE_OFF) {
686 error_setg(errp, "Unsupported preallocation mode '%s'",
687 PreallocMode_str(prealloc));
688 return -ENOTSUP;
689 }
690
Max Reitzeeea1fa2020-02-25 16:56:18 +0100691 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100692 qdict_put_str(options, "driver", drv->format_name);
693
694 blk = blk_new_open(filename, NULL, options,
695 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
696 if (!blk) {
697 error_prepend(errp, "Protocol driver '%s' does not support image "
698 "creation, and opening the image failed: ",
699 drv->format_name);
700 return -EINVAL;
701 }
702
703 size = create_file_fallback_truncate(blk, size, errp);
704 if (size < 0) {
705 ret = size;
706 goto out;
707 }
708
709 ret = create_file_fallback_zero_first_sector(blk, size, errp);
710 if (ret < 0) {
711 goto out;
712 }
713
714 ret = 0;
715out:
716 blk_unref(blk);
717 return ret;
718}
719
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800720int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200721{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100722 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200723 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100724 QDict *qdict;
725 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200726
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500727 GLOBAL_STATE_CODE();
728
Max Reitzb65a5e12015-02-05 13:58:12 -0500729 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200730 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000731 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200732 }
733
Stefano Garzarella729222a2021-03-08 17:12:32 +0100734 if (!drv->create_opts) {
735 error_setg(errp, "Driver '%s' does not support image creation",
736 drv->format_name);
737 return -ENOTSUP;
738 }
739
740 /*
741 * 'opts' contains a QemuOptsList with a combination of format and protocol
742 * default values.
743 *
744 * The format properly removes its options, but the default values remain
745 * in 'opts->list'. So if the protocol has options with the same name
746 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
747 * of the format, since for overlapping options, the format wins.
748 *
749 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
750 * only the set options, and then convert it back to QemuOpts, using the
751 * create_opts of the protocol. So the new QemuOpts, will contain only the
752 * protocol defaults.
753 */
754 qdict = qemu_opts_to_qdict(opts, NULL);
755 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
756 if (protocol_opts == NULL) {
757 ret = -EINVAL;
758 goto out;
759 }
760
761 ret = bdrv_create(drv, filename, protocol_opts, errp);
762out:
763 qemu_opts_del(protocol_opts);
764 qobject_unref(qdict);
765 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200766}
767
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300768int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
769{
770 Error *local_err = NULL;
771 int ret;
772
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500773 IO_CODE();
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300774 assert(bs != NULL);
775
776 if (!bs->drv) {
777 error_setg(errp, "Block node '%s' is not opened", bs->filename);
778 return -ENOMEDIUM;
779 }
780
781 if (!bs->drv->bdrv_co_delete_file) {
782 error_setg(errp, "Driver '%s' does not support image deletion",
783 bs->drv->format_name);
784 return -ENOTSUP;
785 }
786
787 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
788 if (ret < 0) {
789 error_propagate(errp, local_err);
790 }
791
792 return ret;
793}
794
Maxim Levitskya890f082020-12-17 19:09:03 +0200795void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
796{
797 Error *local_err = NULL;
798 int ret;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500799 IO_CODE();
Maxim Levitskya890f082020-12-17 19:09:03 +0200800
801 if (!bs) {
802 return;
803 }
804
805 ret = bdrv_co_delete_file(bs, &local_err);
806 /*
807 * ENOTSUP will happen if the block driver doesn't support
808 * the 'bdrv_co_delete_file' interface. This is a predictable
809 * scenario and shouldn't be reported back to the user.
810 */
811 if (ret == -ENOTSUP) {
812 error_free(local_err);
813 } else if (ret < 0) {
814 error_report_err(local_err);
815 }
816}
817
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100818/**
819 * Try to get @bs's logical and physical block size.
820 * On success, store them in @bsz struct and return 0.
821 * On failure return -errno.
822 * @bs must not be empty.
823 */
824int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
825{
826 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200827 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500828 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100829
830 if (drv && drv->bdrv_probe_blocksizes) {
831 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200832 } else if (filtered) {
833 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100834 }
835
836 return -ENOTSUP;
837}
838
839/**
840 * Try to get @bs's geometry (cyls, heads, sectors).
841 * On success, store them in @geo struct and return 0.
842 * On failure return -errno.
843 * @bs must not be empty.
844 */
845int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
846{
847 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200848 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500849 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100850
851 if (drv && drv->bdrv_probe_geometry) {
852 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200853 } else if (filtered) {
854 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100855 }
856
857 return -ENOTSUP;
858}
859
Jim Meyeringeba25052012-05-28 09:27:54 +0200860/*
861 * Create a uniquely-named empty temporary file.
Bin Meng69fbfff2022-10-10 12:04:31 +0800862 * Return the actual file name used upon success, otherwise NULL.
863 * This string should be freed with g_free() when not needed any longer.
864 *
865 * Note: creating a temporary file for the caller to (re)open is
866 * inherently racy. Use g_file_open_tmp() instead whenever practical.
Jim Meyeringeba25052012-05-28 09:27:54 +0200867 */
Bin Meng69fbfff2022-10-10 12:04:31 +0800868char *create_tmp_file(Error **errp)
Jim Meyeringeba25052012-05-28 09:27:54 +0200869{
bellardea2384d2004-08-01 21:59:26 +0000870 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000871 const char *tmpdir;
Bin Meng69fbfff2022-10-10 12:04:31 +0800872 g_autofree char *filename = NULL;
873
874 tmpdir = g_get_tmp_dir();
875#ifndef _WIN32
876 /*
877 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
878 *
879 * This function is used to create temporary disk images (like -snapshot),
880 * so the files can become very large. /tmp is often a tmpfs where as
881 * /var/tmp is usually on a disk, so more appropriate for disk images.
882 */
883 if (!g_strcmp0(tmpdir, "/tmp")) {
Amit Shah69bef792014-02-26 15:12:37 +0530884 tmpdir = "/var/tmp";
885 }
Bin Meng69fbfff2022-10-10 12:04:31 +0800886#endif
887
888 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
889 fd = g_mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800890 if (fd < 0) {
Bin Meng69fbfff2022-10-10 12:04:31 +0800891 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
892 filename);
893 return NULL;
Dunrong Huangfe235a02012-09-05 21:26:22 +0800894 }
Bin Meng6b6471e2022-10-10 12:04:30 +0800895 close(fd);
Bin Meng69fbfff2022-10-10 12:04:31 +0800896
897 return g_steal_pointer(&filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200898}
bellardea2384d2004-08-01 21:59:26 +0000899
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200900/*
901 * Detect host devices. By convention, /dev/cdrom[N] is always
902 * recognized as a host CDROM.
903 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200904static BlockDriver *find_hdev_driver(const char *filename)
905{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200906 int score_max = 0, score;
907 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500908 GLOBAL_STATE_CODE();
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200909
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100910 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200911 if (d->bdrv_probe_device) {
912 score = d->bdrv_probe_device(filename);
913 if (score > score_max) {
914 score_max = score;
915 drv = d;
916 }
917 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200918 }
919
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200920 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200921}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200922
Marc Mari88d88792016-08-12 09:27:03 -0400923static BlockDriver *bdrv_do_find_protocol(const char *protocol)
924{
925 BlockDriver *drv1;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500926 GLOBAL_STATE_CODE();
Marc Mari88d88792016-08-12 09:27:03 -0400927
928 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
929 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
930 return drv1;
931 }
932 }
933
934 return NULL;
935}
936
Kevin Wolf98289622013-07-10 15:47:39 +0200937BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500938 bool allow_protocol_prefix,
939 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200940{
941 BlockDriver *drv1;
942 char protocol[128];
943 int len;
944 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400945 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200946
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500947 GLOBAL_STATE_CODE();
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200948 /* TODO Drivers without bdrv_file_open must be specified explicitly */
949
Christoph Hellwig39508e72010-06-23 12:25:17 +0200950 /*
951 * XXX(hch): we really should not let host device detection
952 * override an explicit protocol specification, but moving this
953 * later breaks access to device names with colons in them.
954 * Thanks to the brain-dead persistent naming schemes on udev-
955 * based Linux systems those actually are quite common.
956 */
957 drv1 = find_hdev_driver(filename);
958 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200959 return drv1;
960 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200961
Kevin Wolf98289622013-07-10 15:47:39 +0200962 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100963 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200964 }
Kevin Wolf98289622013-07-10 15:47:39 +0200965
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000966 p = strchr(filename, ':');
967 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200968 len = p - filename;
969 if (len > sizeof(protocol) - 1)
970 len = sizeof(protocol) - 1;
971 memcpy(protocol, filename, len);
972 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400973
974 drv1 = bdrv_do_find_protocol(protocol);
975 if (drv1) {
976 return drv1;
977 }
978
979 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
980 if (block_driver_modules[i].protocol_name &&
981 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
982 block_module_load_one(block_driver_modules[i].library_name);
983 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200984 }
985 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500986
Marc Mari88d88792016-08-12 09:27:03 -0400987 drv1 = bdrv_do_find_protocol(protocol);
988 if (!drv1) {
989 error_setg(errp, "Unknown protocol '%s'", protocol);
990 }
991 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200992}
993
Markus Armbrusterc6684242014-11-20 16:27:10 +0100994/*
995 * Guess image format by probing its contents.
996 * This is not a good idea when your image is raw (CVE-2008-2004), but
997 * we do it anyway for backward compatibility.
998 *
999 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +01001000 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1001 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001002 * @filename is its filename.
1003 *
1004 * For all block drivers, call the bdrv_probe() method to get its
1005 * probing score.
1006 * Return the first block driver with the highest probing score.
1007 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01001008BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1009 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001010{
1011 int score_max = 0, score;
1012 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001013 IO_CODE();
Markus Armbrusterc6684242014-11-20 16:27:10 +01001014
1015 QLIST_FOREACH(d, &bdrv_drivers, list) {
1016 if (d->bdrv_probe) {
1017 score = d->bdrv_probe(buf, buf_size, filename);
1018 if (score > score_max) {
1019 score_max = score;
1020 drv = d;
1021 }
1022 }
1023 }
1024
1025 return drv;
1026}
1027
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001028static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +02001029 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +00001030{
Markus Armbrusterc6684242014-11-20 16:27:10 +01001031 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +01001032 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +01001033 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001034
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001035 GLOBAL_STATE_CODE();
1036
Kevin Wolf08a00552010-06-01 18:37:31 +02001037 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001038 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +01001039 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +02001040 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -07001041 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001042
Alberto Fariaa9262f52022-07-05 17:15:11 +01001043 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
bellard83f64092006-08-01 16:21:11 +00001044 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001045 error_setg_errno(errp, -ret, "Could not read image for determining its "
1046 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +02001047 *pdrv = NULL;
1048 return ret;
bellard83f64092006-08-01 16:21:11 +00001049 }
1050
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001051 drv = bdrv_probe_all(buf, sizeof(buf), filename);
Stefan Weilc98ac352010-07-21 21:51:51 +02001052 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001053 error_setg(errp, "Could not determine image format: No compatible "
1054 "driver found");
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001055 *pdrv = NULL;
1056 return -ENOENT;
Stefan Weilc98ac352010-07-21 21:51:51 +02001057 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001058
Stefan Weilc98ac352010-07-21 21:51:51 +02001059 *pdrv = drv;
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001060 return 0;
bellardea2384d2004-08-01 21:59:26 +00001061}
1062
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001063/**
1064 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001065 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001066 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001067int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001068{
1069 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001070 IO_CODE();
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001071
Max Reitzd470ad42017-11-10 21:31:09 +01001072 if (!drv) {
1073 return -ENOMEDIUM;
1074 }
1075
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001076 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001077 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001078 return 0;
1079
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001080 /* query actual device if possible, otherwise just trust the hint */
1081 if (drv->bdrv_getlength) {
1082 int64_t length = drv->bdrv_getlength(bs);
1083 if (length < 0) {
1084 return length;
1085 }
Fam Zheng7e382002013-11-06 19:48:06 +08001086 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001087 }
1088
1089 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001090
1091 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1092 return -EFBIG;
1093 }
1094
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001095 return 0;
1096}
1097
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001098/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001099 * Combines a QDict of new block driver @options with any missing options taken
1100 * from @old_options, so that leaving out an option defaults to its old value.
1101 */
1102static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1103 QDict *old_options)
1104{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001105 GLOBAL_STATE_CODE();
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001106 if (bs->drv && bs->drv->bdrv_join_options) {
1107 bs->drv->bdrv_join_options(options, old_options);
1108 } else {
1109 qdict_join(options, old_options, false);
1110 }
1111}
1112
Alberto Garcia543770b2018-09-06 12:37:09 +03001113static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1114 int open_flags,
1115 Error **errp)
1116{
1117 Error *local_err = NULL;
1118 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1119 BlockdevDetectZeroesOptions detect_zeroes =
1120 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1121 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001122 GLOBAL_STATE_CODE();
Alberto Garcia543770b2018-09-06 12:37:09 +03001123 g_free(value);
1124 if (local_err) {
1125 error_propagate(errp, local_err);
1126 return detect_zeroes;
1127 }
1128
1129 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1130 !(open_flags & BDRV_O_UNMAP))
1131 {
1132 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1133 "without setting discard operation to unmap");
1134 }
1135
1136 return detect_zeroes;
1137}
1138
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001139/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001140 * Set open flags for aio engine
1141 *
1142 * Return 0 on success, -1 if the engine specified is invalid
1143 */
1144int bdrv_parse_aio(const char *mode, int *flags)
1145{
1146 if (!strcmp(mode, "threads")) {
1147 /* do nothing, default */
1148 } else if (!strcmp(mode, "native")) {
1149 *flags |= BDRV_O_NATIVE_AIO;
1150#ifdef CONFIG_LINUX_IO_URING
1151 } else if (!strcmp(mode, "io_uring")) {
1152 *flags |= BDRV_O_IO_URING;
1153#endif
1154 } else {
1155 return -1;
1156 }
1157
1158 return 0;
1159}
1160
1161/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001162 * Set open flags for a given discard mode
1163 *
1164 * Return 0 on success, -1 if the discard mode was invalid.
1165 */
1166int bdrv_parse_discard_flags(const char *mode, int *flags)
1167{
1168 *flags &= ~BDRV_O_UNMAP;
1169
1170 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1171 /* do nothing */
1172 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1173 *flags |= BDRV_O_UNMAP;
1174 } else {
1175 return -1;
1176 }
1177
1178 return 0;
1179}
1180
1181/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001182 * Set open flags for a given cache mode
1183 *
1184 * Return 0 on success, -1 if the cache mode was invalid.
1185 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001186int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001187{
1188 *flags &= ~BDRV_O_CACHE_MASK;
1189
1190 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001191 *writethrough = false;
1192 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001193 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001194 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001195 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001196 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001197 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001198 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001199 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001200 *flags |= BDRV_O_NO_FLUSH;
1201 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001202 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001203 } else {
1204 return -1;
1205 }
1206
1207 return 0;
1208}
1209
Kevin Wolfb5411552017-01-17 15:56:16 +01001210static char *bdrv_child_get_parent_desc(BdrvChild *c)
1211{
1212 BlockDriverState *parent = c->opaque;
Vladimir Sementsov-Ogievskiy2c0a3ac2021-06-01 10:52:15 +03001213 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
Kevin Wolfb5411552017-01-17 15:56:16 +01001214}
1215
Kevin Wolf20018e12016-05-23 18:46:59 +02001216static void bdrv_child_cb_drained_begin(BdrvChild *child)
1217{
1218 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001219 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001220}
1221
Kevin Wolf89bd0302018-03-22 14:11:20 +01001222static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1223{
1224 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001225 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001226}
1227
Max Reitze037c092019-07-19 11:26:14 +02001228static void bdrv_child_cb_drained_end(BdrvChild *child,
1229 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001230{
1231 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001232 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001233}
1234
Kevin Wolf38701b62017-05-04 18:52:39 +02001235static int bdrv_child_cb_inactivate(BdrvChild *child)
1236{
1237 BlockDriverState *bs = child->opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001238 GLOBAL_STATE_CODE();
Kevin Wolf38701b62017-05-04 18:52:39 +02001239 assert(bs->open_flags & BDRV_O_INACTIVE);
1240 return 0;
1241}
1242
Kevin Wolf5d231842019-05-06 19:17:56 +02001243static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1244 GSList **ignore, Error **errp)
1245{
1246 BlockDriverState *bs = child->opaque;
1247 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1248}
1249
Kevin Wolf53a7d042019-05-06 19:17:59 +02001250static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1251 GSList **ignore)
1252{
1253 BlockDriverState *bs = child->opaque;
1254 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1255}
1256
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001257/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001258 * Returns the options and flags that a temporary snapshot should get, based on
1259 * the originally requested flags (the originally requested image will have
1260 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001261 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001262static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1263 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001264{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001265 GLOBAL_STATE_CODE();
Kevin Wolf73176be2016-03-07 13:02:15 +01001266 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1267
1268 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001269 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1270 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001271
Kevin Wolf3f486862019-04-04 17:04:43 +02001272 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001273 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001274 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001275
Kevin Wolf41869042016-06-16 12:59:30 +02001276 /* aio=native doesn't work for cache.direct=off, so disable it for the
1277 * temporary snapshot */
1278 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001279}
1280
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001281static void bdrv_backing_attach(BdrvChild *c)
1282{
1283 BlockDriverState *parent = c->opaque;
1284 BlockDriverState *backing_hd = c->bs;
1285
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001286 GLOBAL_STATE_CODE();
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001287 assert(!parent->backing_blocker);
1288 error_setg(&parent->backing_blocker,
1289 "node is used as backing hd of '%s'",
1290 bdrv_get_device_or_node_name(parent));
1291
Max Reitzf30c66b2019-02-01 20:29:05 +01001292 bdrv_refresh_filename(backing_hd);
1293
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001294 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001295
1296 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1297 /* Otherwise we won't be able to commit or stream */
1298 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1299 parent->backing_blocker);
1300 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1301 parent->backing_blocker);
1302 /*
1303 * We do backup in 3 ways:
1304 * 1. drive backup
1305 * The target bs is new opened, and the source is top BDS
1306 * 2. blockdev backup
1307 * Both the source and the target are top BDSes.
1308 * 3. internal backup(used for block replication)
1309 * Both the source and the target are backing file
1310 *
1311 * In case 1 and 2, neither the source nor the target is the backing file.
1312 * In case 3, we will block the top BDS, so there is only one block job
1313 * for the top BDS and its backing chain.
1314 */
1315 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1316 parent->backing_blocker);
1317 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1318 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001319}
Kevin Wolfd736f112017-12-18 16:05:48 +01001320
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001321static void bdrv_backing_detach(BdrvChild *c)
1322{
1323 BlockDriverState *parent = c->opaque;
1324
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001325 GLOBAL_STATE_CODE();
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001326 assert(parent->backing_blocker);
1327 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1328 error_free(parent->backing_blocker);
1329 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001330}
Kevin Wolfd736f112017-12-18 16:05:48 +01001331
Kevin Wolf6858eba2017-06-29 19:32:21 +02001332static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1333 const char *filename, Error **errp)
1334{
1335 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001336 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001337 int ret;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001338 GLOBAL_STATE_CODE();
Kevin Wolf6858eba2017-06-29 19:32:21 +02001339
Alberto Garciae94d3db2018-11-12 16:00:34 +02001340 if (read_only) {
1341 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001342 if (ret < 0) {
1343 return ret;
1344 }
1345 }
1346
Kevin Wolf6858eba2017-06-29 19:32:21 +02001347 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001348 base->drv ? base->drv->format_name : "",
1349 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001350 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001351 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001352 }
1353
Alberto Garciae94d3db2018-11-12 16:00:34 +02001354 if (read_only) {
1355 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001356 }
1357
Kevin Wolf6858eba2017-06-29 19:32:21 +02001358 return ret;
1359}
1360
Max Reitzfae8bd32020-05-13 13:05:20 +02001361/*
1362 * Returns the options and flags that a generic child of a BDS should
1363 * get, based on the given options and flags for the parent BDS.
1364 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001365static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1366 int *child_flags, QDict *child_options,
1367 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001368{
1369 int flags = parent_flags;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001370 GLOBAL_STATE_CODE();
Max Reitzfae8bd32020-05-13 13:05:20 +02001371
1372 /*
1373 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1374 * Generally, the question to answer is: Should this child be
1375 * format-probed by default?
1376 */
1377
1378 /*
1379 * Pure and non-filtered data children of non-format nodes should
1380 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1381 * set). This only affects a very limited set of drivers (namely
1382 * quorum and blkverify when this comment was written).
1383 * Force-clear BDRV_O_PROTOCOL then.
1384 */
1385 if (!parent_is_format &&
1386 (role & BDRV_CHILD_DATA) &&
1387 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1388 {
1389 flags &= ~BDRV_O_PROTOCOL;
1390 }
1391
1392 /*
1393 * All children of format nodes (except for COW children) and all
1394 * metadata children in general should never be format-probed.
1395 * Force-set BDRV_O_PROTOCOL then.
1396 */
1397 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1398 (role & BDRV_CHILD_METADATA))
1399 {
1400 flags |= BDRV_O_PROTOCOL;
1401 }
1402
1403 /*
1404 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1405 * the parent.
1406 */
1407 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1408 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1409 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1410
1411 if (role & BDRV_CHILD_COW) {
1412 /* backing files are opened read-only by default */
1413 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1414 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1415 } else {
1416 /* Inherit the read-only option from the parent if it's not set */
1417 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1418 qdict_copy_default(child_options, parent_options,
1419 BDRV_OPT_AUTO_READ_ONLY);
1420 }
1421
1422 /*
1423 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1424 * can default to enable it on lower layers regardless of the
1425 * parent option.
1426 */
1427 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1428
1429 /* Clear flags that only apply to the top layer */
1430 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1431
1432 if (role & BDRV_CHILD_METADATA) {
1433 flags &= ~BDRV_O_NO_IO;
1434 }
1435 if (role & BDRV_CHILD_COW) {
1436 flags &= ~BDRV_O_TEMPORARY;
1437 }
1438
1439 *child_flags = flags;
1440}
1441
Max Reitzca2f1232020-05-13 13:05:22 +02001442static void bdrv_child_cb_attach(BdrvChild *child)
1443{
1444 BlockDriverState *bs = child->opaque;
1445
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05001446 assert_bdrv_graph_writable(bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001447 QLIST_INSERT_HEAD(&bs->children, child, next);
1448
Max Reitzca2f1232020-05-13 13:05:22 +02001449 if (child->role & BDRV_CHILD_COW) {
1450 bdrv_backing_attach(child);
1451 }
1452
1453 bdrv_apply_subtree_drain(child, bs);
1454}
1455
Max Reitz48e08282020-05-13 13:05:23 +02001456static void bdrv_child_cb_detach(BdrvChild *child)
1457{
1458 BlockDriverState *bs = child->opaque;
1459
1460 if (child->role & BDRV_CHILD_COW) {
1461 bdrv_backing_detach(child);
1462 }
1463
1464 bdrv_unapply_subtree_drain(child, bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001465
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05001466 assert_bdrv_graph_writable(bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001467 QLIST_REMOVE(child, next);
Max Reitz48e08282020-05-13 13:05:23 +02001468}
1469
Max Reitz43483552020-05-13 13:05:24 +02001470static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1471 const char *filename, Error **errp)
1472{
1473 if (c->role & BDRV_CHILD_COW) {
1474 return bdrv_backing_update_filename(c, base, filename, errp);
1475 }
1476 return 0;
1477}
1478
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001479AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001480{
1481 BlockDriverState *bs = c->opaque;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05001482 IO_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001483
1484 return bdrv_get_aio_context(bs);
1485}
1486
Max Reitz43483552020-05-13 13:05:24 +02001487const BdrvChildClass child_of_bds = {
1488 .parent_is_bds = true,
1489 .get_parent_desc = bdrv_child_get_parent_desc,
1490 .inherit_options = bdrv_inherited_options,
1491 .drained_begin = bdrv_child_cb_drained_begin,
1492 .drained_poll = bdrv_child_cb_drained_poll,
1493 .drained_end = bdrv_child_cb_drained_end,
1494 .attach = bdrv_child_cb_attach,
1495 .detach = bdrv_child_cb_detach,
1496 .inactivate = bdrv_child_cb_inactivate,
1497 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1498 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1499 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001500 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001501};
1502
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001503AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1504{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05001505 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001506 return c->klass->get_parent_aio_context(c);
1507}
1508
Kevin Wolf7b272452012-11-12 17:05:39 +01001509static int bdrv_open_flags(BlockDriverState *bs, int flags)
1510{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001511 int open_flags = flags;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001512 GLOBAL_STATE_CODE();
Kevin Wolf7b272452012-11-12 17:05:39 +01001513
1514 /*
1515 * Clear flags that are internal to the block layer before opening the
1516 * image.
1517 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001518 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001519
Kevin Wolf7b272452012-11-12 17:05:39 +01001520 return open_flags;
1521}
1522
Kevin Wolf91a097e2015-05-08 17:49:53 +02001523static void update_flags_from_options(int *flags, QemuOpts *opts)
1524{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001525 GLOBAL_STATE_CODE();
1526
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001527 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001528
Alberto Garcia57f9db92018-09-06 12:37:06 +03001529 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001530 *flags |= BDRV_O_NO_FLUSH;
1531 }
1532
Alberto Garcia57f9db92018-09-06 12:37:06 +03001533 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001534 *flags |= BDRV_O_NOCACHE;
1535 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001536
Alberto Garcia57f9db92018-09-06 12:37:06 +03001537 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001538 *flags |= BDRV_O_RDWR;
1539 }
1540
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001541 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1542 *flags |= BDRV_O_AUTO_RDONLY;
1543 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001544}
1545
1546static void update_options_from_flags(QDict *options, int flags)
1547{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001548 GLOBAL_STATE_CODE();
Kevin Wolf91a097e2015-05-08 17:49:53 +02001549 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001550 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001551 }
1552 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001553 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1554 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001555 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001556 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001557 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001558 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001559 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1560 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1561 flags & BDRV_O_AUTO_RDONLY);
1562 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001563}
1564
Kevin Wolf636ea372014-01-24 14:11:52 +01001565static void bdrv_assign_node_name(BlockDriverState *bs,
1566 const char *node_name,
1567 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001568{
Jeff Cody15489c72015-10-12 19:36:50 -04001569 char *gen_node_name = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001570 GLOBAL_STATE_CODE();
Benoît Canet6913c0c2014-01-23 21:31:33 +01001571
Jeff Cody15489c72015-10-12 19:36:50 -04001572 if (!node_name) {
1573 node_name = gen_node_name = id_generate(ID_BLOCK);
1574 } else if (!id_wellformed(node_name)) {
1575 /*
1576 * Check for empty string or invalid characters, but not if it is
1577 * generated (generated names use characters not available to the user)
1578 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001579 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001580 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001581 }
1582
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001583 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001584 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001585 error_setg(errp, "node-name=%s is conflicting with a device id",
1586 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001587 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001588 }
1589
Benoît Canet6913c0c2014-01-23 21:31:33 +01001590 /* takes care of avoiding duplicates node names */
1591 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001592 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001593 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001594 }
1595
Kevin Wolf824808d2018-07-04 13:28:29 +02001596 /* Make sure that the node name isn't truncated */
1597 if (strlen(node_name) >= sizeof(bs->node_name)) {
1598 error_setg(errp, "Node name too long");
1599 goto out;
1600 }
1601
Benoît Canet6913c0c2014-01-23 21:31:33 +01001602 /* copy node name into the bs and insert it into the graph list */
1603 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1604 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001605out:
1606 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001607}
1608
Kevin Wolf01a56502017-01-18 15:51:56 +01001609static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1610 const char *node_name, QDict *options,
1611 int open_flags, Error **errp)
1612{
1613 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001614 int i, ret;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001615 GLOBAL_STATE_CODE();
Kevin Wolf01a56502017-01-18 15:51:56 +01001616
1617 bdrv_assign_node_name(bs, node_name, &local_err);
1618 if (local_err) {
1619 error_propagate(errp, local_err);
1620 return -EINVAL;
1621 }
1622
1623 bs->drv = drv;
1624 bs->opaque = g_malloc0(drv->instance_size);
1625
1626 if (drv->bdrv_file_open) {
1627 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1628 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001629 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001630 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001631 } else {
1632 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001633 }
1634
1635 if (ret < 0) {
1636 if (local_err) {
1637 error_propagate(errp, local_err);
1638 } else if (bs->filename[0]) {
1639 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1640 } else {
1641 error_setg_errno(errp, -ret, "Could not open image");
1642 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001643 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001644 }
1645
1646 ret = refresh_total_sectors(bs, bs->total_sectors);
1647 if (ret < 0) {
1648 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001649 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001650 }
1651
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001652 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001653 if (local_err) {
1654 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001655 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001656 }
1657
1658 assert(bdrv_opt_mem_align(bs) != 0);
1659 assert(bdrv_min_mem_align(bs) != 0);
1660 assert(is_power_of_2(bs->bl.request_alignment));
1661
Kevin Wolf0f122642018-03-28 18:29:18 +02001662 for (i = 0; i < bs->quiesce_counter; i++) {
1663 if (drv->bdrv_co_drain_begin) {
1664 drv->bdrv_co_drain_begin(bs);
1665 }
1666 }
1667
Kevin Wolf01a56502017-01-18 15:51:56 +01001668 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001669open_failed:
1670 bs->drv = NULL;
1671 if (bs->file != NULL) {
1672 bdrv_unref_child(bs, bs->file);
1673 bs->file = NULL;
1674 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001675 g_free(bs->opaque);
1676 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001677 return ret;
1678}
1679
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001680/*
1681 * Create and open a block node.
1682 *
1683 * @options is a QDict of options to pass to the block drivers, or NULL for an
1684 * empty set of options. The reference to the QDict belongs to the block layer
1685 * after the call (even on failure), so if the caller intends to reuse the
1686 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1687 */
1688BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1689 const char *node_name,
1690 QDict *options, int flags,
1691 Error **errp)
Kevin Wolf680c7f92017-01-18 17:16:41 +01001692{
1693 BlockDriverState *bs;
1694 int ret;
1695
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001696 GLOBAL_STATE_CODE();
1697
Kevin Wolf680c7f92017-01-18 17:16:41 +01001698 bs = bdrv_new();
1699 bs->open_flags = flags;
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001700 bs->options = options ?: qdict_new();
1701 bs->explicit_options = qdict_clone_shallow(bs->options);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001702 bs->opaque = NULL;
1703
1704 update_options_from_flags(bs->options, flags);
1705
1706 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1707 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001708 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001709 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001710 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001711 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001712 bdrv_unref(bs);
1713 return NULL;
1714 }
1715
1716 return bs;
1717}
1718
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001719/* Create and open a block node. */
1720BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1721 int flags, Error **errp)
1722{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001723 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001724 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1725}
1726
Kevin Wolfc5f30142016-10-06 11:33:17 +02001727QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001728 .name = "bdrv_common",
1729 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1730 .desc = {
1731 {
1732 .name = "node-name",
1733 .type = QEMU_OPT_STRING,
1734 .help = "Node name of the block device node",
1735 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001736 {
1737 .name = "driver",
1738 .type = QEMU_OPT_STRING,
1739 .help = "Block driver to use for the node",
1740 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001741 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001742 .name = BDRV_OPT_CACHE_DIRECT,
1743 .type = QEMU_OPT_BOOL,
1744 .help = "Bypass software writeback cache on the host",
1745 },
1746 {
1747 .name = BDRV_OPT_CACHE_NO_FLUSH,
1748 .type = QEMU_OPT_BOOL,
1749 .help = "Ignore flush requests",
1750 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001751 {
1752 .name = BDRV_OPT_READ_ONLY,
1753 .type = QEMU_OPT_BOOL,
1754 .help = "Node is opened in read-only mode",
1755 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001756 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001757 .name = BDRV_OPT_AUTO_READ_ONLY,
1758 .type = QEMU_OPT_BOOL,
1759 .help = "Node can become read-only if opening read-write fails",
1760 },
1761 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001762 .name = "detect-zeroes",
1763 .type = QEMU_OPT_STRING,
1764 .help = "try to optimize zero writes (off, on, unmap)",
1765 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001766 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001767 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001768 .type = QEMU_OPT_STRING,
1769 .help = "discard operation (ignore/off, unmap/on)",
1770 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001771 {
1772 .name = BDRV_OPT_FORCE_SHARE,
1773 .type = QEMU_OPT_BOOL,
1774 .help = "always accept other writers (default: off)",
1775 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001776 { /* end of list */ }
1777 },
1778};
1779
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001780QemuOptsList bdrv_create_opts_simple = {
1781 .name = "simple-create-opts",
1782 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001783 .desc = {
1784 {
1785 .name = BLOCK_OPT_SIZE,
1786 .type = QEMU_OPT_SIZE,
1787 .help = "Virtual disk size"
1788 },
1789 {
1790 .name = BLOCK_OPT_PREALLOC,
1791 .type = QEMU_OPT_STRING,
1792 .help = "Preallocation mode (allowed values: off)"
1793 },
1794 { /* end of list */ }
1795 }
1796};
1797
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001798/*
Kevin Wolf57915332010-04-14 15:24:50 +02001799 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001800 *
1801 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001802 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001803static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001804 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001805{
1806 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001807 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001808 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001809 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001810 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001811 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001812 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001813 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001814 bool ro;
Kevin Wolf57915332010-04-14 15:24:50 +02001815
Paolo Bonzini64058752012-05-08 16:51:49 +02001816 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001817 assert(options != NULL && bs->options != options);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001818 GLOBAL_STATE_CODE();
Kevin Wolf57915332010-04-14 15:24:50 +02001819
Kevin Wolf62392eb2015-04-24 16:38:02 +02001820 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001821 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001822 ret = -EINVAL;
1823 goto fail_opts;
1824 }
1825
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001826 update_flags_from_options(&bs->open_flags, opts);
1827
Kevin Wolf62392eb2015-04-24 16:38:02 +02001828 driver_name = qemu_opt_get(opts, "driver");
1829 drv = bdrv_find_format(driver_name);
1830 assert(drv != NULL);
1831
Fam Zheng5a9347c2017-05-03 00:35:37 +08001832 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1833
1834 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1835 error_setg(errp,
1836 BDRV_OPT_FORCE_SHARE
1837 "=on can only be used with read-only images");
1838 ret = -EINVAL;
1839 goto fail_opts;
1840 }
1841
Kevin Wolf45673672013-04-22 17:48:40 +02001842 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001843 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001844 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001845 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001846 /*
1847 * Caution: while qdict_get_try_str() is fine, getting
1848 * non-string types would require more care. When @options
1849 * come from -blockdev or blockdev_add, its members are typed
1850 * according to the QAPI schema, but when they come from
1851 * -drive, they're all QString.
1852 */
Kevin Wolf45673672013-04-22 17:48:40 +02001853 filename = qdict_get_try_str(options, "filename");
1854 }
1855
Max Reitz4a008242017-04-13 18:06:24 +02001856 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001857 error_setg(errp, "The '%s' block driver requires a file name",
1858 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001859 ret = -EINVAL;
1860 goto fail_opts;
1861 }
1862
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001863 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1864 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001865
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001866 ro = bdrv_is_read_only(bs);
1867
1868 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1869 if (!ro && bdrv_is_whitelisted(drv, true)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001870 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1871 } else {
1872 ret = -ENOTSUP;
1873 }
1874 if (ret < 0) {
1875 error_setg(errp,
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001876 !ro && bdrv_is_whitelisted(drv, true)
Kevin Wolf8be25de2019-01-22 13:15:31 +01001877 ? "Driver '%s' can only be used for read-only devices"
1878 : "Driver '%s' is not whitelisted",
1879 drv->format_name);
1880 goto fail_opts;
1881 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001882 }
Kevin Wolf57915332010-04-14 15:24:50 +02001883
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001884 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001885 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001886
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001887 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001888 if (!ro) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001889 bdrv_enable_copy_on_read(bs);
1890 } else {
1891 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001892 ret = -EINVAL;
1893 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001894 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001895 }
1896
Alberto Garcia415bbca2018-10-03 13:23:13 +03001897 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001898 if (discard != NULL) {
1899 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1900 error_setg(errp, "Invalid discard option");
1901 ret = -EINVAL;
1902 goto fail_opts;
1903 }
1904 }
1905
Alberto Garcia543770b2018-09-06 12:37:09 +03001906 bs->detect_zeroes =
1907 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1908 if (local_err) {
1909 error_propagate(errp, local_err);
1910 ret = -EINVAL;
1911 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001912 }
1913
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001914 if (filename != NULL) {
1915 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1916 } else {
1917 bs->filename[0] = '\0';
1918 }
Max Reitz91af7012014-07-18 20:24:56 +02001919 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001920
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001921 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001922 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001923 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001924
Kevin Wolf01a56502017-01-18 15:51:56 +01001925 assert(!drv->bdrv_file_open || file == NULL);
1926 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001927 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001928 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001929 }
1930
Kevin Wolf18edf282015-04-07 17:12:56 +02001931 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001932 return 0;
1933
Kevin Wolf18edf282015-04-07 17:12:56 +02001934fail_opts:
1935 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001936 return ret;
1937}
1938
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001939static QDict *parse_json_filename(const char *filename, Error **errp)
1940{
1941 QObject *options_obj;
1942 QDict *options;
1943 int ret;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001944 GLOBAL_STATE_CODE();
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001945
1946 ret = strstart(filename, "json:", &filename);
1947 assert(ret);
1948
Markus Armbruster5577fff2017-02-28 22:26:59 +01001949 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001950 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001951 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001952 return NULL;
1953 }
1954
Max Reitz7dc847e2018-02-24 16:40:29 +01001955 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001956 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001957 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001958 error_setg(errp, "Invalid JSON object given");
1959 return NULL;
1960 }
1961
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001962 qdict_flatten(options);
1963
1964 return options;
1965}
1966
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001967static void parse_json_protocol(QDict *options, const char **pfilename,
1968 Error **errp)
1969{
1970 QDict *json_options;
1971 Error *local_err = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001972 GLOBAL_STATE_CODE();
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001973
1974 /* Parse json: pseudo-protocol */
1975 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1976 return;
1977 }
1978
1979 json_options = parse_json_filename(*pfilename, &local_err);
1980 if (local_err) {
1981 error_propagate(errp, local_err);
1982 return;
1983 }
1984
1985 /* Options given in the filename have lower priority than options
1986 * specified directly */
1987 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001988 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001989 *pfilename = NULL;
1990}
1991
Kevin Wolf57915332010-04-14 15:24:50 +02001992/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001993 * Fills in default options for opening images and converts the legacy
1994 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001995 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1996 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001997 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001998static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001999 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02002000{
2001 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04002002 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002003 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02002004 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002005 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002006
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002007 GLOBAL_STATE_CODE();
2008
Markus Armbruster129c7d12017-03-30 19:43:12 +02002009 /*
2010 * Caution: while qdict_get_try_str() is fine, getting non-string
2011 * types would require more care. When @options come from
2012 * -blockdev or blockdev_add, its members are typed according to
2013 * the QAPI schema, but when they come from -drive, they're all
2014 * QString.
2015 */
Max Reitz53a29512015-03-19 14:53:16 -04002016 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02002017 if (drvname) {
2018 drv = bdrv_find_format(drvname);
2019 if (!drv) {
2020 error_setg(errp, "Unknown driver '%s'", drvname);
2021 return -ENOENT;
2022 }
2023 /* If the user has explicitly specified the driver, this choice should
2024 * override the BDRV_O_PROTOCOL flag */
2025 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04002026 }
2027
2028 if (protocol) {
2029 *flags |= BDRV_O_PROTOCOL;
2030 } else {
2031 *flags &= ~BDRV_O_PROTOCOL;
2032 }
2033
Kevin Wolf91a097e2015-05-08 17:49:53 +02002034 /* Translate cache options from flags into options */
2035 update_options_from_flags(*options, *flags);
2036
Kevin Wolff54120f2014-05-26 11:09:59 +02002037 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002038 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002039 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002040 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02002041 parse_filename = true;
2042 } else {
2043 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2044 "the same time");
2045 return -EINVAL;
2046 }
2047 }
2048
2049 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02002050 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02002051 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02002052
Max Reitz053e1572015-08-26 19:47:51 +02002053 if (!drvname && protocol) {
2054 if (filename) {
2055 drv = bdrv_find_protocol(filename, parse_filename, errp);
2056 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002057 return -EINVAL;
2058 }
Max Reitz053e1572015-08-26 19:47:51 +02002059
2060 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05002061 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02002062 } else {
2063 error_setg(errp, "Must specify either driver or file");
2064 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002065 }
2066 }
2067
Kevin Wolf17b005f2014-05-27 10:50:29 +02002068 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02002069
2070 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002071 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002072 drv->bdrv_parse_filename(filename, *options, &local_err);
2073 if (local_err) {
2074 error_propagate(errp, local_err);
2075 return -EINVAL;
2076 }
2077
2078 if (!drv->bdrv_needs_filename) {
2079 qdict_del(*options, "filename");
2080 }
2081 }
2082
2083 return 0;
2084}
2085
Kevin Wolf148eb132017-09-14 14:32:04 +02002086typedef struct BlockReopenQueueEntry {
2087 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01002088 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02002089 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002090 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02002091} BlockReopenQueueEntry;
2092
2093/*
2094 * Return the flags that @bs will have after the reopens in @q have
2095 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2096 * return the current flags.
2097 */
2098static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2099{
2100 BlockReopenQueueEntry *entry;
2101
2102 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002103 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002104 if (entry->state.bs == bs) {
2105 return entry->state.flags;
2106 }
2107 }
2108 }
2109
2110 return bs->open_flags;
2111}
2112
2113/* Returns whether the image file can be written to after the reopen queue @q
2114 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002115static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2116 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002117{
2118 int flags = bdrv_reopen_get_flags(q, bs);
2119
2120 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2121}
2122
Max Reitzcc022142018-06-06 21:37:00 +02002123/*
2124 * Return whether the BDS can be written to. This is not necessarily
2125 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2126 * be written to but do not count as read-only images.
2127 */
2128bool bdrv_is_writable(BlockDriverState *bs)
2129{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05002130 IO_CODE();
Max Reitzcc022142018-06-06 21:37:00 +02002131 return bdrv_is_writable_after_reopen(bs, NULL);
2132}
2133
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002134static char *bdrv_child_user_desc(BdrvChild *c)
2135{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002136 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002137 return c->klass->get_parent_desc(c);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002138}
2139
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002140/*
2141 * Check that @a allows everything that @b needs. @a and @b must reference same
2142 * child node.
2143 */
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002144static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2145{
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002146 const char *child_bs_name;
2147 g_autofree char *a_user = NULL;
2148 g_autofree char *b_user = NULL;
2149 g_autofree char *perms = NULL;
2150
2151 assert(a->bs);
2152 assert(a->bs == b->bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002153 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002154
2155 if ((b->perm & a->shared_perm) == b->perm) {
2156 return true;
2157 }
2158
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002159 child_bs_name = bdrv_get_node_name(b->bs);
2160 a_user = bdrv_child_user_desc(a);
2161 b_user = bdrv_child_user_desc(b);
2162 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2163
2164 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2165 "both required by %s (uses node '%s' as '%s' child) and "
2166 "unshared by %s (uses node '%s' as '%s' child).",
2167 child_bs_name, perms,
2168 b_user, child_bs_name, b->name,
2169 a_user, child_bs_name, a->name);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002170
2171 return false;
2172}
2173
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002174static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002175{
2176 BdrvChild *a, *b;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002177 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002178
2179 /*
2180 * During the loop we'll look at each pair twice. That's correct because
2181 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2182 * directions.
2183 */
2184 QLIST_FOREACH(a, &bs->parents, next_parent) {
2185 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002186 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002187 continue;
2188 }
2189
2190 if (!bdrv_a_allow_b(a, b, errp)) {
2191 return true;
2192 }
2193 }
2194 }
2195
2196 return false;
2197}
2198
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002199static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002200 BdrvChild *c, BdrvChildRole role,
2201 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002202 uint64_t parent_perm, uint64_t parent_shared,
2203 uint64_t *nperm, uint64_t *nshared)
2204{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002205 assert(bs->drv && bs->drv->bdrv_child_perm);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002206 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002207 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002208 parent_perm, parent_shared,
2209 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002210 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002211 if (child_bs && child_bs->force_share) {
2212 *nshared = BLK_PERM_ALL;
2213 }
2214}
2215
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002216/*
2217 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2218 * nodes that are already in the @list, of course) so that final list is
2219 * topologically sorted. Return the result (GSList @list object is updated, so
2220 * don't use old reference after function call).
2221 *
2222 * On function start @list must be already topologically sorted and for any node
2223 * in the @list the whole subtree of the node must be in the @list as well. The
2224 * simplest way to satisfy this criteria: use only result of
2225 * bdrv_topological_dfs() or NULL as @list parameter.
2226 */
2227static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2228 BlockDriverState *bs)
2229{
2230 BdrvChild *child;
2231 g_autoptr(GHashTable) local_found = NULL;
2232
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002233 GLOBAL_STATE_CODE();
2234
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002235 if (!found) {
2236 assert(!list);
2237 found = local_found = g_hash_table_new(NULL, NULL);
2238 }
2239
2240 if (g_hash_table_contains(found, bs)) {
2241 return list;
2242 }
2243 g_hash_table_add(found, bs);
2244
2245 QLIST_FOREACH(child, &bs->children, next) {
2246 list = bdrv_topological_dfs(list, found, child->bs);
2247 }
2248
2249 return g_slist_prepend(list, bs);
2250}
2251
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002252typedef struct BdrvChildSetPermState {
2253 BdrvChild *child;
2254 uint64_t old_perm;
2255 uint64_t old_shared_perm;
2256} BdrvChildSetPermState;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002257
2258static void bdrv_child_set_perm_abort(void *opaque)
2259{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002260 BdrvChildSetPermState *s = opaque;
2261
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002262 GLOBAL_STATE_CODE();
2263
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002264 s->child->perm = s->old_perm;
2265 s->child->shared_perm = s->old_shared_perm;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002266}
2267
2268static TransactionActionDrv bdrv_child_set_pem_drv = {
2269 .abort = bdrv_child_set_perm_abort,
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002270 .clean = g_free,
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002271};
2272
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002273static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2274 uint64_t shared, Transaction *tran)
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002275{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002276 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002277 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002278
2279 *s = (BdrvChildSetPermState) {
2280 .child = c,
2281 .old_perm = c->perm,
2282 .old_shared_perm = c->shared_perm,
2283 };
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002284
2285 c->perm = perm;
2286 c->shared_perm = shared;
2287
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002288 tran_add(tran, &bdrv_child_set_pem_drv, s);
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002289}
2290
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002291static void bdrv_drv_set_perm_commit(void *opaque)
2292{
2293 BlockDriverState *bs = opaque;
2294 uint64_t cumulative_perms, cumulative_shared_perms;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002295 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002296
2297 if (bs->drv->bdrv_set_perm) {
2298 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2299 &cumulative_shared_perms);
2300 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2301 }
2302}
2303
2304static void bdrv_drv_set_perm_abort(void *opaque)
2305{
2306 BlockDriverState *bs = opaque;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002307 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002308
2309 if (bs->drv->bdrv_abort_perm_update) {
2310 bs->drv->bdrv_abort_perm_update(bs);
2311 }
2312}
2313
2314TransactionActionDrv bdrv_drv_set_perm_drv = {
2315 .abort = bdrv_drv_set_perm_abort,
2316 .commit = bdrv_drv_set_perm_commit,
2317};
2318
2319static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2320 uint64_t shared_perm, Transaction *tran,
2321 Error **errp)
2322{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002323 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002324 if (!bs->drv) {
2325 return 0;
2326 }
2327
2328 if (bs->drv->bdrv_check_perm) {
2329 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2330 if (ret < 0) {
2331 return ret;
2332 }
2333 }
2334
2335 if (tran) {
2336 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2337 }
2338
2339 return 0;
2340}
2341
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002342typedef struct BdrvReplaceChildState {
2343 BdrvChild *child;
2344 BlockDriverState *old_bs;
2345} BdrvReplaceChildState;
2346
2347static void bdrv_replace_child_commit(void *opaque)
2348{
2349 BdrvReplaceChildState *s = opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002350 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002351
2352 bdrv_unref(s->old_bs);
2353}
2354
2355static void bdrv_replace_child_abort(void *opaque)
2356{
2357 BdrvReplaceChildState *s = opaque;
2358 BlockDriverState *new_bs = s->child->bs;
2359
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002360 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002361 /* old_bs reference is transparently moved from @s to @s->child */
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002362 bdrv_replace_child_noperm(&s->child, s->old_bs);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002363 bdrv_unref(new_bs);
2364}
2365
2366static TransactionActionDrv bdrv_replace_child_drv = {
2367 .commit = bdrv_replace_child_commit,
2368 .abort = bdrv_replace_child_abort,
2369 .clean = g_free,
2370};
2371
2372/*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002373 * bdrv_replace_child_tran
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002374 *
2375 * Note: real unref of old_bs is done only on commit.
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002376 *
2377 * The function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002378 */
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002379static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002380 Transaction *tran)
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002381{
2382 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2383 *s = (BdrvReplaceChildState) {
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002384 .child = child,
2385 .old_bs = child->bs,
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002386 };
2387 tran_add(tran, &bdrv_replace_child_drv, s);
2388
2389 if (new_bs) {
2390 bdrv_ref(new_bs);
2391 }
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002392 bdrv_replace_child_noperm(&child, new_bs);
2393 /* old_bs reference is transparently moved from @child to @s */
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002394}
2395
Kevin Wolf33a610c2016-12-15 13:04:20 +01002396/*
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002397 * Refresh permissions in @bs subtree. The function is intended to be called
2398 * after some graph modification that was done without permission update.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002399 */
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002400static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2401 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002402{
2403 BlockDriver *drv = bs->drv;
2404 BdrvChild *c;
2405 int ret;
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002406 uint64_t cumulative_perms, cumulative_shared_perms;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002407 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002408
2409 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002410
2411 /* Write permissions never work with read-only images */
2412 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002413 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002414 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002415 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2416 error_setg(errp, "Block node is read-only");
2417 } else {
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002418 error_setg(errp, "Read-only block node '%s' cannot support "
2419 "read-write users", bdrv_get_node_name(bs));
Max Reitz481e0ee2019-05-15 22:15:00 +02002420 }
2421
Kevin Wolf33a610c2016-12-15 13:04:20 +01002422 return -EPERM;
2423 }
2424
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002425 /*
2426 * Unaligned requests will automatically be aligned to bl.request_alignment
2427 * and without RESIZE we can't extend requests to write to space beyond the
2428 * end of the image, so it's required that the image size is aligned.
2429 */
2430 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2431 !(cumulative_perms & BLK_PERM_RESIZE))
2432 {
2433 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2434 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2435 "Image size is not a multiple of request "
2436 "alignment");
2437 return -EPERM;
2438 }
2439 }
2440
Kevin Wolf33a610c2016-12-15 13:04:20 +01002441 /* Check this node */
2442 if (!drv) {
2443 return 0;
2444 }
2445
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002446 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002447 errp);
2448 if (ret < 0) {
2449 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002450 }
2451
Kevin Wolf78e421c2016-12-20 23:25:12 +01002452 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002453 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002454 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002455 return 0;
2456 }
2457
2458 /* Check all children */
2459 QLIST_FOREACH(c, &bs->children, next) {
2460 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002461
Max Reitze5d8a402020-05-13 13:05:44 +02002462 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002463 cumulative_perms, cumulative_shared_perms,
2464 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002465 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002466 }
2467
2468 return 0;
2469}
2470
Vladimir Sementsov-Ogievskiy25409802021-04-28 18:18:00 +03002471static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2472 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002473{
2474 int ret;
2475 BlockDriverState *bs;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002476 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002477
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002478 for ( ; list; list = list->next) {
2479 bs = list->data;
2480
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002481 if (bdrv_parent_perms_conflict(bs, errp)) {
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002482 return -EINVAL;
2483 }
2484
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002485 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002486 if (ret < 0) {
2487 return ret;
2488 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002489 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002490
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002491 return 0;
2492}
2493
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002494void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2495 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002496{
2497 BdrvChild *c;
2498 uint64_t cumulative_perms = 0;
2499 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2500
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002501 GLOBAL_STATE_CODE();
2502
Kevin Wolf33a610c2016-12-15 13:04:20 +01002503 QLIST_FOREACH(c, &bs->parents, next_parent) {
2504 cumulative_perms |= c->perm;
2505 cumulative_shared_perms &= c->shared_perm;
2506 }
2507
2508 *perm = cumulative_perms;
2509 *shared_perm = cumulative_shared_perms;
2510}
2511
Fam Zheng51761962017-05-03 00:35:36 +08002512char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002513{
2514 struct perm_name {
2515 uint64_t perm;
2516 const char *name;
2517 } permissions[] = {
2518 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2519 { BLK_PERM_WRITE, "write" },
2520 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2521 { BLK_PERM_RESIZE, "resize" },
Kevin Wolfd0833192017-01-16 18:26:20 +01002522 { 0, NULL }
2523 };
2524
Alberto Garciae2a74232020-01-10 18:15:18 +01002525 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002526 struct perm_name *p;
2527
2528 for (p = permissions; p->name; p++) {
2529 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002530 if (result->len > 0) {
2531 g_string_append(result, ", ");
2532 }
2533 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002534 }
2535 }
2536
Alberto Garciae2a74232020-01-10 18:15:18 +01002537 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002538}
2539
Kevin Wolf33a610c2016-12-15 13:04:20 +01002540
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002541static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002542{
2543 int ret;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002544 Transaction *tran = tran_new();
2545 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002546 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002547
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002548 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2549 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002550
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002551 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002552}
2553
Kevin Wolf33a610c2016-12-15 13:04:20 +01002554int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2555 Error **errp)
2556{
Max Reitz10467792019-05-22 19:03:51 +02002557 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002558 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002559 int ret;
2560
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002561 GLOBAL_STATE_CODE();
2562
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002563 bdrv_child_set_perm(c, perm, shared, tran);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002564
2565 ret = bdrv_refresh_perms(c->bs, &local_err);
2566
2567 tran_finalize(tran, ret);
2568
Kevin Wolf33a610c2016-12-15 13:04:20 +01002569 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002570 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2571 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002572 error_propagate(errp, local_err);
2573 } else {
2574 /*
2575 * Our caller may intend to only loosen restrictions and
2576 * does not expect this function to fail. Errors are not
2577 * fatal in such a case, so we can just hide them from our
2578 * caller.
2579 */
2580 error_free(local_err);
2581 ret = 0;
2582 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002583 }
2584
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002585 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002586}
2587
Max Reitzc1087f12019-05-22 19:03:46 +02002588int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2589{
2590 uint64_t parent_perms, parent_shared;
2591 uint64_t perms, shared;
2592
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002593 GLOBAL_STATE_CODE();
2594
Max Reitzc1087f12019-05-22 19:03:46 +02002595 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002596 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002597 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002598
2599 return bdrv_child_try_set_perm(c, perms, shared, errp);
2600}
2601
Max Reitz87278af2020-05-13 13:05:40 +02002602/*
2603 * Default implementation for .bdrv_child_perm() for block filters:
2604 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2605 * filtered child.
2606 */
2607static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002608 BdrvChildRole role,
2609 BlockReopenQueue *reopen_queue,
2610 uint64_t perm, uint64_t shared,
2611 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002612{
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002613 GLOBAL_STATE_CODE();
Kevin Wolfe444fa82019-08-02 15:59:41 +02002614 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2615 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002616}
2617
Max Reitz70082db2020-05-13 13:05:26 +02002618static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002619 BdrvChildRole role,
2620 BlockReopenQueue *reopen_queue,
2621 uint64_t perm, uint64_t shared,
2622 uint64_t *nperm, uint64_t *nshared)
2623{
Max Reitze5d8a402020-05-13 13:05:44 +02002624 assert(role & BDRV_CHILD_COW);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002625 GLOBAL_STATE_CODE();
Max Reitz70082db2020-05-13 13:05:26 +02002626
2627 /*
2628 * We want consistent read from backing files if the parent needs it.
2629 * No other operations are performed on backing files.
2630 */
2631 perm &= BLK_PERM_CONSISTENT_READ;
2632
2633 /*
2634 * If the parent can deal with changing data, we're okay with a
2635 * writable and resizable backing file.
2636 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2637 */
2638 if (shared & BLK_PERM_WRITE) {
2639 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2640 } else {
2641 shared = 0;
2642 }
2643
Vladimir Sementsov-Ogievskiy64631f32021-09-02 12:37:54 +03002644 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
Max Reitz70082db2020-05-13 13:05:26 +02002645
2646 if (bs->open_flags & BDRV_O_INACTIVE) {
2647 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2648 }
2649
2650 *nperm = perm;
2651 *nshared = shared;
2652}
2653
Max Reitz6f838a42020-05-13 13:05:27 +02002654static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002655 BdrvChildRole role,
2656 BlockReopenQueue *reopen_queue,
2657 uint64_t perm, uint64_t shared,
2658 uint64_t *nperm, uint64_t *nshared)
2659{
2660 int flags;
2661
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002662 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002663 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002664
2665 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2666
2667 /*
2668 * Apart from the modifications below, the same permissions are
2669 * forwarded and left alone as for filters
2670 */
Max Reitze5d8a402020-05-13 13:05:44 +02002671 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002672 perm, shared, &perm, &shared);
2673
Max Reitzf8890542020-05-13 13:05:28 +02002674 if (role & BDRV_CHILD_METADATA) {
2675 /* Format drivers may touch metadata even if the guest doesn't write */
2676 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2677 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2678 }
2679
2680 /*
2681 * bs->file always needs to be consistent because of the
2682 * metadata. We can never allow other users to resize or write
2683 * to it.
2684 */
2685 if (!(flags & BDRV_O_NO_IO)) {
2686 perm |= BLK_PERM_CONSISTENT_READ;
2687 }
2688 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002689 }
2690
Max Reitzf8890542020-05-13 13:05:28 +02002691 if (role & BDRV_CHILD_DATA) {
2692 /*
2693 * Technically, everything in this block is a subset of the
2694 * BDRV_CHILD_METADATA path taken above, and so this could
2695 * be an "else if" branch. However, that is not obvious, and
2696 * this function is not performance critical, therefore we let
2697 * this be an independent "if".
2698 */
2699
2700 /*
2701 * We cannot allow other users to resize the file because the
2702 * format driver might have some assumptions about the size
2703 * (e.g. because it is stored in metadata, or because the file
2704 * is split into fixed-size data files).
2705 */
2706 shared &= ~BLK_PERM_RESIZE;
2707
2708 /*
2709 * WRITE_UNCHANGED often cannot be performed as such on the
2710 * data file. For example, the qcow2 driver may still need to
2711 * write copied clusters on copy-on-read.
2712 */
2713 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2714 perm |= BLK_PERM_WRITE;
2715 }
2716
2717 /*
2718 * If the data file is written to, the format driver may
2719 * expect to be able to resize it by writing beyond the EOF.
2720 */
2721 if (perm & BLK_PERM_WRITE) {
2722 perm |= BLK_PERM_RESIZE;
2723 }
Max Reitz6f838a42020-05-13 13:05:27 +02002724 }
Max Reitz6f838a42020-05-13 13:05:27 +02002725
2726 if (bs->open_flags & BDRV_O_INACTIVE) {
2727 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2728 }
2729
2730 *nperm = perm;
2731 *nshared = shared;
2732}
2733
Max Reitz2519f542020-05-13 13:05:29 +02002734void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002735 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002736 uint64_t perm, uint64_t shared,
2737 uint64_t *nperm, uint64_t *nshared)
2738{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002739 GLOBAL_STATE_CODE();
Max Reitz2519f542020-05-13 13:05:29 +02002740 if (role & BDRV_CHILD_FILTERED) {
2741 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2742 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002743 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002744 perm, shared, nperm, nshared);
2745 } else if (role & BDRV_CHILD_COW) {
2746 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002747 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002748 perm, shared, nperm, nshared);
2749 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002750 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002751 perm, shared, nperm, nshared);
2752 } else {
2753 g_assert_not_reached();
2754 }
2755}
2756
Max Reitz7b1d9c42019-11-08 13:34:51 +01002757uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2758{
2759 static const uint64_t permissions[] = {
2760 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2761 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2762 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2763 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
Max Reitz7b1d9c42019-11-08 13:34:51 +01002764 };
2765
2766 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2767 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2768
2769 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2770
2771 return permissions[qapi_perm];
2772}
2773
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002774static void bdrv_replace_child_noperm(BdrvChild **childp,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002775 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002776{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002777 BdrvChild *child = *childp;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002778 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002779 int new_bs_quiesce_counter;
2780 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002781
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002782 assert(!child->frozen);
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02002783 assert(old_bs != new_bs);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002784 GLOBAL_STATE_CODE();
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002785
Fam Zhengbb2614e2017-04-07 14:54:10 +08002786 if (old_bs && new_bs) {
2787 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2788 }
Max Reitzdebc2922019-07-22 15:33:44 +02002789
2790 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2791 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2792
2793 /*
2794 * If the new child node is drained but the old one was not, flush
2795 * all outstanding requests to the old child node.
2796 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002797 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002798 bdrv_parent_drained_begin_single(child, true);
2799 drain_saldo--;
2800 }
2801
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002802 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002803 /* Detach first so that the recursive drain sections coming from @child
2804 * are already gone and we only end the drain sections that came from
2805 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002806 if (child->klass->detach) {
2807 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002808 }
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002809 assert_bdrv_graph_writable(old_bs);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002810 QLIST_REMOVE(child, next_parent);
2811 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002812
2813 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002814
2815 if (new_bs) {
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002816 assert_bdrv_graph_writable(new_bs);
Kevin Wolf36fe1332016-05-17 14:51:55 +02002817 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002818
2819 /*
2820 * Detaching the old node may have led to the new node's
2821 * quiesce_counter having been decreased. Not a problem, we
2822 * just need to recognize this here and then invoke
2823 * drained_end appropriately more often.
2824 */
2825 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2826 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002827
Kevin Wolfd736f112017-12-18 16:05:48 +01002828 /* Attach only after starting new drained sections, so that recursive
2829 * drain sections coming from @child don't get an extra .drained_begin
2830 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002831 if (child->klass->attach) {
2832 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002833 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002834 }
Max Reitzdebc2922019-07-22 15:33:44 +02002835
2836 /*
2837 * If the old child node was drained but the new one is not, allow
2838 * requests to come in only after the new node has been attached.
2839 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002840 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002841 bdrv_parent_drained_end_single(child);
2842 drain_saldo++;
2843 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002844}
2845
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002846/**
2847 * Free the given @child.
2848 *
2849 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2850 * unused (i.e. not in a children list).
2851 */
2852static void bdrv_child_free(BdrvChild *child)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002853{
2854 assert(!child->bs);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002855 GLOBAL_STATE_CODE();
Hanna Reitza2253692021-11-15 15:53:58 +01002856 assert(!child->next.le_prev); /* not in children list */
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002857
2858 g_free(child->name);
2859 g_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002860}
2861
2862typedef struct BdrvAttachChildCommonState {
2863 BdrvChild **child;
2864 AioContext *old_parent_ctx;
2865 AioContext *old_child_ctx;
2866} BdrvAttachChildCommonState;
2867
2868static void bdrv_attach_child_common_abort(void *opaque)
2869{
2870 BdrvAttachChildCommonState *s = opaque;
2871 BdrvChild *child = *s->child;
2872 BlockDriverState *bs = child->bs;
2873
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002874 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002875 bdrv_replace_child_noperm(s->child, NULL);
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-Ogievskiy4eba8252022-07-26 23:11:28 +03002897 *s->child = NULL;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002898}
2899
2900static TransactionActionDrv bdrv_attach_child_common_drv = {
2901 .abort = bdrv_attach_child_common_abort,
2902 .clean = g_free,
2903};
2904
2905/*
2906 * Common part of attaching bdrv child to bs or to blk or to job
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002907 *
2908 * Resulting new child is returned through @child.
2909 * At start *@child must be NULL.
2910 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2911 * NULL on abort(). So referenced variable must live at least until transaction
2912 * end.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002913 *
2914 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002915 */
2916static int bdrv_attach_child_common(BlockDriverState *child_bs,
2917 const char *child_name,
2918 const BdrvChildClass *child_class,
2919 BdrvChildRole child_role,
2920 uint64_t perm, uint64_t shared_perm,
2921 void *opaque, BdrvChild **child,
2922 Transaction *tran, Error **errp)
2923{
2924 BdrvChild *new_child;
2925 AioContext *parent_ctx;
2926 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2927
2928 assert(child);
2929 assert(*child == NULL);
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002930 assert(child_class->get_parent_desc);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002931 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002932
2933 new_child = g_new(BdrvChild, 1);
2934 *new_child = (BdrvChild) {
2935 .bs = NULL,
2936 .name = g_strdup(child_name),
2937 .klass = child_class,
2938 .role = child_role,
2939 .perm = perm,
2940 .shared_perm = shared_perm,
2941 .opaque = opaque,
2942 };
2943
2944 /*
2945 * If the AioContexts don't match, first try to move the subtree of
2946 * child_bs into the AioContext of the new parent. If this doesn't work,
2947 * try moving the parent into the AioContext of child_bs instead.
2948 */
2949 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2950 if (child_ctx != parent_ctx) {
2951 Error *local_err = NULL;
2952 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2953
2954 if (ret < 0 && child_class->can_set_aio_ctx) {
2955 GSList *ignore = g_slist_prepend(NULL, new_child);
2956 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2957 NULL))
2958 {
2959 error_free(local_err);
2960 ret = 0;
2961 g_slist_free(ignore);
2962 ignore = g_slist_prepend(NULL, new_child);
2963 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2964 }
2965 g_slist_free(ignore);
2966 }
2967
2968 if (ret < 0) {
2969 error_propagate(errp, local_err);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002970 bdrv_child_free(new_child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002971 return ret;
2972 }
2973 }
2974
2975 bdrv_ref(child_bs);
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002976 bdrv_replace_child_noperm(&new_child, child_bs);
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);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003010 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003011
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02003012 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3013 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3014 child_bs->node_name, child_name, parent_bs->node_name);
3015 return -EINVAL;
3016 }
3017
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003018 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3019 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3020 perm, shared_perm, &perm, &shared_perm);
3021
3022 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3023 child_role, perm, shared_perm, parent_bs,
3024 child, tran, errp);
3025 if (ret < 0) {
3026 return ret;
3027 }
3028
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003029 return 0;
3030}
3031
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003032static void bdrv_detach_child(BdrvChild **childp)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003033{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003034 BlockDriverState *old_bs = (*childp)->bs;
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003035
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003036 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03003037 bdrv_replace_child_noperm(childp, NULL);
3038 bdrv_child_free(*childp);
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003039
3040 if (old_bs) {
3041 /*
3042 * Update permissions for old node. We're just taking a parent away, so
3043 * we're loosening restrictions. Errors of permission update are not
3044 * fatal in this case, ignore them.
3045 */
3046 bdrv_refresh_perms(old_bs, NULL);
3047
3048 /*
3049 * When the parent requiring a non-default AioContext is removed, the
3050 * node moves back to the main AioContext
3051 */
3052 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3053 }
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003054}
3055
Alberto Garciab441dc72019-05-13 16:46:18 +03003056/*
3057 * This function steals the reference to child_bs from the caller.
3058 * That reference is later dropped by bdrv_root_unref_child().
3059 *
3060 * On failure NULL is returned, errp is set and the reference to
3061 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003062 *
3063 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3064 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003065 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003066BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3067 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003068 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003069 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003070 uint64_t perm, uint64_t shared_perm,
3071 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003072{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003073 int ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003074 BdrvChild *child = NULL;
3075 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003076
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05003077 GLOBAL_STATE_CODE();
3078
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003079 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3080 child_role, perm, shared_perm, opaque,
3081 &child, tran, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003082 if (ret < 0) {
Kevin Wolfe878bb12021-05-03 13:05:54 +02003083 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003084 }
3085
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003086 ret = bdrv_refresh_perms(child_bs, errp);
Kevin Wolfdf581792015-06-15 11:53:47 +02003087
Kevin Wolfe878bb12021-05-03 13:05:54 +02003088out:
3089 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003090 /* child is unset on failure by bdrv_attach_child_common_abort() */
3091 assert((ret < 0) == !child);
3092
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003093 bdrv_unref(child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003094 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003095}
3096
Alberto Garciab441dc72019-05-13 16:46:18 +03003097/*
3098 * This function transfers the reference to child_bs from the caller
3099 * to parent_bs. That reference is later dropped by parent_bs on
3100 * bdrv_close() or if someone calls bdrv_unref_child().
3101 *
3102 * On failure NULL is returned, errp is set and the reference to
3103 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003104 *
3105 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3106 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003107 */
Wen Congyang98292c62016-05-10 15:36:38 +08003108BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3109 BlockDriverState *child_bs,
3110 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003111 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003112 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003113 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003114{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003115 int ret;
3116 BdrvChild *child = NULL;
3117 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003118
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003119 GLOBAL_STATE_CODE();
3120
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003121 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3122 child_role, &child, tran, errp);
3123 if (ret < 0) {
3124 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003125 }
3126
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003127 ret = bdrv_refresh_perms(parent_bs, errp);
3128 if (ret < 0) {
3129 goto out;
3130 }
3131
3132out:
3133 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003134 /* child is unset on failure by bdrv_attach_child_common_abort() */
3135 assert((ret < 0) == !child);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003136
3137 bdrv_unref(child_bs);
3138
Kevin Wolff21d96d2016-03-08 13:47:46 +01003139 return child;
3140}
3141
Max Reitz7b99a262019-06-12 16:07:11 +02003142/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003143void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003144{
Kevin Wolf779020c2015-10-13 14:09:44 +02003145 BlockDriverState *child_bs;
3146
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003147 GLOBAL_STATE_CODE();
3148
Kevin Wolff21d96d2016-03-08 13:47:46 +01003149 child_bs = child->bs;
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003150 bdrv_detach_child(&child);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003151 bdrv_unref(child_bs);
3152}
3153
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003154typedef struct BdrvSetInheritsFrom {
3155 BlockDriverState *bs;
3156 BlockDriverState *old_inherits_from;
3157} BdrvSetInheritsFrom;
3158
3159static void bdrv_set_inherits_from_abort(void *opaque)
3160{
3161 BdrvSetInheritsFrom *s = opaque;
3162
3163 s->bs->inherits_from = s->old_inherits_from;
3164}
3165
3166static TransactionActionDrv bdrv_set_inherits_from_drv = {
3167 .abort = bdrv_set_inherits_from_abort,
3168 .clean = g_free,
3169};
3170
3171/* @tran is allowed to be NULL. In this case no rollback is possible */
3172static void bdrv_set_inherits_from(BlockDriverState *bs,
3173 BlockDriverState *new_inherits_from,
3174 Transaction *tran)
3175{
3176 if (tran) {
3177 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3178
3179 *s = (BdrvSetInheritsFrom) {
3180 .bs = bs,
3181 .old_inherits_from = bs->inherits_from,
3182 };
3183
3184 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3185 }
3186
3187 bs->inherits_from = new_inherits_from;
3188}
3189
Max Reitz3cf746b2019-07-03 19:28:07 +02003190/**
3191 * Clear all inherits_from pointers from children and grandchildren of
3192 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003193 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003194 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003195static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3196 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003197{
Max Reitz3cf746b2019-07-03 19:28:07 +02003198 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003199
Max Reitz3cf746b2019-07-03 19:28:07 +02003200 if (child->bs->inherits_from == root) {
3201 /*
3202 * Remove inherits_from only when the last reference between root and
3203 * child->bs goes away.
3204 */
3205 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003206 if (c != child && c->bs == child->bs) {
3207 break;
3208 }
3209 }
3210 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003211 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003212 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003213 }
3214
Max Reitz3cf746b2019-07-03 19:28:07 +02003215 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003216 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003217 }
3218}
3219
Max Reitz7b99a262019-06-12 16:07:11 +02003220/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003221void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3222{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003223 GLOBAL_STATE_CODE();
Max Reitz3cf746b2019-07-03 19:28:07 +02003224 if (child == NULL) {
3225 return;
3226 }
3227
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003228 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003229 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003230}
3231
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003232
3233static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3234{
3235 BdrvChild *c;
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003236 GLOBAL_STATE_CODE();
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003237 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003238 if (c->klass->change_media) {
3239 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003240 }
3241 }
3242}
3243
Alberto Garcia0065c452018-10-31 18:16:37 +02003244/* Return true if you can reach parent going through child->inherits_from
3245 * recursively. If parent or child are NULL, return false */
3246static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3247 BlockDriverState *parent)
3248{
3249 while (child && child != parent) {
3250 child = child->inherits_from;
3251 }
3252
3253 return child != NULL;
3254}
3255
Kevin Wolf5db15a52015-09-14 15:33:33 +02003256/*
Max Reitz25191e52020-05-13 13:05:33 +02003257 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3258 * mostly used for COW backing children (role = COW), but also for
3259 * filtered children (role = FILTERED | PRIMARY).
3260 */
3261static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3262{
3263 if (bs->drv && bs->drv->is_filter) {
3264 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3265 } else {
3266 return BDRV_CHILD_COW;
3267 }
3268}
3269
3270/*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003271 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3272 * callers which don't need their own reference any more must call bdrv_unref().
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003273 *
3274 * Function doesn't update permissions, caller is responsible for this.
Kevin Wolf5db15a52015-09-14 15:33:33 +02003275 */
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003276static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3277 BlockDriverState *child_bs,
3278 bool is_backing,
3279 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003280{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003281 int ret = 0;
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003282 bool update_inherits_from =
3283 bdrv_inherits_from_recursive(child_bs, parent_bs);
3284 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3285 BdrvChildRole role;
Alberto Garcia0065c452018-10-31 18:16:37 +02003286
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003287 GLOBAL_STATE_CODE();
3288
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003289 if (!parent_bs->drv) {
3290 /*
3291 * Node without drv is an object without a class :/. TODO: finally fix
3292 * qcow2 driver to never clear bs->drv and implement format corruption
3293 * handling in other way.
3294 */
3295 error_setg(errp, "Node corrupted");
3296 return -EINVAL;
3297 }
3298
3299 if (child && child->frozen) {
3300 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3301 child->name, parent_bs->node_name, child->bs->node_name);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003302 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003303 }
3304
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03003305 if (is_backing && !parent_bs->drv->is_filter &&
3306 !parent_bs->drv->supports_backing)
3307 {
3308 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3309 "files", parent_bs->drv->format_name, parent_bs->node_name);
3310 return -EINVAL;
3311 }
3312
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003313 if (parent_bs->drv->is_filter) {
3314 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3315 } else if (is_backing) {
3316 role = BDRV_CHILD_COW;
3317 } else {
3318 /*
3319 * We only can use same role as it is in existing child. We don't have
3320 * infrastructure to determine role of file child in generic way
3321 */
3322 if (!child) {
3323 error_setg(errp, "Cannot set file child to format node without "
3324 "file child");
3325 return -EINVAL;
3326 }
3327 role = child->role;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003328 }
3329
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003330 if (child) {
3331 bdrv_unset_inherits_from(parent_bs, child, tran);
3332 bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3333 }
3334
3335 if (!child_bs) {
Fam Zheng8d24cce2014-05-23 21:29:45 +08003336 goto out;
3337 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003338
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003339 ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3340 is_backing ? "backing" : "file",
3341 &child_of_bds, role,
3342 is_backing ? &parent_bs->backing :
3343 &parent_bs->file,
3344 tran, errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003345 if (ret < 0) {
3346 return ret;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003347 }
3348
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003349
3350 /*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003351 * If inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003352 * point directly to bs (else it will become NULL).
3353 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003354 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003355 bdrv_set_inherits_from(child_bs, parent_bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003356 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003357
Fam Zheng8d24cce2014-05-23 21:29:45 +08003358out:
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003359 bdrv_refresh_limits(parent_bs, tran, NULL);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003360
3361 return 0;
3362}
3363
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003364static int bdrv_set_backing_noperm(BlockDriverState *bs,
3365 BlockDriverState *backing_hd,
3366 Transaction *tran, Error **errp)
3367{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003368 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003369 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3370}
3371
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003372int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3373 Error **errp)
3374{
3375 int ret;
3376 Transaction *tran = tran_new();
3377
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003378 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003379 bdrv_drained_begin(bs);
3380
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003381 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3382 if (ret < 0) {
3383 goto out;
3384 }
3385
3386 ret = bdrv_refresh_perms(bs, errp);
3387out:
3388 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003389
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003390 bdrv_drained_end(bs);
3391
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003392 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003393}
3394
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003395/*
3396 * Opens the backing file for a BlockDriverState if not yet open
3397 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003398 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3399 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3400 * itself, all options starting with "${bdref_key}." are considered part of the
3401 * BlockdevRef.
3402 *
3403 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003404 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003405int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3406 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003407{
Max Reitz6b6833c2019-02-01 20:29:15 +01003408 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003409 char *bdref_key_dot;
3410 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003411 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003412 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003413 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003414 QDict *options;
3415 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003416 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003417
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003418 GLOBAL_STATE_CODE();
3419
Kevin Wolf760e0062015-06-17 14:55:21 +02003420 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003421 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003422 }
3423
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003424 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003425 if (parent_options == NULL) {
3426 tmp_parent_options = qdict_new();
3427 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003428 }
3429
Paolo Bonzini9156df12012-10-18 16:49:17 +02003430 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003431
3432 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3433 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3434 g_free(bdref_key_dot);
3435
Markus Armbruster129c7d12017-03-30 19:43:12 +02003436 /*
3437 * Caution: while qdict_get_try_str() is fine, getting non-string
3438 * types would require more care. When @parent_options come from
3439 * -blockdev or blockdev_add, its members are typed according to
3440 * the QAPI schema, but when they come from -drive, they're all
3441 * QString.
3442 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003443 reference = qdict_get_try_str(parent_options, bdref_key);
3444 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003445 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003446 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003447 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003448 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003449 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003450 if (qdict_size(options) == 0) {
3451 /* If the user specifies options that do not modify the
3452 * backing file's behavior, we might still consider it the
3453 * implicit backing file. But it's easier this way, and
3454 * just specifying some of the backing BDS's options is
3455 * only possible with -drive anyway (otherwise the QAPI
3456 * schema forces the user to specify everything). */
3457 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3458 }
3459
Max Reitz6b6833c2019-02-01 20:29:15 +01003460 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003461 if (local_err) {
3462 ret = -EINVAL;
3463 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003464 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003465 goto free_exit;
3466 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003467 }
3468
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003469 if (!bs->drv || !bs->drv->supports_backing) {
3470 ret = -EINVAL;
3471 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003472 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003473 goto free_exit;
3474 }
3475
Peter Krempa6bff5972017-10-12 16:14:10 +02003476 if (!reference &&
3477 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003478 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003479 }
3480
Max Reitz6b6833c2019-02-01 20:29:15 +01003481 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003482 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003483 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003484 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003485 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003486 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003487 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003488 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003489
Max Reitz998c2012019-02-01 20:29:08 +01003490 if (implicit_backing) {
3491 bdrv_refresh_filename(backing_hd);
3492 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3493 backing_hd->filename);
3494 }
3495
Kevin Wolf5db15a52015-09-14 15:33:33 +02003496 /* Hook up the backing file link; drop our reference, bs owns the
3497 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003498 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003499 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003500 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003501 goto free_exit;
3502 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003503
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003504 qdict_del(parent_options, bdref_key);
3505
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003506free_exit:
3507 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003508 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003509 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003510}
3511
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003512static BlockDriverState *
3513bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003514 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003515 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003516{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003517 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003518 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003519 char *bdref_key_dot;
3520 const char *reference;
3521
Max Reitzbd86fb92020-05-13 13:05:13 +02003522 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003523
Max Reitzda557aa2013-12-20 19:28:11 +01003524 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3525 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3526 g_free(bdref_key_dot);
3527
Markus Armbruster129c7d12017-03-30 19:43:12 +02003528 /*
3529 * Caution: while qdict_get_try_str() is fine, getting non-string
3530 * types would require more care. When @options come from
3531 * -blockdev or blockdev_add, its members are typed according to
3532 * the QAPI schema, but when they come from -drive, they're all
3533 * QString.
3534 */
Max Reitzda557aa2013-12-20 19:28:11 +01003535 reference = qdict_get_try_str(options, bdref_key);
3536 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003537 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003538 error_setg(errp, "A block device must be specified for \"%s\"",
3539 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003540 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003541 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003542 goto done;
3543 }
3544
Max Reitz5b363932016-05-17 16:41:31 +02003545 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003546 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003547 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003548 goto done;
3549 }
3550
Max Reitzda557aa2013-12-20 19:28:11 +01003551done:
3552 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003553 return bs;
3554}
3555
3556/*
3557 * Opens a disk image whose options are given as BlockdevRef in another block
3558 * device's options.
3559 *
3560 * If allow_none is true, no image will be opened if filename is false and no
3561 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3562 *
3563 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3564 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3565 * itself, all options starting with "${bdref_key}." are considered part of the
3566 * BlockdevRef.
3567 *
3568 * The BlockdevRef will be removed from the options QDict.
3569 */
3570BdrvChild *bdrv_open_child(const char *filename,
3571 QDict *options, const char *bdref_key,
3572 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003573 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003574 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003575 bool allow_none, Error **errp)
3576{
3577 BlockDriverState *bs;
3578
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003579 GLOBAL_STATE_CODE();
3580
Max Reitzbd86fb92020-05-13 13:05:13 +02003581 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003582 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003583 if (bs == NULL) {
3584 return NULL;
3585 }
3586
Max Reitz258b7762020-05-13 13:05:15 +02003587 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3588 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003589}
3590
Max Reitzbd86fb92020-05-13 13:05:13 +02003591/*
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003592 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3593 */
3594int bdrv_open_file_child(const char *filename,
3595 QDict *options, const char *bdref_key,
3596 BlockDriverState *parent, Error **errp)
3597{
3598 BdrvChildRole role;
3599
3600 /* commit_top and mirror_top don't use this function */
3601 assert(!parent->drv->filtered_child_is_backing);
3602
3603 role = parent->drv->is_filter ?
3604 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3605
3606 parent->file = bdrv_open_child(filename, options, bdref_key, parent,
3607 &child_of_bds, role, false, errp);
3608
3609 return parent->file ? 0 : -EINVAL;
3610}
3611
3612/*
Max Reitzbd86fb92020-05-13 13:05:13 +02003613 * TODO Future callers may need to specify parent/child_class in order for
3614 * option inheritance to work. Existing callers use it for the root node.
3615 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003616BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3617{
3618 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003619 QObject *obj = NULL;
3620 QDict *qdict = NULL;
3621 const char *reference = NULL;
3622 Visitor *v = NULL;
3623
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003624 GLOBAL_STATE_CODE();
3625
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003626 if (ref->type == QTYPE_QSTRING) {
3627 reference = ref->u.reference;
3628 } else {
3629 BlockdevOptions *options = &ref->u.definition;
3630 assert(ref->type == QTYPE_QDICT);
3631
3632 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003633 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003634 visit_complete(v, &obj);
3635
Max Reitz7dc847e2018-02-24 16:40:29 +01003636 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003637 qdict_flatten(qdict);
3638
3639 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3640 * compatibility with other callers) rather than what we want as the
3641 * real defaults. Apply the defaults here instead. */
3642 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3643 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3644 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003645 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3646
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003647 }
3648
Max Reitz272c02e2020-05-13 13:05:17 +02003649 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003650 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003651 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003652 visit_free(v);
3653 return bs;
3654}
3655
Max Reitz66836182016-05-17 16:41:27 +02003656static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3657 int flags,
3658 QDict *snapshot_options,
3659 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003660{
Bin Meng69fbfff2022-10-10 12:04:31 +08003661 g_autofree char *tmp_filename = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003662 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003663 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003664 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003665 int ret;
3666
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003667 GLOBAL_STATE_CODE();
3668
Kevin Wolfb9988752014-04-03 12:09:34 +02003669 /* if snapshot, we create a temporary backing file and open it
3670 instead of opening 'filename' directly */
3671
3672 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003673 total_size = bdrv_getlength(bs);
3674 if (total_size < 0) {
3675 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003676 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003677 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003678
3679 /* Create the temporary image */
Bin Meng69fbfff2022-10-10 12:04:31 +08003680 tmp_filename = create_tmp_file(errp);
3681 if (!tmp_filename) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003682 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003683 }
3684
Max Reitzef810432014-12-02 18:32:42 +01003685 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003686 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003687 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003688 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003689 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003690 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003691 error_prepend(errp, "Could not create temporary overlay '%s': ",
3692 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003693 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003694 }
3695
Kevin Wolf73176be2016-03-07 13:02:15 +01003696 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003697 qdict_put_str(snapshot_options, "file.driver", "file");
3698 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3699 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003700
Max Reitz5b363932016-05-17 16:41:31 +02003701 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003702 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003703 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003704 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003705 }
3706
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003707 ret = bdrv_append(bs_snapshot, bs, errp);
3708 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003709 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003710 goto out;
3711 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003712
3713out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003714 qobject_unref(snapshot_options);
Eric Blakeff6ed712017-04-27 16:58:18 -05003715 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003716}
3717
Max Reitzda557aa2013-12-20 19:28:11 +01003718/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003719 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003720 *
3721 * options is a QDict of options to pass to the block drivers, or NULL for an
3722 * empty set of options. The reference to the QDict belongs to the block layer
3723 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003724 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003725 *
3726 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3727 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003728 *
3729 * The reference parameter may be used to specify an existing block device which
3730 * should be opened. If specified, neither options nor a filename may be given,
3731 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003732 */
Max Reitz5b363932016-05-17 16:41:31 +02003733static BlockDriverState *bdrv_open_inherit(const char *filename,
3734 const char *reference,
3735 QDict *options, int flags,
3736 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003737 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003738 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003739 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003740{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003741 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003742 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003743 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003744 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003745 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003746 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003747 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003748 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003749 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003750 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003751
Max Reitzbd86fb92020-05-13 13:05:13 +02003752 assert(!child_class || !flags);
3753 assert(!child_class == !parent);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003754 GLOBAL_STATE_CODE();
Max Reitzf67503e2014-02-18 18:33:05 +01003755
Max Reitzddf56362014-02-18 18:33:06 +01003756 if (reference) {
3757 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003758 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003759
Max Reitzddf56362014-02-18 18:33:06 +01003760 if (filename || options_non_empty) {
3761 error_setg(errp, "Cannot reference an existing block device with "
3762 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003763 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003764 }
3765
3766 bs = bdrv_lookup_bs(reference, reference, errp);
3767 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003768 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003769 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003770
Max Reitzddf56362014-02-18 18:33:06 +01003771 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003772 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003773 }
3774
Max Reitz5b363932016-05-17 16:41:31 +02003775 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003776
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003777 /* NULL means an empty set of options */
3778 if (options == NULL) {
3779 options = qdict_new();
3780 }
3781
Kevin Wolf145f5982015-05-08 16:15:03 +02003782 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003783 parse_json_protocol(options, &filename, &local_err);
3784 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003785 goto fail;
3786 }
3787
Kevin Wolf145f5982015-05-08 16:15:03 +02003788 bs->explicit_options = qdict_clone_shallow(options);
3789
Max Reitzbd86fb92020-05-13 13:05:13 +02003790 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003791 bool parent_is_format;
3792
3793 if (parent->drv) {
3794 parent_is_format = parent->drv->is_format;
3795 } else {
3796 /*
3797 * parent->drv is not set yet because this node is opened for
3798 * (potential) format probing. That means that @parent is going
3799 * to be a format node.
3800 */
3801 parent_is_format = true;
3802 }
3803
Kevin Wolfbddcec32015-04-09 18:47:50 +02003804 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003805 child_class->inherit_options(child_role, parent_is_format,
3806 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003807 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003808 }
3809
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003810 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003811 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003812 goto fail;
3813 }
3814
Markus Armbruster129c7d12017-03-30 19:43:12 +02003815 /*
3816 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3817 * Caution: getting a boolean member of @options requires care.
3818 * When @options come from -blockdev or blockdev_add, members are
3819 * typed according to the QAPI schema, but when they come from
3820 * -drive, they're all QString.
3821 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003822 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3823 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3824 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3825 } else {
3826 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003827 }
3828
3829 if (flags & BDRV_O_SNAPSHOT) {
3830 snapshot_options = qdict_new();
3831 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3832 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003833 /* Let bdrv_backing_options() override "read-only" */
3834 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003835 bdrv_inherited_options(BDRV_CHILD_COW, true,
3836 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003837 }
3838
Kevin Wolf62392eb2015-04-24 16:38:02 +02003839 bs->open_flags = flags;
3840 bs->options = options;
3841 options = qdict_clone_shallow(options);
3842
Kevin Wolf76c591b2014-06-04 14:19:44 +02003843 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003844 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003845 drvname = qdict_get_try_str(options, "driver");
3846 if (drvname) {
3847 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003848 if (!drv) {
3849 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003850 goto fail;
3851 }
3852 }
3853
3854 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003855
Markus Armbruster129c7d12017-03-30 19:43:12 +02003856 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003857 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003858 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3859 (backing && *backing == '\0'))
3860 {
Max Reitz4f7be282018-02-24 16:40:33 +01003861 if (backing) {
3862 warn_report("Use of \"backing\": \"\" is deprecated; "
3863 "use \"backing\": null instead");
3864 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003865 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003866 qdict_del(bs->explicit_options, "backing");
3867 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003868 qdict_del(options, "backing");
3869 }
3870
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003871 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003872 * probing, the block drivers will do their own bdrv_open_child() for the
3873 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003874 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003875 BlockDriverState *file_bs;
3876
3877 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003878 &child_of_bds, BDRV_CHILD_IMAGE,
3879 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003880 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003881 goto fail;
3882 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003883 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003884 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3885 * looking at the header to guess the image format. This works even
3886 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003887 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003888 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003889 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003890 if (local_err) {
3891 goto fail;
3892 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003893
Eric Blake46f5ac22017-04-27 16:58:17 -05003894 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003895 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003896 }
3897
Kevin Wolf76c591b2014-06-04 14:19:44 +02003898 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003899 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003900 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003901 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003902 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003903 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003904 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003905 /*
3906 * This option update would logically belong in bdrv_fill_options(),
3907 * but we first need to open bs->file for the probing to work, while
3908 * opening bs->file already requires the (mostly) final set of options
3909 * so that cache mode etc. can be inherited.
3910 *
3911 * Adding the driver later is somewhat ugly, but it's not an option
3912 * that would ever be inherited, so it's correct. We just need to make
3913 * sure to update both bs->options (which has the full effective
3914 * options for bs) and options (which has file.* already removed).
3915 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003916 qdict_put_str(bs->options, "driver", drv->format_name);
3917 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003918 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003919 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003920 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003921 }
3922
Max Reitz53a29512015-03-19 14:53:16 -04003923 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3924 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3925 /* file must be NULL if a protocol BDS is about to be created
3926 * (the inverse results in an error message from bdrv_open_common()) */
3927 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3928
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003929 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003930 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003931 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003932 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003933 }
3934
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003935 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003936 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003937 file = NULL;
3938 }
3939
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003940 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003941 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003942 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003943 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003944 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003945 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003946 }
3947
Alberto Garcia50196d72018-09-06 12:37:03 +03003948 /* Remove all children options and references
3949 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003950 QLIST_FOREACH(child, &bs->children, next) {
3951 char *child_key_dot;
3952 child_key_dot = g_strdup_printf("%s.", child->name);
3953 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3954 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003955 qdict_del(bs->explicit_options, child->name);
3956 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003957 g_free(child_key_dot);
3958 }
3959
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003960 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003961 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003962 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003963 if (flags & BDRV_O_PROTOCOL) {
3964 error_setg(errp, "Block protocol '%s' doesn't support the option "
3965 "'%s'", drv->format_name, entry->key);
3966 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003967 error_setg(errp,
3968 "Block format '%s' does not support the option '%s'",
3969 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003970 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003971
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003972 goto close_and_fail;
3973 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003974
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003975 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003976
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003977 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003978 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003979
3980 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3981 * temporary snapshot afterwards. */
3982 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003983 BlockDriverState *snapshot_bs;
3984 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3985 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003986 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003987 if (local_err) {
3988 goto close_and_fail;
3989 }
Max Reitz5b363932016-05-17 16:41:31 +02003990 /* We are not going to return bs but the overlay on top of it
3991 * (snapshot_bs); thus, we have to drop the strong reference to bs
3992 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3993 * though, because the overlay still has a reference to it. */
3994 bdrv_unref(bs);
3995 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003996 }
3997
Max Reitz5b363932016-05-17 16:41:31 +02003998 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003999
Kevin Wolf8bfea152014-04-11 19:16:36 +02004000fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01004001 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004002 qobject_unref(snapshot_options);
4003 qobject_unref(bs->explicit_options);
4004 qobject_unref(bs->options);
4005 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004006 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03004007 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02004008 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004009 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004010 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004011
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004012close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02004013 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004014 qobject_unref(snapshot_options);
4015 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004016 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004017 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004018}
4019
Max Reitz5b363932016-05-17 16:41:31 +02004020BlockDriverState *bdrv_open(const char *filename, const char *reference,
4021 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02004022{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004023 GLOBAL_STATE_CODE();
4024
Max Reitz5b363932016-05-17 16:41:31 +02004025 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02004026 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02004027}
4028
Alberto Garciafaf116b2019-03-12 18:48:49 +02004029/* Return true if the NULL-terminated @list contains @str */
4030static bool is_str_in_list(const char *str, const char *const *list)
4031{
4032 if (str && list) {
4033 int i;
4034 for (i = 0; list[i] != NULL; i++) {
4035 if (!strcmp(str, list[i])) {
4036 return true;
4037 }
4038 }
4039 }
4040 return false;
4041}
4042
4043/*
4044 * Check that every option set in @bs->options is also set in
4045 * @new_opts.
4046 *
4047 * Options listed in the common_options list and in
4048 * @bs->drv->mutable_opts are skipped.
4049 *
4050 * Return 0 on success, otherwise return -EINVAL and set @errp.
4051 */
4052static int bdrv_reset_options_allowed(BlockDriverState *bs,
4053 const QDict *new_opts, Error **errp)
4054{
4055 const QDictEntry *e;
4056 /* These options are common to all block drivers and are handled
4057 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4058 const char *const common_options[] = {
4059 "node-name", "discard", "cache.direct", "cache.no-flush",
4060 "read-only", "auto-read-only", "detect-zeroes", NULL
4061 };
4062
4063 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4064 if (!qdict_haskey(new_opts, e->key) &&
4065 !is_str_in_list(e->key, common_options) &&
4066 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4067 error_setg(errp, "Option '%s' cannot be reset "
4068 "to its default value", e->key);
4069 return -EINVAL;
4070 }
4071 }
4072
4073 return 0;
4074}
4075
Jeff Codye971aa12012-09-20 15:13:19 -04004076/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004077 * Returns true if @child can be reached recursively from @bs
4078 */
4079static bool bdrv_recurse_has_child(BlockDriverState *bs,
4080 BlockDriverState *child)
4081{
4082 BdrvChild *c;
4083
4084 if (bs == child) {
4085 return true;
4086 }
4087
4088 QLIST_FOREACH(c, &bs->children, next) {
4089 if (bdrv_recurse_has_child(c->bs, child)) {
4090 return true;
4091 }
4092 }
4093
4094 return false;
4095}
4096
4097/*
Jeff Codye971aa12012-09-20 15:13:19 -04004098 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4099 * reopen of multiple devices.
4100 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004101 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04004102 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4103 * be created and initialized. This newly created BlockReopenQueue should be
4104 * passed back in for subsequent calls that are intended to be of the same
4105 * atomic 'set'.
4106 *
4107 * bs is the BlockDriverState to add to the reopen queue.
4108 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004109 * options contains the changed options for the associated bs
4110 * (the BlockReopenQueue takes ownership)
4111 *
Jeff Codye971aa12012-09-20 15:13:19 -04004112 * flags contains the open flags for the associated bs
4113 *
4114 * returns a pointer to bs_queue, which is either the newly allocated
4115 * bs_queue, or the existing bs_queue being used.
4116 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004117 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004118 */
Kevin Wolf28518102015-05-08 17:07:31 +02004119static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4120 BlockDriverState *bs,
4121 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02004122 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02004123 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004124 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02004125 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004126 int parent_flags,
4127 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04004128{
4129 assert(bs != NULL);
4130
4131 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02004132 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004133 QDict *old_options, *explicit_options, *options_copy;
4134 int flags;
4135 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004136
Kevin Wolf1a63a902017-12-06 20:24:44 +01004137 /* Make sure that the caller remembered to use a drained section. This is
4138 * important to avoid graph changes between the recursive queuing here and
4139 * bdrv_reopen_multiple(). */
4140 assert(bs->quiesce_counter > 0);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05004141 GLOBAL_STATE_CODE();
Kevin Wolf1a63a902017-12-06 20:24:44 +01004142
Jeff Codye971aa12012-09-20 15:13:19 -04004143 if (bs_queue == NULL) {
4144 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004145 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04004146 }
4147
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004148 if (!options) {
4149 options = qdict_new();
4150 }
4151
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004152 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004153 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004154 if (bs == bs_entry->state.bs) {
4155 break;
4156 }
4157 }
4158
Kevin Wolf28518102015-05-08 17:07:31 +02004159 /*
4160 * Precedence of options:
4161 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004162 * 2. Retained from explicitly set options of bs
4163 * 3. Inherited from parent node
4164 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004165 */
4166
Kevin Wolf145f5982015-05-08 16:15:03 +02004167 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004168 if (bs_entry || keep_old_opts) {
4169 old_options = qdict_clone_shallow(bs_entry ?
4170 bs_entry->state.explicit_options :
4171 bs->explicit_options);
4172 bdrv_join_options(bs, options, old_options);
4173 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004174 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004175
4176 explicit_options = qdict_clone_shallow(options);
4177
Kevin Wolf28518102015-05-08 17:07:31 +02004178 /* Inherit from parent node */
4179 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004180 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004181 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004182 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004183 } else {
4184 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004185 }
4186
Alberto Garcia077e8e22019-03-12 18:48:44 +02004187 if (keep_old_opts) {
4188 /* Old values are used for options that aren't set yet */
4189 old_options = qdict_clone_shallow(bs->options);
4190 bdrv_join_options(bs, options, old_options);
4191 qobject_unref(old_options);
4192 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004193
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004194 /* We have the final set of options so let's update the flags */
4195 options_copy = qdict_clone_shallow(options);
4196 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4197 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4198 update_flags_from_options(&flags, opts);
4199 qemu_opts_del(opts);
4200 qobject_unref(options_copy);
4201
Kevin Wolffd452022017-08-03 17:02:59 +02004202 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004203 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004204 if (flags & BDRV_O_RDWR) {
4205 flags |= BDRV_O_ALLOW_RDWR;
4206 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004207
Kevin Wolf1857c972017-09-14 14:53:46 +02004208 if (!bs_entry) {
4209 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004210 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004211 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004212 qobject_unref(bs_entry->state.options);
4213 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004214 }
4215
4216 bs_entry->state.bs = bs;
4217 bs_entry->state.options = options;
4218 bs_entry->state.explicit_options = explicit_options;
4219 bs_entry->state.flags = flags;
4220
Alberto Garcia85466322019-03-12 18:48:45 +02004221 /*
4222 * If keep_old_opts is false then it means that unspecified
4223 * options must be reset to their original value. We don't allow
4224 * resetting 'backing' but we need to know if the option is
4225 * missing in order to decide if we have to return an error.
4226 */
4227 if (!keep_old_opts) {
4228 bs_entry->state.backing_missing =
4229 !qdict_haskey(options, "backing") &&
4230 !qdict_haskey(options, "backing.driver");
4231 }
4232
Kevin Wolf67251a32015-04-09 18:54:04 +02004233 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004234 QDict *new_child_options = NULL;
4235 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004236
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004237 /* reopen can only change the options of block devices that were
4238 * implicitly created and inherited options. For other (referenced)
4239 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004240 if (child->bs->inherits_from != bs) {
4241 continue;
4242 }
4243
Alberto Garcia85466322019-03-12 18:48:45 +02004244 /* Check if the options contain a child reference */
4245 if (qdict_haskey(options, child->name)) {
4246 const char *childref = qdict_get_try_str(options, child->name);
4247 /*
4248 * The current child must not be reopened if the child
4249 * reference is null or points to a different node.
4250 */
4251 if (g_strcmp0(childref, child->bs->node_name)) {
4252 continue;
4253 }
4254 /*
4255 * If the child reference points to the current child then
4256 * reopen it with its existing set of options (note that
4257 * it can still inherit new options from the parent).
4258 */
4259 child_keep_old = true;
4260 } else {
4261 /* Extract child options ("child-name.*") */
4262 char *child_key_dot = g_strdup_printf("%s.", child->name);
4263 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4264 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4265 g_free(child_key_dot);
4266 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004267
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004268 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004269 child->klass, child->role, bs->drv->is_format,
4270 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004271 }
4272
Jeff Codye971aa12012-09-20 15:13:19 -04004273 return bs_queue;
4274}
4275
Kevin Wolf28518102015-05-08 17:07:31 +02004276BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4277 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004278 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004279{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004280 GLOBAL_STATE_CODE();
4281
Max Reitz3cdc69d2020-05-13 13:05:18 +02004282 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4283 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004284}
4285
Alberto Garciaab5b52282021-07-08 13:47:05 +02004286void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4287{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004288 GLOBAL_STATE_CODE();
Alberto Garciaab5b52282021-07-08 13:47:05 +02004289 if (bs_queue) {
4290 BlockReopenQueueEntry *bs_entry, *next;
4291 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4292 qobject_unref(bs_entry->state.explicit_options);
4293 qobject_unref(bs_entry->state.options);
4294 g_free(bs_entry);
4295 }
4296 g_free(bs_queue);
4297 }
4298}
4299
Jeff Codye971aa12012-09-20 15:13:19 -04004300/*
4301 * Reopen multiple BlockDriverStates atomically & transactionally.
4302 *
4303 * The queue passed in (bs_queue) must have been built up previous
4304 * via bdrv_reopen_queue().
4305 *
4306 * Reopens all BDS specified in the queue, with the appropriate
4307 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004308 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004309 * data cleaned up.
4310 *
4311 * If all devices prepare successfully, then the changes are committed
4312 * to all devices.
4313 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004314 * All affected nodes must be drained between bdrv_reopen_queue() and
4315 * bdrv_reopen_multiple().
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004316 *
4317 * To be called from the main thread, with all other AioContexts unlocked.
Jeff Codye971aa12012-09-20 15:13:19 -04004318 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004319int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004320{
4321 int ret = -1;
4322 BlockReopenQueueEntry *bs_entry, *next;
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004323 AioContext *ctx;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004324 Transaction *tran = tran_new();
4325 g_autoptr(GHashTable) found = NULL;
4326 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004327
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004328 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Jeff Codye971aa12012-09-20 15:13:19 -04004329 assert(bs_queue != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004330 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004331
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004332 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004333 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4334 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004335 ret = bdrv_flush(bs_entry->state.bs);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004336 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004337 if (ret < 0) {
4338 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004339 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004340 }
4341 }
4342
4343 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004344 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004345 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4346 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004347 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004348 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004349 if (ret < 0) {
4350 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004351 }
4352 bs_entry->prepared = true;
4353 }
4354
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004355 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004356 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004357 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004358
4359 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4360 if (state->old_backing_bs) {
4361 refresh_list = bdrv_topological_dfs(refresh_list, found,
4362 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004363 }
Alberto Garciaecd30d22021-06-10 15:05:36 +03004364 if (state->old_file_bs) {
4365 refresh_list = bdrv_topological_dfs(refresh_list, found,
4366 state->old_file_bs);
4367 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004368 }
4369
4370 /*
4371 * Note that file-posix driver rely on permission update done during reopen
4372 * (even if no permission changed), because it wants "new" permissions for
4373 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4374 * in raw_reopen_prepare() which is called with "old" permissions.
4375 */
4376 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4377 if (ret < 0) {
4378 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004379 }
4380
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004381 /*
4382 * If we reach this point, we have success and just need to apply the
4383 * changes.
4384 *
4385 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4386 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4387 * children are usually goes after parents in reopen-queue, so go from last
4388 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004389 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004390 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004391 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4392 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004393 bdrv_reopen_commit(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004394 aio_context_release(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004395 }
4396
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004397 tran_commit(tran);
4398
4399 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4400 BlockDriverState *bs = bs_entry->state.bs;
4401
4402 if (bs->drv->bdrv_reopen_commit_post) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004403 ctx = bdrv_get_aio_context(bs);
4404 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004405 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004406 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004407 }
4408 }
4409
Jeff Codye971aa12012-09-20 15:13:19 -04004410 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004411 goto cleanup;
4412
4413abort:
4414 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004415 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004416 if (bs_entry->prepared) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004417 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4418 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004419 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004420 aio_context_release(ctx);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004421 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004422 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004423
Jeff Codye971aa12012-09-20 15:13:19 -04004424cleanup:
Alberto Garciaab5b52282021-07-08 13:47:05 +02004425 bdrv_reopen_queue_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004426
Jeff Codye971aa12012-09-20 15:13:19 -04004427 return ret;
4428}
4429
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004430int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4431 Error **errp)
4432{
4433 AioContext *ctx = bdrv_get_aio_context(bs);
4434 BlockReopenQueue *queue;
4435 int ret;
4436
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004437 GLOBAL_STATE_CODE();
4438
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004439 bdrv_subtree_drained_begin(bs);
4440 if (ctx != qemu_get_aio_context()) {
4441 aio_context_release(ctx);
4442 }
4443
4444 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4445 ret = bdrv_reopen_multiple(queue, errp);
4446
4447 if (ctx != qemu_get_aio_context()) {
4448 aio_context_acquire(ctx);
4449 }
4450 bdrv_subtree_drained_end(bs);
4451
4452 return ret;
4453}
4454
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004455int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4456 Error **errp)
4457{
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004458 QDict *opts = qdict_new();
4459
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004460 GLOBAL_STATE_CODE();
4461
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004462 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4463
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004464 return bdrv_reopen(bs, opts, true, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004465}
4466
Jeff Codye971aa12012-09-20 15:13:19 -04004467/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004468 * Take a BDRVReopenState and check if the value of 'backing' in the
4469 * reopen_state->options QDict is valid or not.
4470 *
4471 * If 'backing' is missing from the QDict then return 0.
4472 *
4473 * If 'backing' contains the node name of the backing file of
4474 * reopen_state->bs then return 0.
4475 *
4476 * If 'backing' contains a different node name (or is null) then check
4477 * whether the current backing file can be replaced with the new one.
4478 * If that's the case then reopen_state->replace_backing_bs is set to
4479 * true and reopen_state->new_backing_bs contains a pointer to the new
4480 * backing BlockDriverState (or NULL).
4481 *
4482 * Return 0 on success, otherwise return < 0 and set @errp.
4483 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004484static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4485 bool is_backing, Transaction *tran,
4486 Error **errp)
Alberto Garciacb828c32019-03-12 18:48:47 +02004487{
4488 BlockDriverState *bs = reopen_state->bs;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004489 BlockDriverState *new_child_bs;
4490 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4491 child_bs(bs->file);
4492 const char *child_name = is_backing ? "backing" : "file";
Alberto Garciacb828c32019-03-12 18:48:47 +02004493 QObject *value;
4494 const char *str;
4495
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05004496 GLOBAL_STATE_CODE();
4497
Alberto Garciaecd30d22021-06-10 15:05:36 +03004498 value = qdict_get(reopen_state->options, child_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004499 if (value == NULL) {
4500 return 0;
4501 }
4502
4503 switch (qobject_type(value)) {
4504 case QTYPE_QNULL:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004505 assert(is_backing); /* The 'file' option does not allow a null value */
4506 new_child_bs = NULL;
Alberto Garciacb828c32019-03-12 18:48:47 +02004507 break;
4508 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004509 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciaecd30d22021-06-10 15:05:36 +03004510 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4511 if (new_child_bs == NULL) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004512 return -EINVAL;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004513 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4514 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4515 "cycle", str, child_name, bs->node_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004516 return -EINVAL;
4517 }
4518 break;
4519 default:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004520 /*
4521 * The options QDict has been flattened, so 'backing' and 'file'
4522 * do not allow any other data type here.
4523 */
Alberto Garciacb828c32019-03-12 18:48:47 +02004524 g_assert_not_reached();
4525 }
4526
Alberto Garciaecd30d22021-06-10 15:05:36 +03004527 if (old_child_bs == new_child_bs) {
4528 return 0;
4529 }
4530
4531 if (old_child_bs) {
4532 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004533 return 0;
4534 }
4535
Alberto Garciaecd30d22021-06-10 15:05:36 +03004536 if (old_child_bs->implicit) {
4537 error_setg(errp, "Cannot replace implicit %s child of %s",
4538 child_name, bs->node_name);
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004539 return -EPERM;
4540 }
4541 }
4542
Alberto Garciaecd30d22021-06-10 15:05:36 +03004543 if (bs->drv->is_filter && !old_child_bs) {
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004544 /*
4545 * Filters always have a file or a backing child, so we are trying to
4546 * change wrong child
4547 */
4548 error_setg(errp, "'%s' is a %s filter node that does not support a "
Alberto Garciaecd30d22021-06-10 15:05:36 +03004549 "%s child", bs->node_name, bs->drv->format_name, child_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004550 return -EINVAL;
4551 }
4552
Alberto Garciaecd30d22021-06-10 15:05:36 +03004553 if (is_backing) {
4554 reopen_state->old_backing_bs = old_child_bs;
4555 } else {
4556 reopen_state->old_file_bs = old_child_bs;
4557 }
4558
4559 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4560 tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004561}
4562
4563/*
Jeff Codye971aa12012-09-20 15:13:19 -04004564 * Prepares a BlockDriverState for reopen. All changes are staged in the
4565 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4566 * the block driver layer .bdrv_reopen_prepare()
4567 *
4568 * bs is the BlockDriverState to reopen
4569 * flags are the new open flags
4570 * queue is the reopen queue
4571 *
4572 * Returns 0 on success, non-zero on error. On error errp will be set
4573 * as well.
4574 *
4575 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4576 * It is the responsibility of the caller to then call the abort() or
4577 * commit() for any other BDS that have been left in a prepare() state
4578 *
4579 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004580static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004581 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +03004582 Transaction *change_child_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004583{
4584 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004585 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004586 Error *local_err = NULL;
4587 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004588 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004589 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004590 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004591 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004592 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004593
4594 assert(reopen_state != NULL);
4595 assert(reopen_state->bs->drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004596 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004597 drv = reopen_state->bs->drv;
4598
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004599 /* This function and each driver's bdrv_reopen_prepare() remove
4600 * entries from reopen_state->options as they are processed, so
4601 * we need to make a copy of the original QDict. */
4602 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4603
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004604 /* Process generic block layer options */
4605 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004606 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004607 ret = -EINVAL;
4608 goto error;
4609 }
4610
Alberto Garciae6d79c42018-11-12 16:00:47 +02004611 /* This was already called in bdrv_reopen_queue_child() so the flags
4612 * are up-to-date. This time we simply want to remove the options from
4613 * QemuOpts in order to indicate that they have been processed. */
4614 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004615 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004616 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004617
Alberto Garcia415bbca2018-10-03 13:23:13 +03004618 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004619 if (discard != NULL) {
4620 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4621 error_setg(errp, "Invalid discard option");
4622 ret = -EINVAL;
4623 goto error;
4624 }
4625 }
4626
Alberto Garcia543770b2018-09-06 12:37:09 +03004627 reopen_state->detect_zeroes =
4628 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4629 if (local_err) {
4630 error_propagate(errp, local_err);
4631 ret = -EINVAL;
4632 goto error;
4633 }
4634
Alberto Garcia57f9db92018-09-06 12:37:06 +03004635 /* All other options (including node-name and driver) must be unchanged.
4636 * Put them back into the QDict, so that they are checked at the end
4637 * of this function. */
4638 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004639
Jeff Cody3d8ce172017-04-07 16:55:30 -04004640 /* If we are to stay read-only, do not allow permission change
4641 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4642 * not set, or if the BDS still has copy_on_read enabled */
4643 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004644 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004645 if (local_err) {
4646 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004647 goto error;
4648 }
4649
Jeff Codye971aa12012-09-20 15:13:19 -04004650 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004651 /*
4652 * If a driver-specific option is missing, it means that we
4653 * should reset it to its default value.
4654 * But not all options allow that, so we need to check it first.
4655 */
4656 ret = bdrv_reset_options_allowed(reopen_state->bs,
4657 reopen_state->options, errp);
4658 if (ret) {
4659 goto error;
4660 }
4661
Jeff Codye971aa12012-09-20 15:13:19 -04004662 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4663 if (ret) {
4664 if (local_err != NULL) {
4665 error_propagate(errp, local_err);
4666 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004667 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004668 error_setg(errp, "failed while preparing to reopen image '%s'",
4669 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004670 }
4671 goto error;
4672 }
4673 } else {
4674 /* It is currently mandatory to have a bdrv_reopen_prepare()
4675 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004676 error_setg(errp, "Block format '%s' used by node '%s' "
4677 "does not support reopening files", drv->format_name,
4678 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004679 ret = -1;
4680 goto error;
4681 }
4682
Max Reitz9ad08c42018-11-16 17:45:24 +01004683 drv_prepared = true;
4684
Alberto Garciabacd9b82019-03-12 18:48:46 +02004685 /*
4686 * We must provide the 'backing' option if the BDS has a backing
4687 * file or if the image file has a backing file name as part of
4688 * its metadata. Otherwise the 'backing' option can be omitted.
4689 */
4690 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004691 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004692 error_setg(errp, "backing is missing for '%s'",
4693 reopen_state->bs->node_name);
4694 ret = -EINVAL;
4695 goto error;
4696 }
4697
Alberto Garciacb828c32019-03-12 18:48:47 +02004698 /*
4699 * Allow changing the 'backing' option. The new value can be
4700 * either a reference to an existing node (using its node name)
4701 * or NULL to simply detach the current backing file.
4702 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004703 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4704 change_child_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004705 if (ret < 0) {
4706 goto error;
4707 }
4708 qdict_del(reopen_state->options, "backing");
4709
Alberto Garciaecd30d22021-06-10 15:05:36 +03004710 /* Allow changing the 'file' option. In this case NULL is not allowed */
4711 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4712 change_child_tran, errp);
4713 if (ret < 0) {
4714 goto error;
4715 }
4716 qdict_del(reopen_state->options, "file");
4717
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004718 /* Options that are not handled are only okay if they are unchanged
4719 * compared to the old state. It is expected that some options are only
4720 * used for the initial open, but not reopen (e.g. filename) */
4721 if (qdict_size(reopen_state->options)) {
4722 const QDictEntry *entry = qdict_first(reopen_state->options);
4723
4724 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004725 QObject *new = entry->value;
4726 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004727
Alberto Garciadb905282018-09-06 12:37:05 +03004728 /* Allow child references (child_name=node_name) as long as they
4729 * point to the current child (i.e. everything stays the same). */
4730 if (qobject_type(new) == QTYPE_QSTRING) {
4731 BdrvChild *child;
4732 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4733 if (!strcmp(child->name, entry->key)) {
4734 break;
4735 }
4736 }
4737
4738 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004739 if (!strcmp(child->bs->node_name,
4740 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004741 continue; /* Found child with this name, skip option */
4742 }
4743 }
4744 }
4745
Max Reitz54fd1b02017-11-14 19:01:26 +01004746 /*
4747 * TODO: When using -drive to specify blockdev options, all values
4748 * will be strings; however, when using -blockdev, blockdev-add or
4749 * filenames using the json:{} pseudo-protocol, they will be
4750 * correctly typed.
4751 * In contrast, reopening options are (currently) always strings
4752 * (because you can only specify them through qemu-io; all other
4753 * callers do not specify any options).
4754 * Therefore, when using anything other than -drive to create a BDS,
4755 * this cannot detect non-string options as unchanged, because
4756 * qobject_is_equal() always returns false for objects of different
4757 * type. In the future, this should be remedied by correctly typing
4758 * all options. For now, this is not too big of an issue because
4759 * the user can simply omit options which cannot be changed anyway,
4760 * so they will stay unchanged.
4761 */
4762 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004763 error_setg(errp, "Cannot change the option '%s'", entry->key);
4764 ret = -EINVAL;
4765 goto error;
4766 }
4767 } while ((entry = qdict_next(reopen_state->options, entry)));
4768 }
4769
Jeff Codye971aa12012-09-20 15:13:19 -04004770 ret = 0;
4771
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004772 /* Restore the original reopen_state->options QDict */
4773 qobject_unref(reopen_state->options);
4774 reopen_state->options = qobject_ref(orig_reopen_opts);
4775
Jeff Codye971aa12012-09-20 15:13:19 -04004776error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004777 if (ret < 0 && drv_prepared) {
4778 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4779 * call drv->bdrv_reopen_abort() before signaling an error
4780 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4781 * when the respective bdrv_reopen_prepare() has failed) */
4782 if (drv->bdrv_reopen_abort) {
4783 drv->bdrv_reopen_abort(reopen_state);
4784 }
4785 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004786 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004787 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004788 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004789 return ret;
4790}
4791
4792/*
4793 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4794 * makes them final by swapping the staging BlockDriverState contents into
4795 * the active BlockDriverState contents.
4796 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004797static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004798{
4799 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004800 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004801 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004802
4803 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004804 bs = reopen_state->bs;
4805 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004806 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004807 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004808
4809 /* If there are any driver level actions to take */
4810 if (drv->bdrv_reopen_commit) {
4811 drv->bdrv_reopen_commit(reopen_state);
4812 }
4813
4814 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004815 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004816 qobject_unref(bs->options);
Alberto Garciaab5b52282021-07-08 13:47:05 +02004817 qobject_ref(reopen_state->explicit_options);
4818 qobject_ref(reopen_state->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004819
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004820 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004821 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004822 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004823 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004824
Alberto Garcia50196d72018-09-06 12:37:03 +03004825 /* Remove child references from bs->options and bs->explicit_options.
4826 * Child options were already removed in bdrv_reopen_queue_child() */
4827 QLIST_FOREACH(child, &bs->children, next) {
4828 qdict_del(bs->explicit_options, child->name);
4829 qdict_del(bs->options, child->name);
4830 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004831 /* backing is probably removed, so it's not handled by previous loop */
4832 qdict_del(bs->explicit_options, "backing");
4833 qdict_del(bs->options, "backing");
4834
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004835 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004836}
4837
4838/*
4839 * Abort the reopen, and delete and free the staged changes in
4840 * reopen_state
4841 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004842static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004843{
4844 BlockDriver *drv;
4845
4846 assert(reopen_state != NULL);
4847 drv = reopen_state->bs->drv;
4848 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004849 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004850
4851 if (drv->bdrv_reopen_abort) {
4852 drv->bdrv_reopen_abort(reopen_state);
4853 }
4854}
4855
4856
Max Reitz64dff522016-01-29 16:36:10 +01004857static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004858{
Max Reitz33384422014-06-20 21:57:33 +02004859 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004860 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004861
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004862 GLOBAL_STATE_CODE();
Max Reitz30f55fb2016-05-17 16:41:32 +02004863 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004864
Paolo Bonzinifc272912015-12-23 11:48:24 +01004865 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004866 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004867 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004868
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004869 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004870 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004871 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004872 bs->drv->bdrv_close(bs);
4873 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004874 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004875 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004876
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004877 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004878 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004879 }
4880
Alberto Garciadd4118c2019-05-13 16:46:17 +03004881 bs->backing = NULL;
4882 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004883 g_free(bs->opaque);
4884 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004885 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004886 bs->backing_file[0] = '\0';
4887 bs->backing_format[0] = '\0';
4888 bs->total_sectors = 0;
4889 bs->encrypted = false;
4890 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004891 qobject_unref(bs->options);
4892 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004893 bs->options = NULL;
4894 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004895 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004896 bs->full_open_options = NULL;
Hanna Reitz0bc329f2021-08-12 10:41:44 +02004897 g_free(bs->block_status_cache);
4898 bs->block_status_cache = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004899
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004900 bdrv_release_named_dirty_bitmaps(bs);
4901 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4902
Max Reitz33384422014-06-20 21:57:33 +02004903 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4904 g_free(ban);
4905 }
4906 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004907 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004908
4909 /*
4910 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4911 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4912 * gets called.
4913 */
4914 if (bs->quiesce_counter) {
4915 bdrv_drain_all_end_quiesce(bs);
4916 }
bellardb3380822004-03-14 21:38:54 +00004917}
4918
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004919void bdrv_close_all(void)
4920{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004921 GLOBAL_STATE_CODE();
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04004922 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004923
Max Reitzca9bd242016-01-29 16:36:14 +01004924 /* Drop references from requests still in flight, such as canceled block
4925 * jobs whose AIO context has not been polled yet */
4926 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004927
Max Reitzca9bd242016-01-29 16:36:14 +01004928 blk_remove_all_bs();
4929 blockdev_close_all_bdrv_states();
4930
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004931 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004932}
4933
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004934static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004935{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004936 GQueue *queue;
4937 GHashTable *found;
4938 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004939
Max Reitzbd86fb92020-05-13 13:05:13 +02004940 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004941 return false;
4942 }
4943
Max Reitzec9f10f2018-06-13 20:18:15 +02004944 /* If the child @c belongs to the BDS @to, replacing the current
4945 * c->bs by @to would mean to create a loop.
4946 *
4947 * Such a case occurs when appending a BDS to a backing chain.
4948 * For instance, imagine the following chain:
4949 *
4950 * guest device -> node A -> further backing chain...
4951 *
4952 * Now we create a new BDS B which we want to put on top of this
4953 * chain, so we first attach A as its backing node:
4954 *
4955 * node B
4956 * |
4957 * v
4958 * guest device -> node A -> further backing chain...
4959 *
4960 * Finally we want to replace A by B. When doing that, we want to
4961 * replace all pointers to A by pointers to B -- except for the
4962 * pointer from B because (1) that would create a loop, and (2)
4963 * that pointer should simply stay intact:
4964 *
4965 * guest device -> node B
4966 * |
4967 * v
4968 * node A -> further backing chain...
4969 *
4970 * In general, when replacing a node A (c->bs) by a node B (@to),
4971 * if A is a child of B, that means we cannot replace A by B there
4972 * because that would create a loop. Silently detaching A from B
4973 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004974 * place there is the most sensible choice.
4975 *
4976 * We would also create a loop in any cases where @c is only
4977 * indirectly referenced by @to. Prevent this by returning false
4978 * if @c is found (by breadth-first search) anywhere in the whole
4979 * subtree of @to.
4980 */
4981
4982 ret = true;
4983 found = g_hash_table_new(NULL, NULL);
4984 g_hash_table_add(found, to);
4985 queue = g_queue_new();
4986 g_queue_push_tail(queue, to);
4987
4988 while (!g_queue_is_empty(queue)) {
4989 BlockDriverState *v = g_queue_pop_head(queue);
4990 BdrvChild *c2;
4991
4992 QLIST_FOREACH(c2, &v->children, next) {
4993 if (c2 == c) {
4994 ret = false;
4995 break;
4996 }
4997
4998 if (g_hash_table_contains(found, c2->bs)) {
4999 continue;
5000 }
5001
5002 g_queue_push_tail(queue, c2->bs);
5003 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005004 }
5005 }
5006
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005007 g_queue_free(queue);
5008 g_hash_table_destroy(found);
5009
5010 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005011}
5012
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005013typedef struct BdrvRemoveFilterOrCowChild {
5014 BdrvChild *child;
5015 bool is_backing;
5016} BdrvRemoveFilterOrCowChild;
5017
5018static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
5019{
5020 BdrvRemoveFilterOrCowChild *s = opaque;
5021 BlockDriverState *parent_bs = s->child->opaque;
5022
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005023 if (s->is_backing) {
5024 parent_bs->backing = s->child;
5025 } else {
5026 parent_bs->file = s->child;
5027 }
5028
5029 /*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03005030 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005031 * because that function is transactionable and it registered own completion
5032 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
5033 * called automatically.
5034 */
5035}
5036
5037static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
5038{
5039 BdrvRemoveFilterOrCowChild *s = opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005040 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005041 bdrv_child_free(s->child);
5042}
5043
5044static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
5045 .abort = bdrv_remove_filter_or_cow_child_abort,
5046 .commit = bdrv_remove_filter_or_cow_child_commit,
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03005047 .clean = g_free,
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005048};
5049
5050/*
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005051 * A function to remove backing or file child of @bs.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03005052 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005053 */
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005054static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
5055 BdrvChild *child,
5056 Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005057{
5058 BdrvRemoveFilterOrCowChild *s;
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005059
Vladimir Sementsov-Ogievskiya2c37a32022-07-26 23:11:30 +03005060 assert(child == bs->backing || child == bs->file);
5061
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005062 if (!child) {
5063 return;
5064 }
5065
5066 if (child->bs) {
Vladimir Sementsov-Ogievskiya2c37a32022-07-26 23:11:30 +03005067 bdrv_replace_child_tran(child, NULL, tran);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005068 }
5069
5070 s = g_new(BdrvRemoveFilterOrCowChild, 1);
5071 *s = (BdrvRemoveFilterOrCowChild) {
5072 .child = child,
Vladimir Sementsov-Ogievskiya2c37a32022-07-26 23:11:30 +03005073 .is_backing = (child == bs->backing),
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005074 };
5075 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03005076
Vladimir Sementsov-Ogievskiya2c37a32022-07-26 23:11:30 +03005077 if (s->is_backing) {
5078 bs->backing = NULL;
5079 } else {
5080 bs->file = NULL;
5081 }
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005082}
5083
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005084/*
5085 * A function to remove backing-chain child of @bs if exists: cow child for
5086 * format nodes (always .backing) and filter child for filters (may be .file or
5087 * .backing)
5088 */
5089static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
5090 Transaction *tran)
5091{
5092 bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
5093}
5094
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005095static int bdrv_replace_node_noperm(BlockDriverState *from,
5096 BlockDriverState *to,
5097 bool auto_skip, Transaction *tran,
5098 Error **errp)
5099{
5100 BdrvChild *c, *next;
5101
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005102 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005103
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005104 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5105 assert(c->bs == from);
5106 if (!should_update_child(c, to)) {
5107 if (auto_skip) {
5108 continue;
5109 }
5110 error_setg(errp, "Should not change '%s' link to '%s'",
5111 c->name, from->node_name);
5112 return -EINVAL;
5113 }
5114 if (c->frozen) {
5115 error_setg(errp, "Cannot change '%s' link to '%s'",
5116 c->name, from->node_name);
5117 return -EPERM;
5118 }
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03005119 bdrv_replace_child_tran(c, to, tran);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005120 }
5121
5122 return 0;
5123}
5124
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005125/*
5126 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5127 * if it creates a parent-child relation loop or if parent is block-job.
5128 *
5129 * With auto_skip=false the error is returned if from has a parent which should
5130 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005131 *
5132 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5133 * case backing link of the cow-parent of @to is removed.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005134 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005135static int bdrv_replace_node_common(BlockDriverState *from,
5136 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005137 bool auto_skip, bool detach_subchain,
5138 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005139{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005140 Transaction *tran = tran_new();
5141 g_autoptr(GHashTable) found = NULL;
5142 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04005143 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005144 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005145
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005146 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005147
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005148 if (detach_subchain) {
5149 assert(bdrv_chain_contains(from, to));
5150 assert(from != to);
5151 for (to_cow_parent = from;
5152 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5153 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5154 {
5155 ;
5156 }
5157 }
5158
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005159 /* Make sure that @from doesn't go away until we have successfully attached
5160 * all of its parents to @to. */
5161 bdrv_ref(from);
5162
Kevin Wolff871abd2019-05-21 19:00:25 +02005163 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01005164 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02005165 bdrv_drained_begin(from);
5166
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005167 /*
5168 * Do the replacement without permission update.
5169 * Replacement may influence the permissions, we should calculate new
5170 * permissions based on new graph. If we fail, we'll roll-back the
5171 * replacement.
5172 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005173 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5174 if (ret < 0) {
5175 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005176 }
5177
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005178 if (detach_subchain) {
5179 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
5180 }
5181
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005182 found = g_hash_table_new(NULL, NULL);
5183
5184 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5185 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5186
5187 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005188 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005189 goto out;
5190 }
5191
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005192 ret = 0;
5193
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005194out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005195 tran_finalize(tran, ret);
5196
Kevin Wolff871abd2019-05-21 19:00:25 +02005197 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005198 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005199
5200 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005201}
5202
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005203int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5204 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005205{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005206 GLOBAL_STATE_CODE();
5207
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005208 return bdrv_replace_node_common(from, to, true, false, errp);
5209}
5210
5211int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5212{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005213 GLOBAL_STATE_CODE();
5214
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005215 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5216 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005217}
5218
Jeff Cody8802d1f2012-02-28 15:54:06 -05005219/*
5220 * Add new bs contents at the top of an image chain while the chain is
5221 * live, while keeping required fields on the top layer.
5222 *
5223 * This will modify the BlockDriverState fields, and swap contents
5224 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5225 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005226 * bs_new must not be attached to a BlockBackend and must not have backing
5227 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005228 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005229 * This function does not create any image files.
5230 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005231int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5232 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005233{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005234 int ret;
5235 Transaction *tran = tran_new();
5236
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005237 GLOBAL_STATE_CODE();
5238
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005239 assert(!bs_new->backing);
5240
5241 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5242 &child_of_bds, bdrv_backing_role(bs_new),
5243 &bs_new->backing, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005244 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005245 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005246 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005247
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005248 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005249 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005250 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005251 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005252
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005253 ret = bdrv_refresh_perms(bs_new, errp);
5254out:
5255 tran_finalize(tran, ret);
5256
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005257 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005258
5259 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005260}
5261
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005262/* Not for empty child */
5263int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5264 Error **errp)
5265{
5266 int ret;
5267 Transaction *tran = tran_new();
5268 g_autoptr(GHashTable) found = NULL;
5269 g_autoptr(GSList) refresh_list = NULL;
5270 BlockDriverState *old_bs = child->bs;
5271
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005272 GLOBAL_STATE_CODE();
5273
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005274 bdrv_ref(old_bs);
5275 bdrv_drained_begin(old_bs);
5276 bdrv_drained_begin(new_bs);
5277
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03005278 bdrv_replace_child_tran(child, new_bs, tran);
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005279
5280 found = g_hash_table_new(NULL, NULL);
5281 refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5282 refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5283
5284 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5285
5286 tran_finalize(tran, ret);
5287
5288 bdrv_drained_end(old_bs);
5289 bdrv_drained_end(new_bs);
5290 bdrv_unref(old_bs);
5291
5292 return ret;
5293}
5294
Fam Zheng4f6fd342013-08-23 09:14:47 +08005295static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005296{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005297 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005298 assert(!bs->refcnt);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005299 GLOBAL_STATE_CODE();
Markus Armbruster18846de2010-06-29 16:58:30 +02005300
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005301 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005302 if (bs->node_name[0] != '\0') {
5303 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5304 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005305 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5306
Anton Kuchin30c321f2019-05-07 11:12:56 +03005307 bdrv_close(bs);
5308
Anthony Liguori7267c092011-08-20 22:09:37 -05005309 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005310}
5311
Vladimir Sementsov-Ogievskiy96796fa2021-09-20 14:55:36 +03005312
5313/*
5314 * Replace @bs by newly created block node.
5315 *
5316 * @options is a QDict of options to pass to the block drivers, or NULL for an
5317 * empty set of options. The reference to the QDict belongs to the block layer
5318 * after the call (even on failure), so if the caller intends to reuse the
5319 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5320 */
5321BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005322 int flags, Error **errp)
5323{
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005324 ERRP_GUARD();
5325 int ret;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005326 BlockDriverState *new_node_bs = NULL;
5327 const char *drvname, *node_name;
5328 BlockDriver *drv;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005329
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005330 drvname = qdict_get_try_str(options, "driver");
5331 if (!drvname) {
5332 error_setg(errp, "driver is not specified");
5333 goto fail;
5334 }
5335
5336 drv = bdrv_find_format(drvname);
5337 if (!drv) {
5338 error_setg(errp, "Unknown driver: '%s'", drvname);
5339 goto fail;
5340 }
5341
5342 node_name = qdict_get_try_str(options, "node-name");
5343
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005344 GLOBAL_STATE_CODE();
5345
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005346 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5347 errp);
5348 options = NULL; /* bdrv_new_open_driver() eats options */
5349 if (!new_node_bs) {
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005350 error_prepend(errp, "Could not create node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005351 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005352 }
5353
5354 bdrv_drained_begin(bs);
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005355 ret = bdrv_replace_node(bs, new_node_bs, errp);
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005356 bdrv_drained_end(bs);
5357
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005358 if (ret < 0) {
5359 error_prepend(errp, "Could not replace node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005360 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005361 }
5362
5363 return new_node_bs;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005364
5365fail:
5366 qobject_unref(options);
5367 bdrv_unref(new_node_bs);
5368 return NULL;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005369}
5370
aliguorie97fc192009-04-21 23:11:50 +00005371/*
5372 * Run consistency checks on an image
5373 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005374 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005375 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005376 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005377 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005378int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5379 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005380{
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05005381 IO_CODE();
Max Reitz908bcd52014-08-07 22:47:55 +02005382 if (bs->drv == NULL) {
5383 return -ENOMEDIUM;
5384 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005385 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005386 return -ENOTSUP;
5387 }
5388
Kevin Wolfe076f332010-06-29 11:43:13 +02005389 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005390 return bs->drv->bdrv_co_check(bs, res, fix);
5391}
5392
Kevin Wolf756e6732010-01-12 12:55:17 +01005393/*
5394 * Return values:
5395 * 0 - success
5396 * -EINVAL - backing format specified, but no file
5397 * -ENOSPC - can't update the backing file because no space is left in the
5398 * image file header
5399 * -ENOTSUP - format driver doesn't support changing the backing file
5400 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005401int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
Eric Blake497a30d2021-05-03 14:36:00 -07005402 const char *backing_fmt, bool require)
Kevin Wolf756e6732010-01-12 12:55:17 +01005403{
5404 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005405 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005406
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005407 GLOBAL_STATE_CODE();
5408
Max Reitzd470ad42017-11-10 21:31:09 +01005409 if (!drv) {
5410 return -ENOMEDIUM;
5411 }
5412
Paolo Bonzini5f377792012-04-12 14:01:01 +02005413 /* Backing file format doesn't make sense without a backing file */
5414 if (backing_fmt && !backing_file) {
5415 return -EINVAL;
5416 }
5417
Eric Blake497a30d2021-05-03 14:36:00 -07005418 if (require && backing_file && !backing_fmt) {
5419 return -EINVAL;
Eric Blakee54ee1b2020-07-06 15:39:53 -05005420 }
5421
Kevin Wolf756e6732010-01-12 12:55:17 +01005422 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005423 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005424 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005425 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005426 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005427
5428 if (ret == 0) {
5429 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5430 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005431 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5432 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005433 }
5434 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005435}
5436
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005437/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005438 * Finds the first non-filter node above bs in the chain between
5439 * active and bs. The returned node is either an immediate parent of
5440 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005441 *
5442 * Returns NULL if bs is not found in active's image chain,
5443 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005444 *
5445 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005446 */
5447BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5448 BlockDriverState *bs)
5449{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005450
5451 GLOBAL_STATE_CODE();
5452
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005453 bs = bdrv_skip_filters(bs);
5454 active = bdrv_skip_filters(active);
5455
5456 while (active) {
5457 BlockDriverState *next = bdrv_backing_chain_next(active);
5458 if (bs == next) {
5459 return active;
5460 }
5461 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005462 }
5463
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005464 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005465}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005466
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005467/* Given a BDS, searches for the base layer. */
5468BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5469{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005470 GLOBAL_STATE_CODE();
5471
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005472 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005473}
5474
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005475/*
Max Reitz7b99a262019-06-12 16:07:11 +02005476 * Return true if at least one of the COW (backing) and filter links
5477 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005478 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005479 */
5480bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5481 Error **errp)
5482{
5483 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005484 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005485
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005486 GLOBAL_STATE_CODE();
5487
Max Reitz7b99a262019-06-12 16:07:11 +02005488 for (i = bs; i != base; i = child_bs(child)) {
5489 child = bdrv_filter_or_cow_child(i);
5490
5491 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005492 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005493 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005494 return true;
5495 }
5496 }
5497
5498 return false;
5499}
5500
5501/*
Max Reitz7b99a262019-06-12 16:07:11 +02005502 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005503 * If any of the links is already frozen the operation is aborted and
5504 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005505 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005506 * Returns 0 on success. On failure returns < 0 and sets @errp.
5507 */
5508int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5509 Error **errp)
5510{
5511 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005512 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005513
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005514 GLOBAL_STATE_CODE();
5515
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005516 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5517 return -EPERM;
5518 }
5519
Max Reitz7b99a262019-06-12 16:07:11 +02005520 for (i = bs; i != base; i = child_bs(child)) {
5521 child = bdrv_filter_or_cow_child(i);
5522 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005523 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005524 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005525 return -EPERM;
5526 }
5527 }
5528
Max Reitz7b99a262019-06-12 16:07:11 +02005529 for (i = bs; i != base; i = child_bs(child)) {
5530 child = bdrv_filter_or_cow_child(i);
5531 if (child) {
5532 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005533 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005534 }
5535
5536 return 0;
5537}
5538
5539/*
Max Reitz7b99a262019-06-12 16:07:11 +02005540 * Unfreeze all COW (backing) and filter links between @bs and @base.
5541 * The caller must ensure that all links are frozen before using this
5542 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005543 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005544 */
5545void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5546{
5547 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005548 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005549
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005550 GLOBAL_STATE_CODE();
5551
Max Reitz7b99a262019-06-12 16:07:11 +02005552 for (i = bs; i != base; i = child_bs(child)) {
5553 child = bdrv_filter_or_cow_child(i);
5554 if (child) {
5555 assert(child->frozen);
5556 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005557 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005558 }
5559}
5560
5561/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005562 * Drops images above 'base' up to and including 'top', and sets the image
5563 * above 'top' to have base as its backing file.
5564 *
5565 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5566 * information in 'bs' can be properly updated.
5567 *
5568 * E.g., this will convert the following chain:
5569 * bottom <- base <- intermediate <- top <- active
5570 *
5571 * to
5572 *
5573 * bottom <- base <- active
5574 *
5575 * It is allowed for bottom==base, in which case it converts:
5576 *
5577 * base <- intermediate <- top <- active
5578 *
5579 * to
5580 *
5581 * base <- active
5582 *
Jeff Cody54e26902014-06-25 15:40:10 -04005583 * If backing_file_str is non-NULL, it will be used when modifying top's
5584 * overlay image metadata.
5585 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005586 * Error conditions:
5587 * if active == top, that is considered an error
5588 *
5589 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005590int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5591 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005592{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005593 BlockDriverState *explicit_top = top;
5594 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005595 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005596 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005597 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005598 g_autoptr(GSList) updated_children = NULL;
5599 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005600
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005601 GLOBAL_STATE_CODE();
5602
Kevin Wolf6858eba2017-06-29 19:32:21 +02005603 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005604 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005605
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005606 if (!top->drv || !base->drv) {
5607 goto exit;
5608 }
5609
Kevin Wolf5db15a52015-09-14 15:33:33 +02005610 /* Make sure that base is in the backing chain of top */
5611 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005612 goto exit;
5613 }
5614
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005615 /* If 'base' recursively inherits from 'top' then we should set
5616 * base->inherits_from to top->inherits_from after 'top' and all
5617 * other intermediate nodes have been dropped.
5618 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5619 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005620 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005621 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5622
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005623 /* success - we can delete the intermediate states, and link top->base */
Max Reitzf30c66b2019-02-01 20:29:05 +01005624 if (!backing_file_str) {
5625 bdrv_refresh_filename(base);
5626 backing_file_str = base->filename;
5627 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005628
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005629 QLIST_FOREACH(c, &top->parents, next_parent) {
5630 updated_children = g_slist_prepend(updated_children, c);
5631 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005632
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005633 /*
5634 * It seems correct to pass detach_subchain=true here, but it triggers
5635 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5636 * another drained section, which modify the graph (for example, removing
5637 * the child, which we keep in updated_children list). So, it's a TODO.
5638 *
5639 * Note, bug triggered if pass detach_subchain=true here and run
5640 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5641 * That's a FIXME.
5642 */
5643 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005644 if (local_err) {
5645 error_report_err(local_err);
5646 goto exit;
5647 }
5648
5649 for (p = updated_children; p; p = p->next) {
5650 c = p->data;
5651
Max Reitzbd86fb92020-05-13 13:05:13 +02005652 if (c->klass->update_filename) {
5653 ret = c->klass->update_filename(c, base, backing_file_str,
5654 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005655 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005656 /*
5657 * TODO: Actually, we want to rollback all previous iterations
5658 * of this loop, and (which is almost impossible) previous
5659 * bdrv_replace_node()...
5660 *
5661 * Note, that c->klass->update_filename may lead to permission
5662 * update, so it's a bad idea to call it inside permission
5663 * update transaction of bdrv_replace_node.
5664 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005665 error_report_err(local_err);
5666 goto exit;
5667 }
5668 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005669 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005670
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005671 if (update_inherits_from) {
5672 base->inherits_from = explicit_top->inherits_from;
5673 }
5674
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005675 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005676exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005677 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005678 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005679 return ret;
5680}
5681
bellard83f64092006-08-01 16:21:11 +00005682/**
Max Reitz081e4652019-06-12 18:14:13 +02005683 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5684 * sums the size of all data-bearing children. (This excludes backing
5685 * children.)
5686 */
5687static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5688{
5689 BdrvChild *child;
5690 int64_t child_size, sum = 0;
5691
5692 QLIST_FOREACH(child, &bs->children, next) {
5693 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5694 BDRV_CHILD_FILTERED))
5695 {
5696 child_size = bdrv_get_allocated_file_size(child->bs);
5697 if (child_size < 0) {
5698 return child_size;
5699 }
5700 sum += child_size;
5701 }
5702 }
5703
5704 return sum;
5705}
5706
5707/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005708 * Length of a allocated file in bytes. Sparse files are counted by actual
5709 * allocated space. Return < 0 if error or unknown.
5710 */
5711int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5712{
5713 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005714 IO_CODE();
5715
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005716 if (!drv) {
5717 return -ENOMEDIUM;
5718 }
5719 if (drv->bdrv_get_allocated_file_size) {
5720 return drv->bdrv_get_allocated_file_size(bs);
5721 }
Max Reitz081e4652019-06-12 18:14:13 +02005722
5723 if (drv->bdrv_file_open) {
5724 /*
5725 * Protocol drivers default to -ENOTSUP (most of their data is
5726 * not stored in any of their children (if they even have any),
5727 * so there is no generic way to figure it out).
5728 */
5729 return -ENOTSUP;
5730 } else if (drv->is_filter) {
5731 /* Filter drivers default to the size of their filtered child */
5732 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5733 } else {
5734 /* Other drivers default to summing their children's sizes */
5735 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005736 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005737}
5738
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005739/*
5740 * bdrv_measure:
5741 * @drv: Format driver
5742 * @opts: Creation options for new image
5743 * @in_bs: Existing image containing data for new image (may be NULL)
5744 * @errp: Error object
5745 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5746 * or NULL on error
5747 *
5748 * Calculate file size required to create a new image.
5749 *
5750 * If @in_bs is given then space for allocated clusters and zero clusters
5751 * from that image are included in the calculation. If @opts contains a
5752 * backing file that is shared by @in_bs then backing clusters may be omitted
5753 * from the calculation.
5754 *
5755 * If @in_bs is NULL then the calculation includes no allocated clusters
5756 * unless a preallocation option is given in @opts.
5757 *
5758 * Note that @in_bs may use a different BlockDriver from @drv.
5759 *
5760 * If an error occurs the @errp pointer is set.
5761 */
5762BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5763 BlockDriverState *in_bs, Error **errp)
5764{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005765 IO_CODE();
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005766 if (!drv->bdrv_measure) {
5767 error_setg(errp, "Block driver '%s' does not support size measurement",
5768 drv->format_name);
5769 return NULL;
5770 }
5771
5772 return drv->bdrv_measure(opts, in_bs, errp);
5773}
5774
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005775/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005776 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005777 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005778int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005779{
5780 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005781 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005782
bellard83f64092006-08-01 16:21:11 +00005783 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005784 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005785
Kevin Wolfb94a2612013-10-29 12:18:58 +01005786 if (drv->has_variable_length) {
5787 int ret = refresh_total_sectors(bs, bs->total_sectors);
5788 if (ret < 0) {
5789 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005790 }
bellard83f64092006-08-01 16:21:11 +00005791 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005792 return bs->total_sectors;
5793}
5794
5795/**
5796 * Return length in bytes on success, -errno on error.
5797 * The length is always a multiple of BDRV_SECTOR_SIZE.
5798 */
5799int64_t bdrv_getlength(BlockDriverState *bs)
5800{
5801 int64_t ret = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005802 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005803
Eric Blake122860b2020-11-05 09:51:22 -06005804 if (ret < 0) {
5805 return ret;
5806 }
5807 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5808 return -EFBIG;
5809 }
5810 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005811}
5812
bellard19cb3732006-08-19 11:45:59 +00005813/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005814void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005815{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005816 int64_t nb_sectors = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005817 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005818
5819 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005820}
bellardcf989512004-02-16 21:56:36 +00005821
Eric Blake54115412016-06-23 16:37:26 -06005822bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005823{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005824 IO_CODE();
ths985a03b2007-12-24 16:10:43 +00005825 return bs->sg;
5826}
5827
Max Reitzae23f782019-06-12 22:57:15 +02005828/**
5829 * Return whether the given node supports compressed writes.
5830 */
5831bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5832{
5833 BlockDriverState *filtered;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005834 IO_CODE();
Max Reitzae23f782019-06-12 22:57:15 +02005835
5836 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5837 return false;
5838 }
5839
5840 filtered = bdrv_filter_bs(bs);
5841 if (filtered) {
5842 /*
5843 * Filters can only forward compressed writes, so we have to
5844 * check the child.
5845 */
5846 return bdrv_supports_compressed_writes(filtered);
5847 }
5848
5849 return true;
5850}
5851
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005852const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005853{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005854 IO_CODE();
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005855 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005856}
5857
Stefan Hajnocziada42402014-08-27 12:08:55 +01005858static int qsort_strcmp(const void *a, const void *b)
5859{
Max Reitzceff5bd2016-10-12 22:49:05 +02005860 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005861}
5862
ths5fafdf22007-09-16 21:08:06 +00005863void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005864 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005865{
5866 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005867 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005868 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005869 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005870
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005871 GLOBAL_STATE_CODE();
5872
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005873 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005874 if (drv->format_name) {
5875 bool found = false;
5876 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005877
5878 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5879 continue;
5880 }
5881
Jeff Codye855e4f2014-04-28 18:29:54 -04005882 while (formats && i && !found) {
5883 found = !strcmp(formats[--i], drv->format_name);
5884 }
5885
5886 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005887 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005888 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005889 }
5890 }
bellardea2384d2004-08-01 21:59:26 +00005891 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005892
Max Reitzeb0df692016-10-12 22:49:06 +02005893 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5894 const char *format_name = block_driver_modules[i].format_name;
5895
5896 if (format_name) {
5897 bool found = false;
5898 int j = count;
5899
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005900 if (use_bdrv_whitelist &&
5901 !bdrv_format_is_whitelisted(format_name, read_only)) {
5902 continue;
5903 }
5904
Max Reitzeb0df692016-10-12 22:49:06 +02005905 while (formats && j && !found) {
5906 found = !strcmp(formats[--j], format_name);
5907 }
5908
5909 if (!found) {
5910 formats = g_renew(const char *, formats, count + 1);
5911 formats[count++] = format_name;
5912 }
5913 }
5914 }
5915
Stefan Hajnocziada42402014-08-27 12:08:55 +01005916 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5917
5918 for (i = 0; i < count; i++) {
5919 it(opaque, formats[i]);
5920 }
5921
Jeff Codye855e4f2014-04-28 18:29:54 -04005922 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005923}
5924
Benoît Canetdc364f42014-01-23 21:31:32 +01005925/* This function is to find a node in the bs graph */
5926BlockDriverState *bdrv_find_node(const char *node_name)
5927{
5928 BlockDriverState *bs;
5929
5930 assert(node_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005931 GLOBAL_STATE_CODE();
Benoît Canetdc364f42014-01-23 21:31:32 +01005932
5933 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5934 if (!strcmp(node_name, bs->node_name)) {
5935 return bs;
5936 }
5937 }
5938 return NULL;
5939}
5940
Benoît Canetc13163f2014-01-23 21:31:34 +01005941/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005942BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5943 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005944{
Eric Blake9812e712020-10-27 00:05:47 -05005945 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005946 BlockDriverState *bs;
5947
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005948 GLOBAL_STATE_CODE();
5949
Benoît Canetc13163f2014-01-23 21:31:34 +01005950 list = NULL;
5951 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005952 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005953 if (!info) {
5954 qapi_free_BlockDeviceInfoList(list);
5955 return NULL;
5956 }
Eric Blake9812e712020-10-27 00:05:47 -05005957 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005958 }
5959
5960 return list;
5961}
5962
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005963typedef struct XDbgBlockGraphConstructor {
5964 XDbgBlockGraph *graph;
5965 GHashTable *graph_nodes;
5966} XDbgBlockGraphConstructor;
5967
5968static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5969{
5970 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5971
5972 gr->graph = g_new0(XDbgBlockGraph, 1);
5973 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5974
5975 return gr;
5976}
5977
5978static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5979{
5980 XDbgBlockGraph *graph = gr->graph;
5981
5982 g_hash_table_destroy(gr->graph_nodes);
5983 g_free(gr);
5984
5985 return graph;
5986}
5987
5988static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5989{
5990 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5991
5992 if (ret != 0) {
5993 return ret;
5994 }
5995
5996 /*
5997 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5998 * answer of g_hash_table_lookup.
5999 */
6000 ret = g_hash_table_size(gr->graph_nodes) + 1;
6001 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6002
6003 return ret;
6004}
6005
6006static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6007 XDbgBlockGraphNodeType type, const char *name)
6008{
6009 XDbgBlockGraphNode *n;
6010
6011 n = g_new0(XDbgBlockGraphNode, 1);
6012
6013 n->id = xdbg_graph_node_num(gr, node);
6014 n->type = type;
6015 n->name = g_strdup(name);
6016
Eric Blake9812e712020-10-27 00:05:47 -05006017 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006018}
6019
6020static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6021 const BdrvChild *child)
6022{
Max Reitzcdb1cec2019-11-08 13:34:52 +01006023 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006024 XDbgBlockGraphEdge *edge;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05006025 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006026
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006027 edge = g_new0(XDbgBlockGraphEdge, 1);
6028
6029 edge->parent = xdbg_graph_node_num(gr, parent);
6030 edge->child = xdbg_graph_node_num(gr, child->bs);
6031 edge->name = g_strdup(child->name);
6032
Max Reitzcdb1cec2019-11-08 13:34:52 +01006033 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6034 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6035
6036 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006037 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006038 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01006039 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006040 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006041 }
6042 }
6043
Eric Blake9812e712020-10-27 00:05:47 -05006044 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006045}
6046
6047
6048XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6049{
6050 BlockBackend *blk;
6051 BlockJob *job;
6052 BlockDriverState *bs;
6053 BdrvChild *child;
6054 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6055
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006056 GLOBAL_STATE_CODE();
6057
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006058 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6059 char *allocated_name = NULL;
6060 const char *name = blk_name(blk);
6061
6062 if (!*name) {
6063 name = allocated_name = blk_get_attached_dev_id(blk);
6064 }
6065 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6066 name);
6067 g_free(allocated_name);
6068 if (blk_root(blk)) {
6069 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6070 }
6071 }
6072
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04006073 WITH_JOB_LOCK_GUARD() {
6074 for (job = block_job_next_locked(NULL); job;
6075 job = block_job_next_locked(job)) {
6076 GSList *el;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006077
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04006078 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6079 job->job.id);
6080 for (el = job->nodes; el; el = el->next) {
6081 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6082 }
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006083 }
6084 }
6085
6086 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6087 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6088 bs->node_name);
6089 QLIST_FOREACH(child, &bs->children, next) {
6090 xdbg_graph_add_edge(gr, bs, child);
6091 }
6092 }
6093
6094 return xdbg_graph_finalize(gr);
6095}
6096
Benoît Canet12d3ba82014-01-23 21:31:35 +01006097BlockDriverState *bdrv_lookup_bs(const char *device,
6098 const char *node_name,
6099 Error **errp)
6100{
Markus Armbruster7f06d472014-10-07 13:59:12 +02006101 BlockBackend *blk;
6102 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006103
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006104 GLOBAL_STATE_CODE();
6105
Benoît Canet12d3ba82014-01-23 21:31:35 +01006106 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02006107 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006108
Markus Armbruster7f06d472014-10-07 13:59:12 +02006109 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006110 bs = blk_bs(blk);
6111 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02006112 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02006113 }
6114
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006115 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006116 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006117 }
6118
Benoît Canetdd67fa52014-02-12 17:15:06 +01006119 if (node_name) {
6120 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006121
Benoît Canetdd67fa52014-02-12 17:15:06 +01006122 if (bs) {
6123 return bs;
6124 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006125 }
6126
Connor Kuehl785ec4b2021-03-05 09:19:28 -06006127 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01006128 device ? device : "",
6129 node_name ? node_name : "");
6130 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006131}
6132
Jeff Cody5a6684d2014-06-25 15:40:09 -04006133/* If 'base' is in the same chain as 'top', return true. Otherwise,
6134 * return false. If either argument is NULL, return false. */
6135bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6136{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006137
6138 GLOBAL_STATE_CODE();
6139
Jeff Cody5a6684d2014-06-25 15:40:09 -04006140 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006141 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04006142 }
6143
6144 return top != NULL;
6145}
6146
Fam Zheng04df7652014-10-31 11:32:54 +08006147BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6148{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006149 GLOBAL_STATE_CODE();
Fam Zheng04df7652014-10-31 11:32:54 +08006150 if (!bs) {
6151 return QTAILQ_FIRST(&graph_bdrv_states);
6152 }
6153 return QTAILQ_NEXT(bs, node_list);
6154}
6155
Kevin Wolf0f122642018-03-28 18:29:18 +02006156BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6157{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006158 GLOBAL_STATE_CODE();
Kevin Wolf0f122642018-03-28 18:29:18 +02006159 if (!bs) {
6160 return QTAILQ_FIRST(&all_bdrv_states);
6161 }
6162 return QTAILQ_NEXT(bs, bs_list);
6163}
6164
Fam Zheng20a9e772014-10-31 11:32:55 +08006165const char *bdrv_get_node_name(const BlockDriverState *bs)
6166{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006167 IO_CODE();
Fam Zheng20a9e772014-10-31 11:32:55 +08006168 return bs->node_name;
6169}
6170
Kevin Wolf1f0c4612016-03-22 18:38:44 +01006171const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006172{
6173 BdrvChild *c;
6174 const char *name;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05006175 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006176
6177 /* If multiple parents have a name, just pick the first one. */
6178 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006179 if (c->klass->get_name) {
6180 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006181 if (name && *name) {
6182 return name;
6183 }
6184 }
6185 }
6186
6187 return NULL;
6188}
6189
Markus Armbruster7f06d472014-10-07 13:59:12 +02006190/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02006191const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00006192{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006193 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006194 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00006195}
6196
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006197/* This can be used to identify nodes that might not have a device
6198 * name associated. Since node and device names live in the same
6199 * namespace, the result is unambiguous. The exception is if both are
6200 * absent, then this returns an empty (non-null) string. */
6201const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6202{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006203 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006204 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006205}
6206
Markus Armbrusterc8433282012-06-05 16:49:24 +02006207int bdrv_get_flags(BlockDriverState *bs)
6208{
Hanna Reitz15aee7a2022-04-27 13:40:54 +02006209 IO_CODE();
Markus Armbrusterc8433282012-06-05 16:49:24 +02006210 return bs->open_flags;
6211}
6212
Peter Lieven3ac21622013-06-28 12:47:42 +02006213int bdrv_has_zero_init_1(BlockDriverState *bs)
6214{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006215 GLOBAL_STATE_CODE();
Peter Lieven3ac21622013-06-28 12:47:42 +02006216 return 1;
6217}
6218
Kevin Wolff2feebb2010-04-14 17:30:35 +02006219int bdrv_has_zero_init(BlockDriverState *bs)
6220{
Max Reitz93393e62019-06-12 17:03:38 +02006221 BlockDriverState *filtered;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006222 GLOBAL_STATE_CODE();
Max Reitz93393e62019-06-12 17:03:38 +02006223
Max Reitzd470ad42017-11-10 21:31:09 +01006224 if (!bs->drv) {
6225 return 0;
6226 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006227
Paolo Bonzini11212d82013-09-04 19:00:27 +02006228 /* If BS is a copy on write image, it is initialized to
6229 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02006230 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02006231 return 0;
6232 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02006233 if (bs->drv->bdrv_has_zero_init) {
6234 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02006235 }
Max Reitz93393e62019-06-12 17:03:38 +02006236
6237 filtered = bdrv_filter_bs(bs);
6238 if (filtered) {
6239 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006240 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006241
Peter Lieven3ac21622013-06-28 12:47:42 +02006242 /* safe default */
6243 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02006244}
6245
Peter Lieven4ce78692013-10-24 12:06:54 +02006246bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6247{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006248 IO_CODE();
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03006249 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02006250 return false;
6251 }
6252
Eric Blakee24d8132018-01-26 13:34:39 -06006253 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02006254}
6255
ths5fafdf22007-09-16 21:08:06 +00006256void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00006257 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00006258{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006259 IO_CODE();
Kevin Wolf3574c602011-10-26 11:02:11 +02006260 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00006261}
6262
bellardfaea38e2006-08-05 21:31:00 +00006263int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6264{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006265 int ret;
bellardfaea38e2006-08-05 21:31:00 +00006266 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006267 IO_CODE();
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006268 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6269 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00006270 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006271 }
6272 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02006273 BlockDriverState *filtered = bdrv_filter_bs(bs);
6274 if (filtered) {
6275 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006276 }
bellardfaea38e2006-08-05 21:31:00 +00006277 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006278 }
bellardfaea38e2006-08-05 21:31:00 +00006279 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006280 ret = drv->bdrv_get_info(bs, bdi);
6281 if (ret < 0) {
6282 return ret;
6283 }
6284
6285 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6286 return -EINVAL;
6287 }
6288
6289 return 0;
bellardfaea38e2006-08-05 21:31:00 +00006290}
6291
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006292ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6293 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02006294{
6295 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006296 IO_CODE();
Max Reitzeae041f2013-10-09 10:46:16 +02006297 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006298 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02006299 }
6300 return NULL;
6301}
6302
Anton Nefedovd9245592019-09-23 15:17:37 +03006303BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6304{
6305 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006306 IO_CODE();
Anton Nefedovd9245592019-09-23 15:17:37 +03006307 if (!drv || !drv->bdrv_get_specific_stats) {
6308 return NULL;
6309 }
6310 return drv->bdrv_get_specific_stats(bs);
6311}
6312
Eric Blakea31939e2015-11-18 01:52:54 -07006313void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006314{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006315 IO_CODE();
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006316 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006317 return;
6318 }
6319
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006320 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006321}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006322
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006323static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01006324{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006325 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006326 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02006327 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006328 }
6329
6330 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006331 assert(bs->drv->bdrv_debug_remove_breakpoint);
6332 return bs;
6333 }
6334
6335 return NULL;
6336}
6337
6338int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6339 const char *tag)
6340{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006341 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006342 bs = bdrv_find_debug_node(bs);
6343 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006344 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6345 }
6346
6347 return -ENOTSUP;
6348}
6349
Fam Zheng4cc70e92013-11-20 10:01:54 +08006350int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6351{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006352 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006353 bs = bdrv_find_debug_node(bs);
6354 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006355 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6356 }
6357
6358 return -ENOTSUP;
6359}
6360
Kevin Wolf41c695c2012-12-06 14:32:58 +01006361int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6362{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006363 GLOBAL_STATE_CODE();
Max Reitz938789e2014-03-10 23:44:08 +01006364 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006365 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006366 }
6367
6368 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6369 return bs->drv->bdrv_debug_resume(bs, tag);
6370 }
6371
6372 return -ENOTSUP;
6373}
6374
6375bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6376{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006377 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006378 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006379 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006380 }
6381
6382 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6383 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6384 }
6385
6386 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006387}
6388
Jeff Codyb1b1d782012-10-16 15:49:09 -04006389/* backing_file can either be relative, or absolute, or a protocol. If it is
6390 * relative, it must be relative to the chain. So, passing in bs->filename
6391 * from a BDS as backing_file should not be done, as that may be relative to
6392 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006393BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6394 const char *backing_file)
6395{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006396 char *filename_full = NULL;
6397 char *backing_file_full = NULL;
6398 char *filename_tmp = NULL;
6399 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006400 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006401 BlockDriverState *curr_bs = NULL;
6402 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006403 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006404
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006405 GLOBAL_STATE_CODE();
6406
Jeff Codyb1b1d782012-10-16 15:49:09 -04006407 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006408 return NULL;
6409 }
6410
Jeff Codyb1b1d782012-10-16 15:49:09 -04006411 filename_full = g_malloc(PATH_MAX);
6412 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006413
6414 is_protocol = path_has_protocol(backing_file);
6415
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006416 /*
6417 * Being largely a legacy function, skip any filters here
6418 * (because filters do not have normal filenames, so they cannot
6419 * match anyway; and allowing json:{} filenames is a bit out of
6420 * scope).
6421 */
6422 for (curr_bs = bdrv_skip_filters(bs);
6423 bdrv_cow_child(curr_bs) != NULL;
6424 curr_bs = bs_below)
6425 {
6426 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006427
Max Reitz0b877d02018-08-01 20:34:11 +02006428 if (bdrv_backing_overridden(curr_bs)) {
6429 /*
6430 * If the backing file was overridden, we can only compare
6431 * directly against the backing node's filename.
6432 */
6433
6434 if (!filenames_refreshed) {
6435 /*
6436 * This will automatically refresh all of the
6437 * filenames in the rest of the backing chain, so we
6438 * only need to do this once.
6439 */
6440 bdrv_refresh_filename(bs_below);
6441 filenames_refreshed = true;
6442 }
6443
6444 if (strcmp(backing_file, bs_below->filename) == 0) {
6445 retval = bs_below;
6446 break;
6447 }
6448 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6449 /*
6450 * If either of the filename paths is actually a protocol, then
6451 * compare unmodified paths; otherwise make paths relative.
6452 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006453 char *backing_file_full_ret;
6454
Jeff Codyb1b1d782012-10-16 15:49:09 -04006455 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006456 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006457 break;
6458 }
Jeff Cody418661e2017-01-25 20:08:20 -05006459 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006460 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6461 NULL);
6462 if (backing_file_full_ret) {
6463 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6464 g_free(backing_file_full_ret);
6465 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006466 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006467 break;
6468 }
Jeff Cody418661e2017-01-25 20:08:20 -05006469 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006470 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006471 /* If not an absolute filename path, make it relative to the current
6472 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006473 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6474 NULL);
6475 /* We are going to compare canonicalized absolute pathnames */
6476 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6477 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006478 continue;
6479 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006480 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006481
6482 /* We need to make sure the backing filename we are comparing against
6483 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006484 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6485 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6486 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006487 continue;
6488 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006489 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006490
6491 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006492 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006493 break;
6494 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006495 }
6496 }
6497
Jeff Codyb1b1d782012-10-16 15:49:09 -04006498 g_free(filename_full);
6499 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006500 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006501}
6502
bellardea2384d2004-08-01 21:59:26 +00006503void bdrv_init(void)
6504{
Kevin Wolfe5f05f82021-07-09 18:41:41 +02006505#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6506 use_bdrv_whitelist = 1;
6507#endif
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006508 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006509}
pbrookce1a14d2006-08-07 02:38:06 +00006510
Markus Armbrustereb852012009-10-27 18:41:44 +01006511void bdrv_init_with_whitelist(void)
6512{
6513 use_bdrv_whitelist = 1;
6514 bdrv_init();
6515}
6516
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006517int bdrv_activate(BlockDriverState *bs, Error **errp)
6518{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006519 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006520 Error *local_err = NULL;
6521 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006522 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006523
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006524 GLOBAL_STATE_CODE();
6525
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006526 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006527 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006528 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006529
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006530 QLIST_FOREACH(child, &bs->children, next) {
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006531 bdrv_activate(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006532 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006533 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006534 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006535 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006536 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006537
Kevin Wolfdafe0962017-11-16 13:00:01 +01006538 /*
6539 * Update permissions, they may differ for inactive nodes.
6540 *
6541 * Note that the required permissions of inactive images are always a
6542 * subset of the permissions required after activating the image. This
6543 * allows us to just get the permissions upfront without restricting
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006544 * bdrv_co_invalidate_cache().
Kevin Wolfdafe0962017-11-16 13:00:01 +01006545 *
6546 * It also means that in error cases, we don't have to try and revert to
6547 * the old permissions (which is an operation that could fail, too). We can
6548 * just keep the extended permissions for the next time that an activation
6549 * of the image is tried.
6550 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006551 if (bs->open_flags & BDRV_O_INACTIVE) {
6552 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006553 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006554 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006555 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006556 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006557 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006558
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006559 ret = bdrv_invalidate_cache(bs, errp);
6560 if (ret < 0) {
6561 bs->open_flags |= BDRV_O_INACTIVE;
6562 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006563 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006564
Kevin Wolf7bb49412019-12-17 15:06:38 +01006565 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6566 bdrv_dirty_bitmap_skip_store(bm, false);
6567 }
6568
6569 ret = refresh_total_sectors(bs, bs->total_sectors);
6570 if (ret < 0) {
6571 bs->open_flags |= BDRV_O_INACTIVE;
6572 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006573 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006574 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006575 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006576
6577 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006578 if (parent->klass->activate) {
6579 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006580 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006581 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006582 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006583 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006584 }
6585 }
6586 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006587
6588 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006589}
6590
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006591int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6592{
6593 Error *local_err = NULL;
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05006594 IO_CODE();
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006595
6596 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6597
6598 if (bs->drv->bdrv_co_invalidate_cache) {
6599 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6600 if (local_err) {
6601 error_propagate(errp, local_err);
6602 return -EINVAL;
6603 }
6604 }
6605
6606 return 0;
6607}
6608
Emanuele Giuseppe Esposito3b717192022-02-09 05:54:51 -05006609void bdrv_activate_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006610{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006611 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006612 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006613
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006614 GLOBAL_STATE_CODE();
6615
Kevin Wolf88be7b42016-05-20 18:49:07 +02006616 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006617 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006618 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006619
6620 aio_context_acquire(aio_context);
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006621 ret = bdrv_activate(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006622 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006623 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006624 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006625 return;
6626 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006627 }
6628}
6629
Kevin Wolf9e372712018-11-23 15:11:14 +01006630static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6631{
6632 BdrvChild *parent;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006633 GLOBAL_STATE_CODE();
Kevin Wolf9e372712018-11-23 15:11:14 +01006634
6635 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006636 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006637 BlockDriverState *parent_bs = parent->opaque;
6638 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6639 return true;
6640 }
6641 }
6642 }
6643
6644 return false;
6645}
6646
6647static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006648{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006649 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006650 int ret;
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006651 uint64_t cumulative_perms, cumulative_shared_perms;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006652
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05006653 GLOBAL_STATE_CODE();
6654
Max Reitzd470ad42017-11-10 21:31:09 +01006655 if (!bs->drv) {
6656 return -ENOMEDIUM;
6657 }
6658
Kevin Wolf9e372712018-11-23 15:11:14 +01006659 /* Make sure that we don't inactivate a child before its parent.
6660 * It will be covered by recursion from the yet active parent. */
6661 if (bdrv_has_bds_parent(bs, true)) {
6662 return 0;
6663 }
6664
6665 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6666
6667 /* Inactivate this node */
6668 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006669 ret = bs->drv->bdrv_inactivate(bs);
6670 if (ret < 0) {
6671 return ret;
6672 }
6673 }
6674
Kevin Wolf9e372712018-11-23 15:11:14 +01006675 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006676 if (parent->klass->inactivate) {
6677 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006678 if (ret < 0) {
6679 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006680 }
6681 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006682 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006683
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006684 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6685 &cumulative_shared_perms);
6686 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6687 /* Our inactive parents still need write access. Inactivation failed. */
6688 return -EPERM;
6689 }
6690
Kevin Wolf9e372712018-11-23 15:11:14 +01006691 bs->open_flags |= BDRV_O_INACTIVE;
6692
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006693 /*
6694 * Update permissions, they may differ for inactive nodes.
6695 * We only tried to loosen restrictions, so errors are not fatal, ignore
6696 * them.
6697 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006698 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006699
6700 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006701 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006702 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006703 if (ret < 0) {
6704 return ret;
6705 }
6706 }
6707
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006708 return 0;
6709}
6710
6711int bdrv_inactivate_all(void)
6712{
Max Reitz79720af2016-03-16 19:54:44 +01006713 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006714 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006715 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006716 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006717
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006718 GLOBAL_STATE_CODE();
6719
Kevin Wolf88be7b42016-05-20 18:49:07 +02006720 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006721 AioContext *aio_context = bdrv_get_aio_context(bs);
6722
6723 if (!g_slist_find(aio_ctxs, aio_context)) {
6724 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6725 aio_context_acquire(aio_context);
6726 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006727 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006728
Kevin Wolf9e372712018-11-23 15:11:14 +01006729 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6730 /* Nodes with BDS parents are covered by recursion from the last
6731 * parent that gets inactivated. Don't inactivate them a second
6732 * time if that has already happened. */
6733 if (bdrv_has_bds_parent(bs, false)) {
6734 continue;
6735 }
6736 ret = bdrv_inactivate_recurse(bs);
6737 if (ret < 0) {
6738 bdrv_next_cleanup(&it);
6739 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006740 }
6741 }
6742
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006743out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006744 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6745 AioContext *aio_context = ctx->data;
6746 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006747 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006748 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006749
6750 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006751}
6752
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006753/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006754/* removable device support */
6755
6756/**
6757 * Return TRUE if the media is present
6758 */
Max Reitze031f752015-10-19 17:53:11 +02006759bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006760{
6761 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006762 BdrvChild *child;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006763 IO_CODE();
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006764
Max Reitze031f752015-10-19 17:53:11 +02006765 if (!drv) {
6766 return false;
6767 }
Max Reitz28d7a782015-10-19 17:53:13 +02006768 if (drv->bdrv_is_inserted) {
6769 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006770 }
Max Reitz28d7a782015-10-19 17:53:13 +02006771 QLIST_FOREACH(child, &bs->children, next) {
6772 if (!bdrv_is_inserted(child->bs)) {
6773 return false;
6774 }
6775 }
6776 return true;
bellard19cb3732006-08-19 11:45:59 +00006777}
6778
6779/**
bellard19cb3732006-08-19 11:45:59 +00006780 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6781 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006782void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006783{
6784 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006785 IO_CODE();
bellard19cb3732006-08-19 11:45:59 +00006786
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006787 if (drv && drv->bdrv_eject) {
6788 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006789 }
bellard19cb3732006-08-19 11:45:59 +00006790}
6791
bellard19cb3732006-08-19 11:45:59 +00006792/**
6793 * Lock or unlock the media (if it is locked, the user won't be able
6794 * to eject it manually).
6795 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006796void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006797{
6798 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006799 IO_CODE();
Markus Armbruster025e8492011-09-06 18:58:47 +02006800 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006801
Markus Armbruster025e8492011-09-06 18:58:47 +02006802 if (drv && drv->bdrv_lock_medium) {
6803 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006804 }
6805}
ths985a03b2007-12-24 16:10:43 +00006806
Fam Zheng9fcb0252013-08-23 09:14:46 +08006807/* Get a reference to bs */
6808void bdrv_ref(BlockDriverState *bs)
6809{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006810 GLOBAL_STATE_CODE();
Fam Zheng9fcb0252013-08-23 09:14:46 +08006811 bs->refcnt++;
6812}
6813
6814/* Release a previously grabbed reference to bs.
6815 * If after releasing, reference count is zero, the BlockDriverState is
6816 * deleted. */
6817void bdrv_unref(BlockDriverState *bs)
6818{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006819 GLOBAL_STATE_CODE();
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006820 if (!bs) {
6821 return;
6822 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006823 assert(bs->refcnt > 0);
6824 if (--bs->refcnt == 0) {
6825 bdrv_delete(bs);
6826 }
6827}
6828
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006829struct BdrvOpBlocker {
6830 Error *reason;
6831 QLIST_ENTRY(BdrvOpBlocker) list;
6832};
6833
6834bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6835{
6836 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006837 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006838 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6839 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6840 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006841 error_propagate_prepend(errp, error_copy(blocker->reason),
6842 "Node '%s' is busy: ",
6843 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006844 return true;
6845 }
6846 return false;
6847}
6848
6849void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6850{
6851 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006852 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006853 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6854
Markus Armbruster5839e532014-08-19 10:31:08 +02006855 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006856 blocker->reason = reason;
6857 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6858}
6859
6860void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6861{
6862 BdrvOpBlocker *blocker, *next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006863 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006864 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6865 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6866 if (blocker->reason == reason) {
6867 QLIST_REMOVE(blocker, list);
6868 g_free(blocker);
6869 }
6870 }
6871}
6872
6873void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6874{
6875 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006876 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006877 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6878 bdrv_op_block(bs, i, reason);
6879 }
6880}
6881
6882void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6883{
6884 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006885 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006886 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6887 bdrv_op_unblock(bs, i, reason);
6888 }
6889}
6890
6891bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6892{
6893 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006894 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006895 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6896 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6897 return false;
6898 }
6899 }
6900 return true;
6901}
6902
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006903void bdrv_img_create(const char *filename, const char *fmt,
6904 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006905 char *options, uint64_t img_size, int flags, bool quiet,
6906 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006907{
Chunyan Liu83d05212014-06-05 17:20:51 +08006908 QemuOptsList *create_opts = NULL;
6909 QemuOpts *opts = NULL;
6910 const char *backing_fmt, *backing_file;
6911 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006912 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006913 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006914 int ret = 0;
6915
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006916 GLOBAL_STATE_CODE();
6917
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006918 /* Find driver and parse its options */
6919 drv = bdrv_find_format(fmt);
6920 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006921 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006922 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006923 }
6924
Max Reitzb65a5e12015-02-05 13:58:12 -05006925 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006926 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006927 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006928 }
6929
Max Reitzc6149722014-12-02 18:32:45 +01006930 if (!drv->create_opts) {
6931 error_setg(errp, "Format driver '%s' does not support image creation",
6932 drv->format_name);
6933 return;
6934 }
6935
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006936 if (!proto_drv->create_opts) {
6937 error_setg(errp, "Protocol driver '%s' does not support image creation",
6938 proto_drv->format_name);
6939 return;
6940 }
6941
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006942 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006943 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006944 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006945
Chunyan Liu83d05212014-06-05 17:20:51 +08006946 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006947
6948 /* Parse -o options */
6949 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006950 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006951 goto out;
6952 }
6953 }
6954
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006955 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6956 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6957 } else if (img_size != UINT64_C(-1)) {
6958 error_setg(errp, "The image size must be specified only once");
6959 goto out;
6960 }
6961
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006962 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006963 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006964 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006965 error_setg(errp, "Backing file not supported for file format '%s'",
6966 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006967 goto out;
6968 }
6969 }
6970
6971 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006972 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006973 error_setg(errp, "Backing file format not supported for file "
6974 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006975 goto out;
6976 }
6977 }
6978
Chunyan Liu83d05212014-06-05 17:20:51 +08006979 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6980 if (backing_file) {
6981 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006982 error_setg(errp, "Error: Trying to create an image with the "
6983 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006984 goto out;
6985 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006986 if (backing_file[0] == '\0') {
6987 error_setg(errp, "Expected backing file name, got empty string");
6988 goto out;
6989 }
Jes Sorensen792da932010-12-16 13:52:17 +01006990 }
6991
Chunyan Liu83d05212014-06-05 17:20:51 +08006992 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006993
John Snow6e6e55f2017-07-17 20:34:22 -04006994 /* The size for the image must always be specified, unless we have a backing
6995 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006996 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006997 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6998 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006999 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04007000 int back_flags;
7001 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02007002
Max Reitz645ae7d2019-02-01 20:29:14 +01007003 full_backing =
7004 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7005 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04007006 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007007 goto out;
7008 }
Max Reitz645ae7d2019-02-01 20:29:14 +01007009 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04007010
Max Reitzd5b23992021-06-22 16:00:30 +02007011 /*
7012 * No need to do I/O here, which allows us to open encrypted
7013 * backing images without needing the secret
7014 */
John Snow6e6e55f2017-07-17 20:34:22 -04007015 back_flags = flags;
7016 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02007017 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04007018
Fam Zhengcc954f02017-12-15 16:04:45 +08007019 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04007020 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04007021 qdict_put_str(backing_options, "driver", backing_fmt);
7022 }
Fam Zhengcc954f02017-12-15 16:04:45 +08007023 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04007024
7025 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7026 &local_err);
7027 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05007028 if (!bs) {
7029 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04007030 goto out;
7031 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05007032 if (!backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007033 error_setg(&local_err,
7034 "Backing file specified without backing format");
7035 error_append_hint(&local_err, "Detected format of %s.",
7036 bs->drv->format_name);
7037 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007038 }
John Snow6e6e55f2017-07-17 20:34:22 -04007039 if (size == -1) {
7040 /* Opened BS, have no size */
7041 size = bdrv_getlength(bs);
7042 if (size < 0) {
7043 error_setg_errno(errp, -size, "Could not get size of '%s'",
7044 backing_file);
7045 bdrv_unref(bs);
7046 goto out;
7047 }
7048 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7049 }
7050 bdrv_unref(bs);
7051 }
Eric Blaked9f059a2020-07-06 15:39:54 -05007052 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7053 } else if (backing_file && !backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007054 error_setg(&local_err,
7055 "Backing file specified without backing format");
7056 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007057 }
John Snow6e6e55f2017-07-17 20:34:22 -04007058
7059 if (size == -1) {
7060 error_setg(errp, "Image creation needs a size parameter");
7061 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007062 }
7063
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007064 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02007065 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08007066 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007067 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05007068 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007069 }
Chunyan Liu83d05212014-06-05 17:20:51 +08007070
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007071 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08007072
Max Reitzcc84d902013-09-06 17:14:26 +02007073 if (ret == -EFBIG) {
7074 /* This is generally a better message than whatever the driver would
7075 * deliver (especially because of the cluster_size_hint), since that
7076 * is most probably not much different from "image too large". */
7077 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08007078 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02007079 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007080 }
Max Reitzcc84d902013-09-06 17:14:26 +02007081 error_setg(errp, "The image size is too large for file format '%s'"
7082 "%s", fmt, cluster_size_hint);
7083 error_free(local_err);
7084 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007085 }
7086
7087out:
Chunyan Liu83d05212014-06-05 17:20:51 +08007088 qemu_opts_del(opts);
7089 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03007090 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007091}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007092
7093AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7094{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007095 IO_CODE();
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00007096 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007097}
7098
Kevin Wolfe336fd42020-10-05 17:58:53 +02007099AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7100{
7101 Coroutine *self = qemu_coroutine_self();
7102 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7103 AioContext *new_ctx;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007104 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007105
7106 /*
7107 * Increase bs->in_flight to ensure that this operation is completed before
7108 * moving the node to a different AioContext. Read new_ctx only afterwards.
7109 */
7110 bdrv_inc_in_flight(bs);
7111
7112 new_ctx = bdrv_get_aio_context(bs);
7113 aio_co_reschedule_self(new_ctx);
7114 return old_ctx;
7115}
7116
7117void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7118{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007119 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007120 aio_co_reschedule_self(old_ctx);
7121 bdrv_dec_in_flight(bs);
7122}
7123
Kevin Wolf18c6ac12020-10-05 17:58:54 +02007124void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7125{
7126 AioContext *ctx = bdrv_get_aio_context(bs);
7127
7128 /* In the main thread, bs->aio_context won't change concurrently */
7129 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7130
7131 /*
7132 * We're in coroutine context, so we already hold the lock of the main
7133 * loop AioContext. Don't lock it twice to avoid deadlocks.
7134 */
7135 assert(qemu_in_coroutine());
7136 if (ctx != qemu_get_aio_context()) {
7137 aio_context_acquire(ctx);
7138 }
7139}
7140
7141void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7142{
7143 AioContext *ctx = bdrv_get_aio_context(bs);
7144
7145 assert(qemu_in_coroutine());
7146 if (ctx != qemu_get_aio_context()) {
7147 aio_context_release(ctx);
7148 }
7149}
7150
Fam Zheng052a7572017-04-10 20:09:25 +08007151void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7152{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007153 IO_CODE();
Fam Zheng052a7572017-04-10 20:09:25 +08007154 aio_co_enter(bdrv_get_aio_context(bs), co);
7155}
7156
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007157static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7158{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05007159 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007160 QLIST_REMOVE(ban, list);
7161 g_free(ban);
7162}
7163
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007164static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007165{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007166 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007167
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007168 assert(!bs->walking_aio_notifiers);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007169 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007170 bs->walking_aio_notifiers = true;
7171 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7172 if (baf->deleted) {
7173 bdrv_do_remove_aio_context_notifier(baf);
7174 } else {
7175 baf->detach_aio_context(baf->opaque);
7176 }
Max Reitz33384422014-06-20 21:57:33 +02007177 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007178 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7179 * remove remaining aio notifiers if we aren't called again.
7180 */
7181 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02007182
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007183 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007184 bs->drv->bdrv_detach_aio_context(bs);
7185 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007186
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007187 if (bs->quiesce_counter) {
7188 aio_enable_external(bs->aio_context);
7189 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007190 bs->aio_context = NULL;
7191}
7192
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007193static void bdrv_attach_aio_context(BlockDriverState *bs,
7194 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007195{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007196 BdrvAioNotifier *ban, *ban_tmp;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007197 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007198
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007199 if (bs->quiesce_counter) {
7200 aio_disable_external(new_context);
7201 }
7202
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007203 bs->aio_context = new_context;
7204
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007205 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007206 bs->drv->bdrv_attach_aio_context(bs, new_context);
7207 }
Max Reitz33384422014-06-20 21:57:33 +02007208
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007209 assert(!bs->walking_aio_notifiers);
7210 bs->walking_aio_notifiers = true;
7211 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7212 if (ban->deleted) {
7213 bdrv_do_remove_aio_context_notifier(ban);
7214 } else {
7215 ban->attached_aio_context(new_context, ban->opaque);
7216 }
Max Reitz33384422014-06-20 21:57:33 +02007217 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007218 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007219}
7220
Kevin Wolf42a65f02019-05-07 18:31:38 +02007221/*
7222 * Changes the AioContext used for fd handlers, timers, and BHs by this
7223 * BlockDriverState and all its children and parents.
7224 *
Max Reitz43eaaae2019-07-22 15:30:54 +02007225 * Must be called from the main AioContext.
7226 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02007227 * The caller must own the AioContext lock for the old AioContext of bs, but it
7228 * must not own the AioContext lock for new_context (unless new_context is the
7229 * same as the current context of bs).
7230 *
7231 * @ignore will accumulate all visited BdrvChild object. The caller is
7232 * responsible for freeing the list afterwards.
7233 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02007234void bdrv_set_aio_context_ignore(BlockDriverState *bs,
7235 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007236{
Max Reitze037c092019-07-19 11:26:14 +02007237 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007238 GSList *children_to_process = NULL;
7239 GSList *parents_to_process = NULL;
7240 GSList *entry;
7241 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02007242
Max Reitz43eaaae2019-07-22 15:30:54 +02007243 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05007244 GLOBAL_STATE_CODE();
Max Reitz43eaaae2019-07-22 15:30:54 +02007245
Max Reitze037c092019-07-19 11:26:14 +02007246 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03007247 return;
7248 }
7249
Kevin Wolfd70d5952019-02-08 16:53:37 +01007250 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02007251
7252 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007253 if (g_slist_find(*ignore, child)) {
7254 continue;
7255 }
7256 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007257 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02007258 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007259
7260 QLIST_FOREACH(parent, &bs->parents, next_parent) {
7261 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007262 continue;
7263 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007264 *ignore = g_slist_prepend(*ignore, parent);
7265 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02007266 }
7267
Sergio Lopez722d8e72021-02-01 13:50:31 +01007268 for (entry = children_to_process;
7269 entry != NULL;
7270 entry = g_slist_next(entry)) {
7271 child = entry->data;
7272 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
7273 }
7274 g_slist_free(children_to_process);
7275
7276 for (entry = parents_to_process;
7277 entry != NULL;
7278 entry = g_slist_next(entry)) {
7279 parent = entry->data;
7280 assert(parent->klass->set_aio_ctx);
7281 parent->klass->set_aio_ctx(parent, new_context, ignore);
7282 }
7283 g_slist_free(parents_to_process);
7284
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007285 bdrv_detach_aio_context(bs);
7286
Max Reitze037c092019-07-19 11:26:14 +02007287 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02007288 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007289 aio_context_acquire(new_context);
7290 }
7291
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007292 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02007293
7294 /*
7295 * If this function was recursively called from
7296 * bdrv_set_aio_context_ignore(), there may be nodes in the
7297 * subtree that have not yet been moved to the new AioContext.
7298 * Release the old one so bdrv_drained_end() can poll them.
7299 */
Max Reitz43eaaae2019-07-22 15:30:54 +02007300 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007301 aio_context_release(old_context);
7302 }
7303
Kevin Wolfd70d5952019-02-08 16:53:37 +01007304 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02007305
Max Reitz43eaaae2019-07-22 15:30:54 +02007306 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007307 aio_context_acquire(old_context);
7308 }
Max Reitz43eaaae2019-07-22 15:30:54 +02007309 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007310 aio_context_release(new_context);
7311 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007312}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02007313
Kevin Wolf5d231842019-05-06 19:17:56 +02007314static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7315 GSList **ignore, Error **errp)
7316{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05007317 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007318 if (g_slist_find(*ignore, c)) {
7319 return true;
7320 }
7321 *ignore = g_slist_prepend(*ignore, c);
7322
Max Reitzbd86fb92020-05-13 13:05:13 +02007323 /*
7324 * A BdrvChildClass that doesn't handle AioContext changes cannot
7325 * tolerate any AioContext changes
7326 */
7327 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007328 char *user = bdrv_child_user_desc(c);
7329 error_setg(errp, "Changing iothreads is not supported by %s", user);
7330 g_free(user);
7331 return false;
7332 }
Max Reitzbd86fb92020-05-13 13:05:13 +02007333 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007334 assert(!errp || *errp);
7335 return false;
7336 }
7337 return true;
7338}
7339
7340bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7341 GSList **ignore, Error **errp)
7342{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007343 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007344 if (g_slist_find(*ignore, c)) {
7345 return true;
7346 }
7347 *ignore = g_slist_prepend(*ignore, c);
7348 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
7349}
7350
7351/* @ignore will accumulate all visited BdrvChild object. The caller is
7352 * responsible for freeing the list afterwards. */
7353bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7354 GSList **ignore, Error **errp)
7355{
7356 BdrvChild *c;
7357
7358 if (bdrv_get_aio_context(bs) == ctx) {
7359 return true;
7360 }
7361
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007362 GLOBAL_STATE_CODE();
7363
Kevin Wolf5d231842019-05-06 19:17:56 +02007364 QLIST_FOREACH(c, &bs->parents, next_parent) {
7365 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
7366 return false;
7367 }
7368 }
7369 QLIST_FOREACH(c, &bs->children, next) {
7370 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
7371 return false;
7372 }
7373 }
7374
7375 return true;
7376}
7377
7378int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7379 BdrvChild *ignore_child, Error **errp)
7380{
7381 GSList *ignore;
7382 bool ret;
7383
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007384 GLOBAL_STATE_CODE();
7385
Kevin Wolf5d231842019-05-06 19:17:56 +02007386 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7387 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7388 g_slist_free(ignore);
7389
7390 if (!ret) {
7391 return -EPERM;
7392 }
7393
Kevin Wolf53a7d042019-05-06 19:17:59 +02007394 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7395 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7396 g_slist_free(ignore);
7397
Kevin Wolf5d231842019-05-06 19:17:56 +02007398 return 0;
7399}
7400
7401int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7402 Error **errp)
7403{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007404 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007405 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7406}
7407
Max Reitz33384422014-06-20 21:57:33 +02007408void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7409 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7410 void (*detach_aio_context)(void *opaque), void *opaque)
7411{
7412 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7413 *ban = (BdrvAioNotifier){
7414 .attached_aio_context = attached_aio_context,
7415 .detach_aio_context = detach_aio_context,
7416 .opaque = opaque
7417 };
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007418 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007419
7420 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7421}
7422
7423void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7424 void (*attached_aio_context)(AioContext *,
7425 void *),
7426 void (*detach_aio_context)(void *),
7427 void *opaque)
7428{
7429 BdrvAioNotifier *ban, *ban_next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007430 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007431
7432 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7433 if (ban->attached_aio_context == attached_aio_context &&
7434 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007435 ban->opaque == opaque &&
7436 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007437 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007438 if (bs->walking_aio_notifiers) {
7439 ban->deleted = true;
7440 } else {
7441 bdrv_do_remove_aio_context_notifier(ban);
7442 }
Max Reitz33384422014-06-20 21:57:33 +02007443 return;
7444 }
7445 }
7446
7447 abort();
7448}
7449
Max Reitz77485432014-10-27 11:12:50 +01007450int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007451 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007452 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007453 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007454{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007455 GLOBAL_STATE_CODE();
Max Reitzd470ad42017-11-10 21:31:09 +01007456 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007457 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007458 return -ENOMEDIUM;
7459 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007460 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007461 error_setg(errp, "Block driver '%s' does not support option amendment",
7462 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007463 return -ENOTSUP;
7464 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007465 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7466 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007467}
Benoît Canetf6186f42013-10-02 14:33:48 +02007468
Max Reitz5d69b5a2020-02-18 11:34:41 +01007469/*
7470 * This function checks whether the given @to_replace is allowed to be
7471 * replaced by a node that always shows the same data as @bs. This is
7472 * used for example to verify whether the mirror job can replace
7473 * @to_replace by the target mirrored from @bs.
7474 * To be replaceable, @bs and @to_replace may either be guaranteed to
7475 * always show the same data (because they are only connected through
7476 * filters), or some driver may allow replacing one of its children
7477 * because it can guarantee that this child's data is not visible at
7478 * all (for example, for dissenting quorum children that have no other
7479 * parents).
7480 */
7481bool bdrv_recurse_can_replace(BlockDriverState *bs,
7482 BlockDriverState *to_replace)
7483{
Max Reitz93393e62019-06-12 17:03:38 +02007484 BlockDriverState *filtered;
7485
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007486 GLOBAL_STATE_CODE();
7487
Max Reitz5d69b5a2020-02-18 11:34:41 +01007488 if (!bs || !bs->drv) {
7489 return false;
7490 }
7491
7492 if (bs == to_replace) {
7493 return true;
7494 }
7495
7496 /* See what the driver can do */
7497 if (bs->drv->bdrv_recurse_can_replace) {
7498 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7499 }
7500
7501 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007502 filtered = bdrv_filter_bs(bs);
7503 if (filtered) {
7504 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007505 }
7506
7507 /* Safe default */
7508 return false;
7509}
7510
Max Reitz810803a2020-02-18 11:34:44 +01007511/*
7512 * Check whether the given @node_name can be replaced by a node that
7513 * has the same data as @parent_bs. If so, return @node_name's BDS;
7514 * NULL otherwise.
7515 *
7516 * @node_name must be a (recursive) *child of @parent_bs (or this
7517 * function will return NULL).
7518 *
7519 * The result (whether the node can be replaced or not) is only valid
7520 * for as long as no graph or permission changes occur.
7521 */
Wen Congyange12f3782015-07-17 10:12:22 +08007522BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7523 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007524{
7525 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007526 AioContext *aio_context;
7527
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007528 GLOBAL_STATE_CODE();
7529
Benoît Canet09158f02014-06-27 18:25:25 +02007530 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007531 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007532 return NULL;
7533 }
7534
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007535 aio_context = bdrv_get_aio_context(to_replace_bs);
7536 aio_context_acquire(aio_context);
7537
Benoît Canet09158f02014-06-27 18:25:25 +02007538 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007539 to_replace_bs = NULL;
7540 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007541 }
7542
7543 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7544 * most non filter in order to prevent data corruption.
7545 * Another benefit is that this tests exclude backing files which are
7546 * blocked by the backing blockers.
7547 */
Max Reitz810803a2020-02-18 11:34:44 +01007548 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7549 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7550 "because it cannot be guaranteed that doing so would not "
7551 "lead to an abrupt change of visible data",
7552 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007553 to_replace_bs = NULL;
7554 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007555 }
7556
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007557out:
7558 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007559 return to_replace_bs;
7560}
Ming Lei448ad912014-07-04 18:04:33 +08007561
Max Reitz97e2f022019-02-01 20:29:27 +01007562/**
7563 * Iterates through the list of runtime option keys that are said to
7564 * be "strong" for a BDS. An option is called "strong" if it changes
7565 * a BDS's data. For example, the null block driver's "size" and
7566 * "read-zeroes" options are strong, but its "latency-ns" option is
7567 * not.
7568 *
7569 * If a key returned by this function ends with a dot, all options
7570 * starting with that prefix are strong.
7571 */
7572static const char *const *strong_options(BlockDriverState *bs,
7573 const char *const *curopt)
7574{
7575 static const char *const global_options[] = {
7576 "driver", "filename", NULL
7577 };
7578
7579 if (!curopt) {
7580 return &global_options[0];
7581 }
7582
7583 curopt++;
7584 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7585 curopt = bs->drv->strong_runtime_opts;
7586 }
7587
7588 return (curopt && *curopt) ? curopt : NULL;
7589}
7590
7591/**
7592 * Copies all strong runtime options from bs->options to the given
7593 * QDict. The set of strong option keys is determined by invoking
7594 * strong_options().
7595 *
7596 * Returns true iff any strong option was present in bs->options (and
7597 * thus copied to the target QDict) with the exception of "filename"
7598 * and "driver". The caller is expected to use this value to decide
7599 * whether the existence of strong options prevents the generation of
7600 * a plain filename.
7601 */
7602static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7603{
7604 bool found_any = false;
7605 const char *const *option_name = NULL;
7606
7607 if (!bs->drv) {
7608 return false;
7609 }
7610
7611 while ((option_name = strong_options(bs, option_name))) {
7612 bool option_given = false;
7613
7614 assert(strlen(*option_name) > 0);
7615 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7616 QObject *entry = qdict_get(bs->options, *option_name);
7617 if (!entry) {
7618 continue;
7619 }
7620
7621 qdict_put_obj(d, *option_name, qobject_ref(entry));
7622 option_given = true;
7623 } else {
7624 const QDictEntry *entry;
7625 for (entry = qdict_first(bs->options); entry;
7626 entry = qdict_next(bs->options, entry))
7627 {
7628 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7629 qdict_put_obj(d, qdict_entry_key(entry),
7630 qobject_ref(qdict_entry_value(entry)));
7631 option_given = true;
7632 }
7633 }
7634 }
7635
7636 /* While "driver" and "filename" need to be included in a JSON filename,
7637 * their existence does not prohibit generation of a plain filename. */
7638 if (!found_any && option_given &&
7639 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7640 {
7641 found_any = true;
7642 }
7643 }
7644
Max Reitz62a01a272019-02-01 20:29:34 +01007645 if (!qdict_haskey(d, "driver")) {
7646 /* Drivers created with bdrv_new_open_driver() may not have a
7647 * @driver option. Add it here. */
7648 qdict_put_str(d, "driver", bs->drv->format_name);
7649 }
7650
Max Reitz97e2f022019-02-01 20:29:27 +01007651 return found_any;
7652}
7653
Max Reitz90993622019-02-01 20:29:09 +01007654/* Note: This function may return false positives; it may return true
7655 * even if opening the backing file specified by bs's image header
7656 * would result in exactly bs->backing. */
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -05007657static bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007658{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007659 GLOBAL_STATE_CODE();
Max Reitz90993622019-02-01 20:29:09 +01007660 if (bs->backing) {
7661 return strcmp(bs->auto_backing_file,
7662 bs->backing->bs->filename);
7663 } else {
7664 /* No backing BDS, so if the image header reports any backing
7665 * file, it must have been suppressed */
7666 return bs->auto_backing_file[0] != '\0';
7667 }
7668}
7669
Max Reitz91af7012014-07-18 20:24:56 +02007670/* Updates the following BDS fields:
7671 * - exact_filename: A filename which may be used for opening a block device
7672 * which (mostly) equals the given BDS (even without any
7673 * other options; so reading and writing must return the same
7674 * results, but caching etc. may be different)
7675 * - full_open_options: Options which, when given when opening a block device
7676 * (without a filename), result in a BDS (mostly)
7677 * equalling the given one
7678 * - filename: If exact_filename is set, it is copied here. Otherwise,
7679 * full_open_options is converted to a JSON object, prefixed with
7680 * "json:" (for use through the JSON pseudo protocol) and put here.
7681 */
7682void bdrv_refresh_filename(BlockDriverState *bs)
7683{
7684 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007685 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007686 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007687 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007688 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007689 bool generate_json_filename; /* Whether our default implementation should
7690 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007691
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007692 GLOBAL_STATE_CODE();
7693
Max Reitz91af7012014-07-18 20:24:56 +02007694 if (!drv) {
7695 return;
7696 }
7697
Max Reitze24518e2019-02-01 20:29:06 +01007698 /* This BDS's file name may depend on any of its children's file names, so
7699 * refresh those first */
7700 QLIST_FOREACH(child, &bs->children, next) {
7701 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007702 }
7703
Max Reitzbb808d52019-02-01 20:29:07 +01007704 if (bs->implicit) {
7705 /* For implicit nodes, just copy everything from the single child */
7706 child = QLIST_FIRST(&bs->children);
7707 assert(QLIST_NEXT(child, next) == NULL);
7708
7709 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7710 child->bs->exact_filename);
7711 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7712
Pan Nengyuancb895612020-01-16 16:56:00 +08007713 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007714 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7715
7716 return;
7717 }
7718
Max Reitz90993622019-02-01 20:29:09 +01007719 backing_overridden = bdrv_backing_overridden(bs);
7720
7721 if (bs->open_flags & BDRV_O_NO_IO) {
7722 /* Without I/O, the backing file does not change anything.
7723 * Therefore, in such a case (primarily qemu-img), we can
7724 * pretend the backing file has not been overridden even if
7725 * it technically has been. */
7726 backing_overridden = false;
7727 }
7728
Max Reitz97e2f022019-02-01 20:29:27 +01007729 /* Gather the options QDict */
7730 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007731 generate_json_filename = append_strong_runtime_options(opts, bs);
7732 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007733
7734 if (drv->bdrv_gather_child_options) {
7735 /* Some block drivers may not want to present all of their children's
7736 * options, or name them differently from BdrvChild.name */
7737 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7738 } else {
7739 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007740 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007741 /* We can skip the backing BDS if it has not been overridden */
7742 continue;
7743 }
7744
7745 qdict_put(opts, child->name,
7746 qobject_ref(child->bs->full_open_options));
7747 }
7748
7749 if (backing_overridden && !bs->backing) {
7750 /* Force no backing file */
7751 qdict_put_null(opts, "backing");
7752 }
7753 }
7754
7755 qobject_unref(bs->full_open_options);
7756 bs->full_open_options = opts;
7757
Max Reitz52f72d62019-06-12 17:43:03 +02007758 primary_child_bs = bdrv_primary_bs(bs);
7759
Max Reitz998b3a12019-02-01 20:29:28 +01007760 if (drv->bdrv_refresh_filename) {
7761 /* Obsolete information is of no use here, so drop the old file name
7762 * information before refreshing it */
7763 bs->exact_filename[0] = '\0';
7764
7765 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007766 } else if (primary_child_bs) {
7767 /*
7768 * Try to reconstruct valid information from the underlying
7769 * file -- this only works for format nodes (filter nodes
7770 * cannot be probed and as such must be selected by the user
7771 * either through an options dict, or through a special
7772 * filename which the filter driver must construct in its
7773 * .bdrv_refresh_filename() implementation).
7774 */
Max Reitz998b3a12019-02-01 20:29:28 +01007775
7776 bs->exact_filename[0] = '\0';
7777
Max Reitzfb695c72019-02-01 20:29:29 +01007778 /*
7779 * We can use the underlying file's filename if:
7780 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007781 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007782 * - the file is a protocol BDS, and
7783 * - opening that file (as this BDS's format) will automatically create
7784 * the BDS tree we have right now, that is:
7785 * - the user did not significantly change this BDS's behavior with
7786 * some explicit (strong) options
7787 * - no non-file child of this BDS has been overridden by the user
7788 * Both of these conditions are represented by generate_json_filename.
7789 */
Max Reitz52f72d62019-06-12 17:43:03 +02007790 if (primary_child_bs->exact_filename[0] &&
7791 primary_child_bs->drv->bdrv_file_open &&
7792 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007793 {
Max Reitz52f72d62019-06-12 17:43:03 +02007794 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007795 }
7796 }
7797
Max Reitz91af7012014-07-18 20:24:56 +02007798 if (bs->exact_filename[0]) {
7799 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007800 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007801 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007802 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007803 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007804 /* Give user a hint if we truncated things. */
7805 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7806 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007807 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007808 }
7809}
Wen Congyange06018a2016-05-10 15:36:37 +08007810
Max Reitz1e89d0f2019-02-01 20:29:18 +01007811char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7812{
7813 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007814 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007815
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007816 GLOBAL_STATE_CODE();
7817
Max Reitz1e89d0f2019-02-01 20:29:18 +01007818 if (!drv) {
7819 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7820 return NULL;
7821 }
7822
7823 if (drv->bdrv_dirname) {
7824 return drv->bdrv_dirname(bs, errp);
7825 }
7826
Max Reitz52f72d62019-06-12 17:43:03 +02007827 child_bs = bdrv_primary_bs(bs);
7828 if (child_bs) {
7829 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007830 }
7831
7832 bdrv_refresh_filename(bs);
7833 if (bs->exact_filename[0] != '\0') {
7834 return path_combine(bs->exact_filename, "");
7835 }
7836
7837 error_setg(errp, "Cannot generate a base directory for %s nodes",
7838 drv->format_name);
7839 return NULL;
7840}
7841
Wen Congyange06018a2016-05-10 15:36:37 +08007842/*
7843 * Hot add/remove a BDS's child. So the user can take a child offline when
7844 * it is broken and take a new child online
7845 */
7846void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7847 Error **errp)
7848{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007849 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007850 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7851 error_setg(errp, "The node %s does not support adding a child",
7852 bdrv_get_device_or_node_name(parent_bs));
7853 return;
7854 }
7855
7856 if (!QLIST_EMPTY(&child_bs->parents)) {
7857 error_setg(errp, "The node %s already has a parent",
7858 child_bs->node_name);
7859 return;
7860 }
7861
7862 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7863}
7864
7865void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7866{
7867 BdrvChild *tmp;
7868
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007869 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007870 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7871 error_setg(errp, "The node %s does not support removing a child",
7872 bdrv_get_device_or_node_name(parent_bs));
7873 return;
7874 }
7875
7876 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7877 if (tmp == child) {
7878 break;
7879 }
7880 }
7881
7882 if (!tmp) {
7883 error_setg(errp, "The node %s does not have a child named %s",
7884 bdrv_get_device_or_node_name(parent_bs),
7885 bdrv_get_device_or_node_name(child->bs));
7886 return;
7887 }
7888
7889 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7890}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007891
7892int bdrv_make_empty(BdrvChild *c, Error **errp)
7893{
7894 BlockDriver *drv = c->bs->drv;
7895 int ret;
7896
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007897 GLOBAL_STATE_CODE();
Max Reitz6f7a3b52020-04-29 16:11:23 +02007898 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7899
7900 if (!drv->bdrv_make_empty) {
7901 error_setg(errp, "%s does not support emptying nodes",
7902 drv->format_name);
7903 return -ENOTSUP;
7904 }
7905
7906 ret = drv->bdrv_make_empty(c->bs);
7907 if (ret < 0) {
7908 error_setg_errno(errp, -ret, "Failed to empty %s",
7909 c->bs->filename);
7910 return ret;
7911 }
7912
7913 return 0;
7914}
Max Reitz9a6fc882019-05-31 15:23:11 +02007915
7916/*
7917 * Return the child that @bs acts as an overlay for, and from which data may be
7918 * copied in COW or COR operations. Usually this is the backing file.
7919 */
7920BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7921{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05007922 IO_CODE();
7923
Max Reitz9a6fc882019-05-31 15:23:11 +02007924 if (!bs || !bs->drv) {
7925 return NULL;
7926 }
7927
7928 if (bs->drv->is_filter) {
7929 return NULL;
7930 }
7931
7932 if (!bs->backing) {
7933 return NULL;
7934 }
7935
7936 assert(bs->backing->role & BDRV_CHILD_COW);
7937 return bs->backing;
7938}
7939
7940/*
7941 * If @bs acts as a filter for exactly one of its children, return
7942 * that child.
7943 */
7944BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7945{
7946 BdrvChild *c;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05007947 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02007948
7949 if (!bs || !bs->drv) {
7950 return NULL;
7951 }
7952
7953 if (!bs->drv->is_filter) {
7954 return NULL;
7955 }
7956
7957 /* Only one of @backing or @file may be used */
7958 assert(!(bs->backing && bs->file));
7959
7960 c = bs->backing ?: bs->file;
7961 if (!c) {
7962 return NULL;
7963 }
7964
7965 assert(c->role & BDRV_CHILD_FILTERED);
7966 return c;
7967}
7968
7969/*
7970 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7971 * whichever is non-NULL.
7972 *
7973 * Return NULL if both are NULL.
7974 */
7975BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7976{
7977 BdrvChild *cow_child = bdrv_cow_child(bs);
7978 BdrvChild *filter_child = bdrv_filter_child(bs);
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05007979 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02007980
7981 /* Filter nodes cannot have COW backing files */
7982 assert(!(cow_child && filter_child));
7983
7984 return cow_child ?: filter_child;
7985}
7986
7987/*
7988 * Return the primary child of this node: For filters, that is the
7989 * filtered child. For other nodes, that is usually the child storing
7990 * metadata.
7991 * (A generally more helpful description is that this is (usually) the
7992 * child that has the same filename as @bs.)
7993 *
7994 * Drivers do not necessarily have a primary child; for example quorum
7995 * does not.
7996 */
7997BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7998{
7999 BdrvChild *c, *found = NULL;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008000 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008001
8002 QLIST_FOREACH(c, &bs->children, next) {
8003 if (c->role & BDRV_CHILD_PRIMARY) {
8004 assert(!found);
8005 found = c;
8006 }
8007 }
8008
8009 return found;
8010}
Max Reitzd38d7eb2019-06-12 15:06:37 +02008011
8012static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8013 bool stop_on_explicit_filter)
8014{
8015 BdrvChild *c;
8016
8017 if (!bs) {
8018 return NULL;
8019 }
8020
8021 while (!(stop_on_explicit_filter && !bs->implicit)) {
8022 c = bdrv_filter_child(bs);
8023 if (!c) {
8024 /*
8025 * A filter that is embedded in a working block graph must
8026 * have a child. Assert this here so this function does
8027 * not return a filter node that is not expected by the
8028 * caller.
8029 */
8030 assert(!bs->drv || !bs->drv->is_filter);
8031 break;
8032 }
8033 bs = c->bs;
8034 }
8035 /*
8036 * Note that this treats nodes with bs->drv == NULL as not being
8037 * filters (bs->drv == NULL should be replaced by something else
8038 * anyway).
8039 * The advantage of this behavior is that this function will thus
8040 * always return a non-NULL value (given a non-NULL @bs).
8041 */
8042
8043 return bs;
8044}
8045
8046/*
8047 * Return the first BDS that has not been added implicitly or that
8048 * does not have a filtered child down the chain starting from @bs
8049 * (including @bs itself).
8050 */
8051BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8052{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05008053 GLOBAL_STATE_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008054 return bdrv_do_skip_filters(bs, true);
8055}
8056
8057/*
8058 * Return the first BDS that does not have a filtered child down the
8059 * chain starting from @bs (including @bs itself).
8060 */
8061BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8062{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008063 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008064 return bdrv_do_skip_filters(bs, false);
8065}
8066
8067/*
8068 * For a backing chain, return the first non-filter backing image of
8069 * the first non-filter image.
8070 */
8071BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8072{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008073 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008074 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8075}
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008076
8077/**
8078 * Check whether [offset, offset + bytes) overlaps with the cached
8079 * block-status data region.
8080 *
8081 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8082 * which is what bdrv_bsc_is_data()'s interface needs.
8083 * Otherwise, *pnum is not touched.
8084 */
8085static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8086 int64_t offset, int64_t bytes,
8087 int64_t *pnum)
8088{
8089 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8090 bool overlaps;
8091
8092 overlaps =
8093 qatomic_read(&bsc->valid) &&
8094 ranges_overlap(offset, bytes, bsc->data_start,
8095 bsc->data_end - bsc->data_start);
8096
8097 if (overlaps && pnum) {
8098 *pnum = bsc->data_end - offset;
8099 }
8100
8101 return overlaps;
8102}
8103
8104/**
8105 * See block_int.h for this function's documentation.
8106 */
8107bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8108{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008109 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008110 RCU_READ_LOCK_GUARD();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008111 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8112}
8113
8114/**
8115 * See block_int.h for this function's documentation.
8116 */
8117void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8118 int64_t offset, int64_t bytes)
8119{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008120 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008121 RCU_READ_LOCK_GUARD();
8122
8123 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8124 qatomic_set(&bs->block_status_cache->valid, false);
8125 }
8126}
8127
8128/**
8129 * See block_int.h for this function's documentation.
8130 */
8131void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8132{
8133 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8134 BdrvBlockStatusCache *old_bsc;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008135 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008136
8137 *new_bsc = (BdrvBlockStatusCache) {
8138 .valid = true,
8139 .data_start = offset,
8140 .data_end = offset + bytes,
8141 };
8142
8143 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8144
8145 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8146 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8147 if (old_bsc) {
8148 g_free_rcu(old_bsc, rcu);
8149 }
8150}