blob: c8ac91eb63874f7b987d0eafb235847b0995d80d [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
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +030093static void bdrv_replace_child_noperm(BdrvChild *child,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +030094 BlockDriverState *new_bs);
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +030095static void bdrv_remove_child(BdrvChild *child, Transaction *tran);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +030096
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +030097static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
98 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +030099 Transaction *change_child_tran, Error **errp);
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +0300100static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
101static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
102
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -0500103static bool bdrv_backing_overridden(BlockDriverState *bs);
104
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -0400105static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -0400106 GHashTable *visited, Transaction *tran,
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -0400107 Error **errp);
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)) {
Claudio Fontanac551fb02022-09-29 11:30:33 +0200465 Error *local_err = NULL;
466 int rv = block_module_load(block_driver_modules[i].library_name,
467 &local_err);
468 if (rv > 0) {
469 return bdrv_do_find_format(format_name);
470 } else if (rv < 0) {
471 error_report_err(local_err);
472 }
Marc Mari88d88792016-08-12 09:27:03 -0400473 break;
474 }
475 }
Claudio Fontanac551fb02022-09-29 11:30:33 +0200476 return NULL;
Marc Mari88d88792016-08-12 09:27:03 -0400477}
478
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300479static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100480{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800481 static const char *whitelist_rw[] = {
482 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200483 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800484 };
485 static const char *whitelist_ro[] = {
486 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200487 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100488 };
489 const char **p;
490
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800491 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100492 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800493 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100494
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800495 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300496 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100497 return 1;
498 }
499 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800500 if (read_only) {
501 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300502 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800503 return 1;
504 }
505 }
506 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100507 return 0;
508}
509
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300510int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
511{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500512 GLOBAL_STATE_CODE();
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300513 return bdrv_format_is_whitelisted(drv->format_name, read_only);
514}
515
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000516bool bdrv_uses_whitelist(void)
517{
518 return use_bdrv_whitelist;
519}
520
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800521typedef struct CreateCo {
522 BlockDriver *drv;
523 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800524 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800525 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200526 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800527} CreateCo;
528
Emanuele Giuseppe Esposito84bdf212022-11-28 09:23:30 -0500529static int coroutine_fn bdrv_co_create(BlockDriver *drv, const char *filename,
530 QemuOpts *opts, Error **errp)
531{
532 int ret;
533 GLOBAL_STATE_CODE();
534 ERRP_GUARD();
535
536 if (!drv->bdrv_co_create_opts) {
537 error_setg(errp, "Driver '%s' does not support image creation",
538 drv->format_name);
539 return -ENOTSUP;
540 }
541
542 ret = drv->bdrv_co_create_opts(drv, filename, opts, errp);
543 if (ret < 0 && !*errp) {
544 error_setg_errno(errp, -ret, "Could not create image");
545 }
546
547 return ret;
548}
549
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800550static void coroutine_fn bdrv_create_co_entry(void *opaque)
551{
552 CreateCo *cco = opaque;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -0500553 GLOBAL_STATE_CODE();
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800554
Emanuele Giuseppe Esposito84bdf212022-11-28 09:23:30 -0500555 cco->ret = bdrv_co_create(cco->drv, cco->filename, cco->opts, &cco->err);
556 aio_wait_kick();
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800557}
558
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200559int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800560 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000561{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500562 GLOBAL_STATE_CODE();
563
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800564 if (qemu_in_coroutine()) {
565 /* Fast-path if already in coroutine context */
Emanuele Giuseppe Esposito84bdf212022-11-28 09:23:30 -0500566 return bdrv_co_create(drv, filename, opts, errp);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800567 } else {
Emanuele Giuseppe Esposito84bdf212022-11-28 09:23:30 -0500568 Coroutine *co;
569 CreateCo cco = {
570 .drv = drv,
571 .filename = filename,
572 .opts = opts,
573 .ret = NOT_DONE,
574 .err = NULL,
575 };
576
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200577 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
578 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800579 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200580 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800581 }
Emanuele Giuseppe Esposito84bdf212022-11-28 09:23:30 -0500582 error_propagate(errp, cco.err);
583 return cco.ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800584 }
bellardea2384d2004-08-01 21:59:26 +0000585}
586
Max Reitzfd171462020-01-22 17:45:29 +0100587/**
588 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
589 * least the given @minimum_size.
590 *
591 * On success, return @blk's actual length.
592 * Otherwise, return -errno.
593 */
594static int64_t create_file_fallback_truncate(BlockBackend *blk,
595 int64_t minimum_size, Error **errp)
596{
597 Error *local_err = NULL;
598 int64_t size;
599 int ret;
600
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500601 GLOBAL_STATE_CODE();
602
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200603 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
604 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100605 if (ret < 0 && ret != -ENOTSUP) {
606 error_propagate(errp, local_err);
607 return ret;
608 }
609
610 size = blk_getlength(blk);
611 if (size < 0) {
612 error_free(local_err);
613 error_setg_errno(errp, -size,
614 "Failed to inquire the new image file's length");
615 return size;
616 }
617
618 if (size < minimum_size) {
619 /* Need to grow the image, but we failed to do that */
620 error_propagate(errp, local_err);
621 return -ENOTSUP;
622 }
623
624 error_free(local_err);
625 local_err = NULL;
626
627 return size;
628}
629
630/**
631 * Helper function for bdrv_create_file_fallback(): Zero the first
632 * sector to remove any potentially pre-existing image header.
633 */
Paolo Bonzini881a4c52022-09-22 10:49:00 +0200634static int coroutine_fn
635create_file_fallback_zero_first_sector(BlockBackend *blk,
636 int64_t current_size,
637 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100638{
639 int64_t bytes_to_clear;
640 int ret;
641
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500642 GLOBAL_STATE_CODE();
643
Max Reitzfd171462020-01-22 17:45:29 +0100644 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
645 if (bytes_to_clear) {
Alberto Fariace47ff22022-10-13 14:37:02 +0200646 ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
Max Reitzfd171462020-01-22 17:45:29 +0100647 if (ret < 0) {
648 error_setg_errno(errp, -ret,
649 "Failed to clear the new image's first sector");
650 return ret;
651 }
652 }
653
654 return 0;
655}
656
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200657/**
658 * Simple implementation of bdrv_co_create_opts for protocol drivers
659 * which only support creation via opening a file
660 * (usually existing raw storage device)
661 */
662int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
663 const char *filename,
664 QemuOpts *opts,
665 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100666{
667 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100668 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100669 int64_t size = 0;
670 char *buf = NULL;
671 PreallocMode prealloc;
672 Error *local_err = NULL;
673 int ret;
674
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -0500675 GLOBAL_STATE_CODE();
676
Max Reitzfd171462020-01-22 17:45:29 +0100677 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
678 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
679 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
680 PREALLOC_MODE_OFF, &local_err);
681 g_free(buf);
682 if (local_err) {
683 error_propagate(errp, local_err);
684 return -EINVAL;
685 }
686
687 if (prealloc != PREALLOC_MODE_OFF) {
688 error_setg(errp, "Unsupported preallocation mode '%s'",
689 PreallocMode_str(prealloc));
690 return -ENOTSUP;
691 }
692
Max Reitzeeea1fa2020-02-25 16:56:18 +0100693 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100694 qdict_put_str(options, "driver", drv->format_name);
695
696 blk = blk_new_open(filename, NULL, options,
697 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
698 if (!blk) {
699 error_prepend(errp, "Protocol driver '%s' does not support image "
700 "creation, and opening the image failed: ",
701 drv->format_name);
702 return -EINVAL;
703 }
704
705 size = create_file_fallback_truncate(blk, size, errp);
706 if (size < 0) {
707 ret = size;
708 goto out;
709 }
710
711 ret = create_file_fallback_zero_first_sector(blk, size, errp);
712 if (ret < 0) {
713 goto out;
714 }
715
716 ret = 0;
717out:
718 blk_unref(blk);
719 return ret;
720}
721
Emanuele Giuseppe Esposito2475a0d2022-11-28 09:23:31 -0500722int coroutine_fn bdrv_co_create_file(const char *filename, QemuOpts *opts,
723 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200724{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100725 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200726 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100727 QDict *qdict;
728 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200729
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500730 GLOBAL_STATE_CODE();
731
Max Reitzb65a5e12015-02-05 13:58:12 -0500732 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200733 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000734 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200735 }
736
Stefano Garzarella729222a2021-03-08 17:12:32 +0100737 if (!drv->create_opts) {
738 error_setg(errp, "Driver '%s' does not support image creation",
739 drv->format_name);
740 return -ENOTSUP;
741 }
742
743 /*
744 * 'opts' contains a QemuOptsList with a combination of format and protocol
745 * default values.
746 *
747 * The format properly removes its options, but the default values remain
748 * in 'opts->list'. So if the protocol has options with the same name
749 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
750 * of the format, since for overlapping options, the format wins.
751 *
752 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
753 * only the set options, and then convert it back to QemuOpts, using the
754 * create_opts of the protocol. So the new QemuOpts, will contain only the
755 * protocol defaults.
756 */
757 qdict = qemu_opts_to_qdict(opts, NULL);
758 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
759 if (protocol_opts == NULL) {
760 ret = -EINVAL;
761 goto out;
762 }
763
Emanuele Giuseppe Esposito2475a0d2022-11-28 09:23:31 -0500764 ret = bdrv_co_create(drv, filename, protocol_opts, errp);
Stefano Garzarella729222a2021-03-08 17:12:32 +0100765out:
766 qemu_opts_del(protocol_opts);
767 qobject_unref(qdict);
768 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200769}
770
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300771int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
772{
773 Error *local_err = NULL;
774 int ret;
775
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500776 IO_CODE();
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300777 assert(bs != NULL);
778
779 if (!bs->drv) {
780 error_setg(errp, "Block node '%s' is not opened", bs->filename);
781 return -ENOMEDIUM;
782 }
783
784 if (!bs->drv->bdrv_co_delete_file) {
785 error_setg(errp, "Driver '%s' does not support image deletion",
786 bs->drv->format_name);
787 return -ENOTSUP;
788 }
789
790 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
791 if (ret < 0) {
792 error_propagate(errp, local_err);
793 }
794
795 return ret;
796}
797
Maxim Levitskya890f082020-12-17 19:09:03 +0200798void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
799{
800 Error *local_err = NULL;
801 int ret;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500802 IO_CODE();
Maxim Levitskya890f082020-12-17 19:09:03 +0200803
804 if (!bs) {
805 return;
806 }
807
808 ret = bdrv_co_delete_file(bs, &local_err);
809 /*
810 * ENOTSUP will happen if the block driver doesn't support
811 * the 'bdrv_co_delete_file' interface. This is a predictable
812 * scenario and shouldn't be reported back to the user.
813 */
814 if (ret == -ENOTSUP) {
815 error_free(local_err);
816 } else if (ret < 0) {
817 error_report_err(local_err);
818 }
819}
820
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100821/**
822 * Try to get @bs's logical and physical block size.
823 * On success, store them in @bsz struct and return 0.
824 * On failure return -errno.
825 * @bs must not be empty.
826 */
827int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
828{
829 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200830 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500831 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100832
833 if (drv && drv->bdrv_probe_blocksizes) {
834 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200835 } else if (filtered) {
836 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100837 }
838
839 return -ENOTSUP;
840}
841
842/**
843 * Try to get @bs's geometry (cyls, heads, sectors).
844 * On success, store them in @geo struct and return 0.
845 * On failure return -errno.
846 * @bs must not be empty.
847 */
848int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
849{
850 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200851 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500852 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100853
854 if (drv && drv->bdrv_probe_geometry) {
855 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200856 } else if (filtered) {
857 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100858 }
859
860 return -ENOTSUP;
861}
862
Jim Meyeringeba25052012-05-28 09:27:54 +0200863/*
864 * Create a uniquely-named empty temporary file.
Bin Meng69fbfff2022-10-10 12:04:31 +0800865 * Return the actual file name used upon success, otherwise NULL.
866 * This string should be freed with g_free() when not needed any longer.
867 *
868 * Note: creating a temporary file for the caller to (re)open is
869 * inherently racy. Use g_file_open_tmp() instead whenever practical.
Jim Meyeringeba25052012-05-28 09:27:54 +0200870 */
Bin Meng69fbfff2022-10-10 12:04:31 +0800871char *create_tmp_file(Error **errp)
Jim Meyeringeba25052012-05-28 09:27:54 +0200872{
bellardea2384d2004-08-01 21:59:26 +0000873 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000874 const char *tmpdir;
Bin Meng69fbfff2022-10-10 12:04:31 +0800875 g_autofree char *filename = NULL;
876
877 tmpdir = g_get_tmp_dir();
878#ifndef _WIN32
879 /*
880 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
881 *
882 * This function is used to create temporary disk images (like -snapshot),
883 * so the files can become very large. /tmp is often a tmpfs where as
884 * /var/tmp is usually on a disk, so more appropriate for disk images.
885 */
886 if (!g_strcmp0(tmpdir, "/tmp")) {
Amit Shah69bef792014-02-26 15:12:37 +0530887 tmpdir = "/var/tmp";
888 }
bellardd5249392004-08-03 21:14:23 +0000889#endif
Bin Meng69fbfff2022-10-10 12:04:31 +0800890
891 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
892 fd = g_mkstemp(filename);
bellardea2384d2004-08-01 21:59:26 +0000893 if (fd < 0) {
Bin Meng69fbfff2022-10-10 12:04:31 +0800894 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
895 filename);
896 return NULL;
bellardea2384d2004-08-01 21:59:26 +0000897 }
Bin Meng6b6471e2022-10-10 12:04:30 +0800898 close(fd);
Bin Meng69fbfff2022-10-10 12:04:31 +0800899
900 return g_steal_pointer(&filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200901}
bellardea2384d2004-08-01 21:59:26 +0000902
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200903/*
904 * Detect host devices. By convention, /dev/cdrom[N] is always
905 * recognized as a host CDROM.
906 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200907static BlockDriver *find_hdev_driver(const char *filename)
908{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200909 int score_max = 0, score;
910 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500911 GLOBAL_STATE_CODE();
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200912
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100913 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200914 if (d->bdrv_probe_device) {
915 score = d->bdrv_probe_device(filename);
916 if (score > score_max) {
917 score_max = score;
918 drv = d;
919 }
920 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200921 }
922
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200923 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200924}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200925
Marc Mari88d88792016-08-12 09:27:03 -0400926static BlockDriver *bdrv_do_find_protocol(const char *protocol)
927{
928 BlockDriver *drv1;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500929 GLOBAL_STATE_CODE();
Marc Mari88d88792016-08-12 09:27:03 -0400930
931 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
932 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
933 return drv1;
934 }
935 }
936
937 return NULL;
938}
939
Kevin Wolf98289622013-07-10 15:47:39 +0200940BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500941 bool allow_protocol_prefix,
942 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200943{
944 BlockDriver *drv1;
945 char protocol[128];
946 int len;
947 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400948 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200949
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500950 GLOBAL_STATE_CODE();
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200951 /* TODO Drivers without bdrv_file_open must be specified explicitly */
952
Christoph Hellwig39508e72010-06-23 12:25:17 +0200953 /*
954 * XXX(hch): we really should not let host device detection
955 * override an explicit protocol specification, but moving this
956 * later breaks access to device names with colons in them.
957 * Thanks to the brain-dead persistent naming schemes on udev-
958 * based Linux systems those actually are quite common.
959 */
960 drv1 = find_hdev_driver(filename);
961 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200962 return drv1;
963 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200964
Kevin Wolf98289622013-07-10 15:47:39 +0200965 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100966 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200967 }
Kevin Wolf98289622013-07-10 15:47:39 +0200968
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000969 p = strchr(filename, ':');
970 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200971 len = p - filename;
972 if (len > sizeof(protocol) - 1)
973 len = sizeof(protocol) - 1;
974 memcpy(protocol, filename, len);
975 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400976
977 drv1 = bdrv_do_find_protocol(protocol);
978 if (drv1) {
979 return drv1;
980 }
981
982 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
983 if (block_driver_modules[i].protocol_name &&
984 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
Claudio Fontanac551fb02022-09-29 11:30:33 +0200985 int rv = block_module_load(block_driver_modules[i].library_name, errp);
986 if (rv > 0) {
987 drv1 = bdrv_do_find_protocol(protocol);
988 } else if (rv < 0) {
989 return NULL;
990 }
Marc Mari88d88792016-08-12 09:27:03 -0400991 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200992 }
993 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500994
Marc Mari88d88792016-08-12 09:27:03 -0400995 if (!drv1) {
996 error_setg(errp, "Unknown protocol '%s'", protocol);
997 }
998 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200999}
1000
Markus Armbrusterc6684242014-11-20 16:27:10 +01001001/*
1002 * Guess image format by probing its contents.
1003 * This is not a good idea when your image is raw (CVE-2008-2004), but
1004 * we do it anyway for backward compatibility.
1005 *
1006 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +01001007 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1008 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001009 * @filename is its filename.
1010 *
1011 * For all block drivers, call the bdrv_probe() method to get its
1012 * probing score.
1013 * Return the first block driver with the highest probing score.
1014 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01001015BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1016 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001017{
1018 int score_max = 0, score;
1019 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001020 IO_CODE();
Markus Armbrusterc6684242014-11-20 16:27:10 +01001021
1022 QLIST_FOREACH(d, &bdrv_drivers, list) {
1023 if (d->bdrv_probe) {
1024 score = d->bdrv_probe(buf, buf_size, filename);
1025 if (score > score_max) {
1026 score_max = score;
1027 drv = d;
1028 }
1029 }
1030 }
1031
1032 return drv;
1033}
1034
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001035static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +02001036 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +00001037{
Markus Armbrusterc6684242014-11-20 16:27:10 +01001038 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +01001039 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +01001040 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001041
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001042 GLOBAL_STATE_CODE();
1043
Kevin Wolf08a00552010-06-01 18:37:31 +02001044 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001045 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +01001046 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +02001047 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -07001048 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001049
Alberto Fariaa9262f52022-07-05 17:15:11 +01001050 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
bellard83f64092006-08-01 16:21:11 +00001051 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001052 error_setg_errno(errp, -ret, "Could not read image for determining its "
1053 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +02001054 *pdrv = NULL;
1055 return ret;
bellard83f64092006-08-01 16:21:11 +00001056 }
1057
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001058 drv = bdrv_probe_all(buf, sizeof(buf), filename);
Stefan Weilc98ac352010-07-21 21:51:51 +02001059 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001060 error_setg(errp, "Could not determine image format: No compatible "
1061 "driver found");
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001062 *pdrv = NULL;
1063 return -ENOENT;
Stefan Weilc98ac352010-07-21 21:51:51 +02001064 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001065
Stefan Weilc98ac352010-07-21 21:51:51 +02001066 *pdrv = drv;
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001067 return 0;
bellardea2384d2004-08-01 21:59:26 +00001068}
1069
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001070/**
1071 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001072 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001073 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001074int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001075{
1076 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001077 IO_CODE();
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001078
Max Reitzd470ad42017-11-10 21:31:09 +01001079 if (!drv) {
1080 return -ENOMEDIUM;
1081 }
1082
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001083 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001084 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001085 return 0;
1086
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001087 /* query actual device if possible, otherwise just trust the hint */
1088 if (drv->bdrv_getlength) {
1089 int64_t length = drv->bdrv_getlength(bs);
1090 if (length < 0) {
1091 return length;
1092 }
Fam Zheng7e382002013-11-06 19:48:06 +08001093 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001094 }
1095
1096 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001097
1098 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1099 return -EFBIG;
1100 }
1101
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001102 return 0;
1103}
1104
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001105/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001106 * Combines a QDict of new block driver @options with any missing options taken
1107 * from @old_options, so that leaving out an option defaults to its old value.
1108 */
1109static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1110 QDict *old_options)
1111{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001112 GLOBAL_STATE_CODE();
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001113 if (bs->drv && bs->drv->bdrv_join_options) {
1114 bs->drv->bdrv_join_options(options, old_options);
1115 } else {
1116 qdict_join(options, old_options, false);
1117 }
1118}
1119
Alberto Garcia543770b2018-09-06 12:37:09 +03001120static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1121 int open_flags,
1122 Error **errp)
1123{
1124 Error *local_err = NULL;
1125 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1126 BlockdevDetectZeroesOptions detect_zeroes =
1127 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1128 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001129 GLOBAL_STATE_CODE();
Alberto Garcia543770b2018-09-06 12:37:09 +03001130 g_free(value);
1131 if (local_err) {
1132 error_propagate(errp, local_err);
1133 return detect_zeroes;
1134 }
1135
1136 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1137 !(open_flags & BDRV_O_UNMAP))
1138 {
1139 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1140 "without setting discard operation to unmap");
1141 }
1142
1143 return detect_zeroes;
1144}
1145
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001146/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001147 * Set open flags for aio engine
1148 *
1149 * Return 0 on success, -1 if the engine specified is invalid
1150 */
1151int bdrv_parse_aio(const char *mode, int *flags)
1152{
1153 if (!strcmp(mode, "threads")) {
1154 /* do nothing, default */
1155 } else if (!strcmp(mode, "native")) {
1156 *flags |= BDRV_O_NATIVE_AIO;
1157#ifdef CONFIG_LINUX_IO_URING
1158 } else if (!strcmp(mode, "io_uring")) {
1159 *flags |= BDRV_O_IO_URING;
1160#endif
1161 } else {
1162 return -1;
1163 }
1164
1165 return 0;
1166}
1167
1168/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001169 * Set open flags for a given discard mode
1170 *
1171 * Return 0 on success, -1 if the discard mode was invalid.
1172 */
1173int bdrv_parse_discard_flags(const char *mode, int *flags)
1174{
1175 *flags &= ~BDRV_O_UNMAP;
1176
1177 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1178 /* do nothing */
1179 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1180 *flags |= BDRV_O_UNMAP;
1181 } else {
1182 return -1;
1183 }
1184
1185 return 0;
1186}
1187
1188/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001189 * Set open flags for a given cache mode
1190 *
1191 * Return 0 on success, -1 if the cache mode was invalid.
1192 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001193int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001194{
1195 *flags &= ~BDRV_O_CACHE_MASK;
1196
1197 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001198 *writethrough = false;
1199 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001200 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001201 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001202 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001203 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001204 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001205 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001206 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001207 *flags |= BDRV_O_NO_FLUSH;
1208 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001209 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001210 } else {
1211 return -1;
1212 }
1213
1214 return 0;
1215}
1216
Kevin Wolfb5411552017-01-17 15:56:16 +01001217static char *bdrv_child_get_parent_desc(BdrvChild *c)
1218{
1219 BlockDriverState *parent = c->opaque;
Vladimir Sementsov-Ogievskiy2c0a3ac2021-06-01 10:52:15 +03001220 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
Kevin Wolfb5411552017-01-17 15:56:16 +01001221}
1222
Kevin Wolf20018e12016-05-23 18:46:59 +02001223static void bdrv_child_cb_drained_begin(BdrvChild *child)
1224{
1225 BlockDriverState *bs = child->opaque;
Kevin Wolfa82a3bd2022-11-18 18:41:07 +01001226 bdrv_do_drained_begin_quiesce(bs, NULL);
Kevin Wolf20018e12016-05-23 18:46:59 +02001227}
1228
Kevin Wolf89bd0302018-03-22 14:11:20 +01001229static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1230{
1231 BlockDriverState *bs = child->opaque;
Kevin Wolf299403a2022-11-18 18:41:05 +01001232 return bdrv_drain_poll(bs, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001233}
1234
Kevin Wolf2f65df62022-11-18 18:40:59 +01001235static void bdrv_child_cb_drained_end(BdrvChild *child)
Kevin Wolf20018e12016-05-23 18:46:59 +02001236{
1237 BlockDriverState *bs = child->opaque;
Kevin Wolf2f65df62022-11-18 18:40:59 +01001238 bdrv_drained_end(bs);
Kevin Wolf20018e12016-05-23 18:46:59 +02001239}
1240
Kevin Wolf38701b62017-05-04 18:52:39 +02001241static int bdrv_child_cb_inactivate(BdrvChild *child)
1242{
1243 BlockDriverState *bs = child->opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001244 GLOBAL_STATE_CODE();
Kevin Wolf38701b62017-05-04 18:52:39 +02001245 assert(bs->open_flags & BDRV_O_INACTIVE);
1246 return 0;
1247}
1248
Emanuele Giuseppe Esposito27633e72022-10-25 04:49:47 -04001249static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1250 GHashTable *visited, Transaction *tran,
1251 Error **errp)
Kevin Wolf5d231842019-05-06 19:17:56 +02001252{
1253 BlockDriverState *bs = child->opaque;
Emanuele Giuseppe Esposito27633e72022-10-25 04:49:47 -04001254 return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
Kevin Wolf53a7d042019-05-06 19:17:59 +02001255}
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);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001448 if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1449 /*
1450 * Here we handle filters and block/raw-format.c when it behave like
1451 * filter. They generally have a single PRIMARY child, which is also the
1452 * FILTERED child, and that they may have multiple more children, which
1453 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1454 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1455 * into bs->backing on exceptional cases; and bs->backing will be
1456 * nothing else.
1457 */
1458 assert(!(child->role & BDRV_CHILD_COW));
1459 if (child->role & BDRV_CHILD_PRIMARY) {
1460 assert(child->role & BDRV_CHILD_FILTERED);
1461 assert(!bs->backing);
1462 assert(!bs->file);
Hanna Reitza2253692021-11-15 15:53:58 +01001463
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001464 if (bs->drv->filtered_child_is_backing) {
1465 bs->backing = child;
1466 } else {
1467 bs->file = child;
1468 }
1469 } else {
1470 assert(!(child->role & BDRV_CHILD_FILTERED));
1471 }
1472 } else if (child->role & BDRV_CHILD_COW) {
1473 assert(bs->drv->supports_backing);
1474 assert(!(child->role & BDRV_CHILD_PRIMARY));
1475 assert(!bs->backing);
1476 bs->backing = child;
Max Reitzca2f1232020-05-13 13:05:22 +02001477 bdrv_backing_attach(child);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001478 } else if (child->role & BDRV_CHILD_PRIMARY) {
1479 assert(!bs->file);
1480 bs->file = child;
Max Reitzca2f1232020-05-13 13:05:22 +02001481 }
Max Reitzca2f1232020-05-13 13:05:22 +02001482}
1483
Max Reitz48e08282020-05-13 13:05:23 +02001484static void bdrv_child_cb_detach(BdrvChild *child)
1485{
1486 BlockDriverState *bs = child->opaque;
1487
1488 if (child->role & BDRV_CHILD_COW) {
1489 bdrv_backing_detach(child);
1490 }
1491
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05001492 assert_bdrv_graph_writable(bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001493 QLIST_REMOVE(child, next);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001494 if (child == bs->backing) {
1495 assert(child != bs->file);
1496 bs->backing = NULL;
1497 } else if (child == bs->file) {
1498 bs->file = NULL;
1499 }
Max Reitz48e08282020-05-13 13:05:23 +02001500}
1501
Max Reitz43483552020-05-13 13:05:24 +02001502static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1503 const char *filename, Error **errp)
1504{
1505 if (c->role & BDRV_CHILD_COW) {
1506 return bdrv_backing_update_filename(c, base, filename, errp);
1507 }
1508 return 0;
1509}
1510
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001511AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001512{
1513 BlockDriverState *bs = c->opaque;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05001514 IO_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001515
1516 return bdrv_get_aio_context(bs);
1517}
1518
Max Reitz43483552020-05-13 13:05:24 +02001519const BdrvChildClass child_of_bds = {
1520 .parent_is_bds = true,
1521 .get_parent_desc = bdrv_child_get_parent_desc,
1522 .inherit_options = bdrv_inherited_options,
1523 .drained_begin = bdrv_child_cb_drained_begin,
1524 .drained_poll = bdrv_child_cb_drained_poll,
1525 .drained_end = bdrv_child_cb_drained_end,
1526 .attach = bdrv_child_cb_attach,
1527 .detach = bdrv_child_cb_detach,
1528 .inactivate = bdrv_child_cb_inactivate,
Emanuele Giuseppe Esposito27633e72022-10-25 04:49:47 -04001529 .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
Max Reitz43483552020-05-13 13:05:24 +02001530 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001531 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001532};
1533
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001534AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1535{
Hanna Reitzd5f8d792022-11-07 16:13:19 +01001536 IO_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001537 return c->klass->get_parent_aio_context(c);
1538}
1539
Kevin Wolf7b272452012-11-12 17:05:39 +01001540static int bdrv_open_flags(BlockDriverState *bs, int flags)
1541{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001542 int open_flags = flags;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001543 GLOBAL_STATE_CODE();
Kevin Wolf7b272452012-11-12 17:05:39 +01001544
1545 /*
1546 * Clear flags that are internal to the block layer before opening the
1547 * image.
1548 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001549 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001550
Kevin Wolf7b272452012-11-12 17:05:39 +01001551 return open_flags;
1552}
1553
Kevin Wolf91a097e2015-05-08 17:49:53 +02001554static void update_flags_from_options(int *flags, QemuOpts *opts)
1555{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001556 GLOBAL_STATE_CODE();
1557
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001558 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001559
Alberto Garcia57f9db92018-09-06 12:37:06 +03001560 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001561 *flags |= BDRV_O_NO_FLUSH;
1562 }
1563
Alberto Garcia57f9db92018-09-06 12:37:06 +03001564 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001565 *flags |= BDRV_O_NOCACHE;
1566 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001567
Alberto Garcia57f9db92018-09-06 12:37:06 +03001568 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001569 *flags |= BDRV_O_RDWR;
1570 }
1571
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001572 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1573 *flags |= BDRV_O_AUTO_RDONLY;
1574 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001575}
1576
1577static void update_options_from_flags(QDict *options, int flags)
1578{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001579 GLOBAL_STATE_CODE();
Kevin Wolf91a097e2015-05-08 17:49:53 +02001580 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001581 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001582 }
1583 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001584 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1585 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001586 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001587 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001588 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001589 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001590 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1591 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1592 flags & BDRV_O_AUTO_RDONLY);
1593 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001594}
1595
Kevin Wolf636ea372014-01-24 14:11:52 +01001596static void bdrv_assign_node_name(BlockDriverState *bs,
1597 const char *node_name,
1598 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001599{
Jeff Cody15489c72015-10-12 19:36:50 -04001600 char *gen_node_name = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001601 GLOBAL_STATE_CODE();
Benoît Canet6913c0c2014-01-23 21:31:33 +01001602
Jeff Cody15489c72015-10-12 19:36:50 -04001603 if (!node_name) {
1604 node_name = gen_node_name = id_generate(ID_BLOCK);
1605 } else if (!id_wellformed(node_name)) {
1606 /*
1607 * Check for empty string or invalid characters, but not if it is
1608 * generated (generated names use characters not available to the user)
1609 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001610 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001611 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001612 }
1613
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001614 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001615 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001616 error_setg(errp, "node-name=%s is conflicting with a device id",
1617 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001618 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001619 }
1620
Benoît Canet6913c0c2014-01-23 21:31:33 +01001621 /* takes care of avoiding duplicates node names */
1622 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001623 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001624 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001625 }
1626
Kevin Wolf824808d2018-07-04 13:28:29 +02001627 /* Make sure that the node name isn't truncated */
1628 if (strlen(node_name) >= sizeof(bs->node_name)) {
1629 error_setg(errp, "Node name too long");
1630 goto out;
1631 }
1632
Benoît Canet6913c0c2014-01-23 21:31:33 +01001633 /* copy node name into the bs and insert it into the graph list */
1634 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1635 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001636out:
1637 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001638}
1639
Kevin Wolf01a56502017-01-18 15:51:56 +01001640static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1641 const char *node_name, QDict *options,
1642 int open_flags, Error **errp)
1643{
1644 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001645 int i, ret;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001646 GLOBAL_STATE_CODE();
Kevin Wolf01a56502017-01-18 15:51:56 +01001647
1648 bdrv_assign_node_name(bs, node_name, &local_err);
1649 if (local_err) {
1650 error_propagate(errp, local_err);
1651 return -EINVAL;
1652 }
1653
1654 bs->drv = drv;
1655 bs->opaque = g_malloc0(drv->instance_size);
1656
1657 if (drv->bdrv_file_open) {
1658 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1659 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001660 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001661 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001662 } else {
1663 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001664 }
1665
1666 if (ret < 0) {
1667 if (local_err) {
1668 error_propagate(errp, local_err);
1669 } else if (bs->filename[0]) {
1670 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1671 } else {
1672 error_setg_errno(errp, -ret, "Could not open image");
1673 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001674 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001675 }
1676
Stefan Hajnoczie8b65352022-10-13 14:59:01 -04001677 assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1678 assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1679
1680 /*
1681 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1682 * drivers that pass read/write requests through to a child the trouble of
1683 * declaring support explicitly.
1684 *
1685 * Drivers must not propagate this flag accidentally when they initiate I/O
1686 * to a bounce buffer. That case should be rare though.
1687 */
1688 bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1689 bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1690
Kevin Wolf01a56502017-01-18 15:51:56 +01001691 ret = refresh_total_sectors(bs, bs->total_sectors);
1692 if (ret < 0) {
1693 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001694 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001695 }
1696
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001697 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001698 if (local_err) {
1699 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001700 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001701 }
1702
1703 assert(bdrv_opt_mem_align(bs) != 0);
1704 assert(bdrv_min_mem_align(bs) != 0);
1705 assert(is_power_of_2(bs->bl.request_alignment));
1706
Kevin Wolf0f122642018-03-28 18:29:18 +02001707 for (i = 0; i < bs->quiesce_counter; i++) {
Kevin Wolf5e8ac212022-11-18 18:40:58 +01001708 if (drv->bdrv_drain_begin) {
1709 drv->bdrv_drain_begin(bs);
Kevin Wolf0f122642018-03-28 18:29:18 +02001710 }
1711 }
1712
Kevin Wolf01a56502017-01-18 15:51:56 +01001713 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001714open_failed:
1715 bs->drv = NULL;
1716 if (bs->file != NULL) {
1717 bdrv_unref_child(bs, bs->file);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001718 assert(!bs->file);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001719 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001720 g_free(bs->opaque);
1721 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001722 return ret;
1723}
1724
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001725/*
1726 * Create and open a block node.
1727 *
1728 * @options is a QDict of options to pass to the block drivers, or NULL for an
1729 * empty set of options. The reference to the QDict belongs to the block layer
1730 * after the call (even on failure), so if the caller intends to reuse the
1731 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1732 */
1733BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1734 const char *node_name,
1735 QDict *options, int flags,
1736 Error **errp)
Kevin Wolf680c7f92017-01-18 17:16:41 +01001737{
1738 BlockDriverState *bs;
1739 int ret;
1740
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001741 GLOBAL_STATE_CODE();
1742
Kevin Wolf680c7f92017-01-18 17:16:41 +01001743 bs = bdrv_new();
1744 bs->open_flags = flags;
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001745 bs->options = options ?: qdict_new();
1746 bs->explicit_options = qdict_clone_shallow(bs->options);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001747 bs->opaque = NULL;
1748
1749 update_options_from_flags(bs->options, flags);
1750
1751 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1752 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001753 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001754 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001755 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001756 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001757 bdrv_unref(bs);
1758 return NULL;
1759 }
1760
1761 return bs;
1762}
1763
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001764/* Create and open a block node. */
1765BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1766 int flags, Error **errp)
1767{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001768 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001769 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1770}
1771
Kevin Wolfc5f30142016-10-06 11:33:17 +02001772QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001773 .name = "bdrv_common",
1774 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1775 .desc = {
1776 {
1777 .name = "node-name",
1778 .type = QEMU_OPT_STRING,
1779 .help = "Node name of the block device node",
1780 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001781 {
1782 .name = "driver",
1783 .type = QEMU_OPT_STRING,
1784 .help = "Block driver to use for the node",
1785 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001786 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001787 .name = BDRV_OPT_CACHE_DIRECT,
1788 .type = QEMU_OPT_BOOL,
1789 .help = "Bypass software writeback cache on the host",
1790 },
1791 {
1792 .name = BDRV_OPT_CACHE_NO_FLUSH,
1793 .type = QEMU_OPT_BOOL,
1794 .help = "Ignore flush requests",
1795 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001796 {
1797 .name = BDRV_OPT_READ_ONLY,
1798 .type = QEMU_OPT_BOOL,
1799 .help = "Node is opened in read-only mode",
1800 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001801 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001802 .name = BDRV_OPT_AUTO_READ_ONLY,
1803 .type = QEMU_OPT_BOOL,
1804 .help = "Node can become read-only if opening read-write fails",
1805 },
1806 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001807 .name = "detect-zeroes",
1808 .type = QEMU_OPT_STRING,
1809 .help = "try to optimize zero writes (off, on, unmap)",
1810 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001811 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001812 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001813 .type = QEMU_OPT_STRING,
1814 .help = "discard operation (ignore/off, unmap/on)",
1815 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001816 {
1817 .name = BDRV_OPT_FORCE_SHARE,
1818 .type = QEMU_OPT_BOOL,
1819 .help = "always accept other writers (default: off)",
1820 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001821 { /* end of list */ }
1822 },
1823};
1824
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001825QemuOptsList bdrv_create_opts_simple = {
1826 .name = "simple-create-opts",
1827 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001828 .desc = {
1829 {
1830 .name = BLOCK_OPT_SIZE,
1831 .type = QEMU_OPT_SIZE,
1832 .help = "Virtual disk size"
1833 },
1834 {
1835 .name = BLOCK_OPT_PREALLOC,
1836 .type = QEMU_OPT_STRING,
1837 .help = "Preallocation mode (allowed values: off)"
1838 },
1839 { /* end of list */ }
1840 }
1841};
1842
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001843/*
Kevin Wolf57915332010-04-14 15:24:50 +02001844 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001845 *
1846 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001847 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001848static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001849 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001850{
1851 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001852 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001853 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001854 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001855 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001856 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001857 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001858 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001859 bool ro;
Kevin Wolf57915332010-04-14 15:24:50 +02001860
Paolo Bonzini64058752012-05-08 16:51:49 +02001861 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001862 assert(options != NULL && bs->options != options);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001863 GLOBAL_STATE_CODE();
Kevin Wolf57915332010-04-14 15:24:50 +02001864
Kevin Wolf62392eb2015-04-24 16:38:02 +02001865 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001866 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001867 ret = -EINVAL;
1868 goto fail_opts;
1869 }
1870
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001871 update_flags_from_options(&bs->open_flags, opts);
1872
Kevin Wolf62392eb2015-04-24 16:38:02 +02001873 driver_name = qemu_opt_get(opts, "driver");
1874 drv = bdrv_find_format(driver_name);
1875 assert(drv != NULL);
1876
Fam Zheng5a9347c2017-05-03 00:35:37 +08001877 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1878
1879 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1880 error_setg(errp,
1881 BDRV_OPT_FORCE_SHARE
1882 "=on can only be used with read-only images");
1883 ret = -EINVAL;
1884 goto fail_opts;
1885 }
1886
Kevin Wolf45673672013-04-22 17:48:40 +02001887 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001888 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001889 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001890 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001891 /*
1892 * Caution: while qdict_get_try_str() is fine, getting
1893 * non-string types would require more care. When @options
1894 * come from -blockdev or blockdev_add, its members are typed
1895 * according to the QAPI schema, but when they come from
1896 * -drive, they're all QString.
1897 */
Kevin Wolf45673672013-04-22 17:48:40 +02001898 filename = qdict_get_try_str(options, "filename");
1899 }
1900
Max Reitz4a008242017-04-13 18:06:24 +02001901 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001902 error_setg(errp, "The '%s' block driver requires a file name",
1903 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001904 ret = -EINVAL;
1905 goto fail_opts;
1906 }
1907
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001908 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1909 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001910
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001911 ro = bdrv_is_read_only(bs);
1912
1913 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1914 if (!ro && bdrv_is_whitelisted(drv, true)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001915 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1916 } else {
1917 ret = -ENOTSUP;
1918 }
1919 if (ret < 0) {
1920 error_setg(errp,
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001921 !ro && bdrv_is_whitelisted(drv, true)
Kevin Wolf8be25de2019-01-22 13:15:31 +01001922 ? "Driver '%s' can only be used for read-only devices"
1923 : "Driver '%s' is not whitelisted",
1924 drv->format_name);
1925 goto fail_opts;
1926 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001927 }
Kevin Wolf57915332010-04-14 15:24:50 +02001928
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001929 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001930 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001931
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001932 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001933 if (!ro) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001934 bdrv_enable_copy_on_read(bs);
1935 } else {
1936 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001937 ret = -EINVAL;
1938 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001939 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001940 }
1941
Alberto Garcia415bbca2018-10-03 13:23:13 +03001942 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001943 if (discard != NULL) {
1944 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1945 error_setg(errp, "Invalid discard option");
1946 ret = -EINVAL;
1947 goto fail_opts;
1948 }
1949 }
1950
Alberto Garcia543770b2018-09-06 12:37:09 +03001951 bs->detect_zeroes =
1952 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1953 if (local_err) {
1954 error_propagate(errp, local_err);
1955 ret = -EINVAL;
1956 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001957 }
1958
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001959 if (filename != NULL) {
1960 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1961 } else {
1962 bs->filename[0] = '\0';
1963 }
Max Reitz91af7012014-07-18 20:24:56 +02001964 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001965
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001966 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001967 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001968 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001969
Kevin Wolf01a56502017-01-18 15:51:56 +01001970 assert(!drv->bdrv_file_open || file == NULL);
1971 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001972 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001973 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001974 }
1975
Kevin Wolf18edf282015-04-07 17:12:56 +02001976 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001977 return 0;
1978
Kevin Wolf18edf282015-04-07 17:12:56 +02001979fail_opts:
1980 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001981 return ret;
1982}
1983
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001984static QDict *parse_json_filename(const char *filename, Error **errp)
1985{
1986 QObject *options_obj;
1987 QDict *options;
1988 int ret;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001989 GLOBAL_STATE_CODE();
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001990
1991 ret = strstart(filename, "json:", &filename);
1992 assert(ret);
1993
Markus Armbruster5577fff2017-02-28 22:26:59 +01001994 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001995 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001996 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001997 return NULL;
1998 }
1999
Max Reitz7dc847e2018-02-24 16:40:29 +01002000 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01002001 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002002 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02002003 error_setg(errp, "Invalid JSON object given");
2004 return NULL;
2005 }
2006
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02002007 qdict_flatten(options);
2008
2009 return options;
2010}
2011
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002012static void parse_json_protocol(QDict *options, const char **pfilename,
2013 Error **errp)
2014{
2015 QDict *json_options;
2016 Error *local_err = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002017 GLOBAL_STATE_CODE();
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002018
2019 /* Parse json: pseudo-protocol */
2020 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2021 return;
2022 }
2023
2024 json_options = parse_json_filename(*pfilename, &local_err);
2025 if (local_err) {
2026 error_propagate(errp, local_err);
2027 return;
2028 }
2029
2030 /* Options given in the filename have lower priority than options
2031 * specified directly */
2032 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002033 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002034 *pfilename = NULL;
2035}
2036
Kevin Wolf57915332010-04-14 15:24:50 +02002037/*
Kevin Wolff54120f2014-05-26 11:09:59 +02002038 * Fills in default options for opening images and converts the legacy
2039 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04002040 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2041 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02002042 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002043static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02002044 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02002045{
2046 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04002047 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002048 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02002049 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002050 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002051
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002052 GLOBAL_STATE_CODE();
2053
Markus Armbruster129c7d12017-03-30 19:43:12 +02002054 /*
2055 * Caution: while qdict_get_try_str() is fine, getting non-string
2056 * types would require more care. When @options come from
2057 * -blockdev or blockdev_add, its members are typed according to
2058 * the QAPI schema, but when they come from -drive, they're all
2059 * QString.
2060 */
Max Reitz53a29512015-03-19 14:53:16 -04002061 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02002062 if (drvname) {
2063 drv = bdrv_find_format(drvname);
2064 if (!drv) {
2065 error_setg(errp, "Unknown driver '%s'", drvname);
2066 return -ENOENT;
2067 }
2068 /* If the user has explicitly specified the driver, this choice should
2069 * override the BDRV_O_PROTOCOL flag */
2070 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04002071 }
2072
2073 if (protocol) {
2074 *flags |= BDRV_O_PROTOCOL;
2075 } else {
2076 *flags &= ~BDRV_O_PROTOCOL;
2077 }
2078
Kevin Wolf91a097e2015-05-08 17:49:53 +02002079 /* Translate cache options from flags into options */
2080 update_options_from_flags(*options, *flags);
2081
Kevin Wolff54120f2014-05-26 11:09:59 +02002082 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002083 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002084 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002085 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02002086 parse_filename = true;
2087 } else {
2088 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2089 "the same time");
2090 return -EINVAL;
2091 }
2092 }
2093
2094 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02002095 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02002096 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02002097
Max Reitz053e1572015-08-26 19:47:51 +02002098 if (!drvname && protocol) {
2099 if (filename) {
2100 drv = bdrv_find_protocol(filename, parse_filename, errp);
2101 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002102 return -EINVAL;
2103 }
Max Reitz053e1572015-08-26 19:47:51 +02002104
2105 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05002106 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02002107 } else {
2108 error_setg(errp, "Must specify either driver or file");
2109 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002110 }
2111 }
2112
Kevin Wolf17b005f2014-05-27 10:50:29 +02002113 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02002114
2115 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002116 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002117 drv->bdrv_parse_filename(filename, *options, &local_err);
2118 if (local_err) {
2119 error_propagate(errp, local_err);
2120 return -EINVAL;
2121 }
2122
2123 if (!drv->bdrv_needs_filename) {
2124 qdict_del(*options, "filename");
2125 }
2126 }
2127
2128 return 0;
2129}
2130
Kevin Wolf148eb132017-09-14 14:32:04 +02002131typedef struct BlockReopenQueueEntry {
2132 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01002133 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02002134 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002135 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02002136} BlockReopenQueueEntry;
2137
2138/*
2139 * Return the flags that @bs will have after the reopens in @q have
2140 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2141 * return the current flags.
2142 */
2143static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2144{
2145 BlockReopenQueueEntry *entry;
2146
2147 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002148 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002149 if (entry->state.bs == bs) {
2150 return entry->state.flags;
2151 }
2152 }
2153 }
2154
2155 return bs->open_flags;
2156}
2157
2158/* Returns whether the image file can be written to after the reopen queue @q
2159 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002160static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2161 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002162{
2163 int flags = bdrv_reopen_get_flags(q, bs);
2164
2165 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2166}
2167
Max Reitzcc022142018-06-06 21:37:00 +02002168/*
2169 * Return whether the BDS can be written to. This is not necessarily
2170 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2171 * be written to but do not count as read-only images.
2172 */
2173bool bdrv_is_writable(BlockDriverState *bs)
2174{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05002175 IO_CODE();
Max Reitzcc022142018-06-06 21:37:00 +02002176 return bdrv_is_writable_after_reopen(bs, NULL);
2177}
2178
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002179static char *bdrv_child_user_desc(BdrvChild *c)
2180{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002181 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002182 return c->klass->get_parent_desc(c);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002183}
2184
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002185/*
2186 * Check that @a allows everything that @b needs. @a and @b must reference same
2187 * child node.
2188 */
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002189static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2190{
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002191 const char *child_bs_name;
2192 g_autofree char *a_user = NULL;
2193 g_autofree char *b_user = NULL;
2194 g_autofree char *perms = NULL;
2195
2196 assert(a->bs);
2197 assert(a->bs == b->bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002198 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002199
2200 if ((b->perm & a->shared_perm) == b->perm) {
2201 return true;
2202 }
2203
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002204 child_bs_name = bdrv_get_node_name(b->bs);
2205 a_user = bdrv_child_user_desc(a);
2206 b_user = bdrv_child_user_desc(b);
2207 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2208
2209 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2210 "both required by %s (uses node '%s' as '%s' child) and "
2211 "unshared by %s (uses node '%s' as '%s' child).",
2212 child_bs_name, perms,
2213 b_user, child_bs_name, b->name,
2214 a_user, child_bs_name, a->name);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002215
2216 return false;
2217}
2218
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002219static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002220{
2221 BdrvChild *a, *b;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002222 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002223
2224 /*
2225 * During the loop we'll look at each pair twice. That's correct because
2226 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2227 * directions.
2228 */
2229 QLIST_FOREACH(a, &bs->parents, next_parent) {
2230 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002231 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002232 continue;
2233 }
2234
2235 if (!bdrv_a_allow_b(a, b, errp)) {
2236 return true;
2237 }
2238 }
2239 }
2240
2241 return false;
2242}
2243
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002244static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002245 BdrvChild *c, BdrvChildRole role,
2246 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002247 uint64_t parent_perm, uint64_t parent_shared,
2248 uint64_t *nperm, uint64_t *nshared)
2249{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002250 assert(bs->drv && bs->drv->bdrv_child_perm);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002251 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002252 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002253 parent_perm, parent_shared,
2254 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002255 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002256 if (child_bs && child_bs->force_share) {
2257 *nshared = BLK_PERM_ALL;
2258 }
2259}
2260
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002261/*
2262 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2263 * nodes that are already in the @list, of course) so that final list is
2264 * topologically sorted. Return the result (GSList @list object is updated, so
2265 * don't use old reference after function call).
2266 *
2267 * On function start @list must be already topologically sorted and for any node
2268 * in the @list the whole subtree of the node must be in the @list as well. The
2269 * simplest way to satisfy this criteria: use only result of
2270 * bdrv_topological_dfs() or NULL as @list parameter.
2271 */
2272static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2273 BlockDriverState *bs)
2274{
2275 BdrvChild *child;
2276 g_autoptr(GHashTable) local_found = NULL;
2277
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002278 GLOBAL_STATE_CODE();
2279
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002280 if (!found) {
2281 assert(!list);
2282 found = local_found = g_hash_table_new(NULL, NULL);
2283 }
2284
2285 if (g_hash_table_contains(found, bs)) {
2286 return list;
2287 }
2288 g_hash_table_add(found, bs);
2289
2290 QLIST_FOREACH(child, &bs->children, next) {
2291 list = bdrv_topological_dfs(list, found, child->bs);
2292 }
2293
2294 return g_slist_prepend(list, bs);
2295}
2296
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002297typedef struct BdrvChildSetPermState {
2298 BdrvChild *child;
2299 uint64_t old_perm;
2300 uint64_t old_shared_perm;
2301} BdrvChildSetPermState;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002302
2303static void bdrv_child_set_perm_abort(void *opaque)
2304{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002305 BdrvChildSetPermState *s = opaque;
2306
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002307 GLOBAL_STATE_CODE();
2308
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002309 s->child->perm = s->old_perm;
2310 s->child->shared_perm = s->old_shared_perm;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002311}
2312
2313static TransactionActionDrv bdrv_child_set_pem_drv = {
2314 .abort = bdrv_child_set_perm_abort,
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002315 .clean = g_free,
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002316};
2317
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002318static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2319 uint64_t shared, Transaction *tran)
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002320{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002321 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002322 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002323
2324 *s = (BdrvChildSetPermState) {
2325 .child = c,
2326 .old_perm = c->perm,
2327 .old_shared_perm = c->shared_perm,
2328 };
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002329
2330 c->perm = perm;
2331 c->shared_perm = shared;
2332
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002333 tran_add(tran, &bdrv_child_set_pem_drv, s);
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002334}
2335
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002336static void bdrv_drv_set_perm_commit(void *opaque)
2337{
2338 BlockDriverState *bs = opaque;
2339 uint64_t cumulative_perms, cumulative_shared_perms;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002340 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002341
2342 if (bs->drv->bdrv_set_perm) {
2343 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2344 &cumulative_shared_perms);
2345 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2346 }
2347}
2348
2349static void bdrv_drv_set_perm_abort(void *opaque)
2350{
2351 BlockDriverState *bs = opaque;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002352 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002353
2354 if (bs->drv->bdrv_abort_perm_update) {
2355 bs->drv->bdrv_abort_perm_update(bs);
2356 }
2357}
2358
2359TransactionActionDrv bdrv_drv_set_perm_drv = {
2360 .abort = bdrv_drv_set_perm_abort,
2361 .commit = bdrv_drv_set_perm_commit,
2362};
2363
2364static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2365 uint64_t shared_perm, Transaction *tran,
2366 Error **errp)
2367{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002368 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002369 if (!bs->drv) {
2370 return 0;
2371 }
2372
2373 if (bs->drv->bdrv_check_perm) {
2374 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2375 if (ret < 0) {
2376 return ret;
2377 }
2378 }
2379
2380 if (tran) {
2381 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2382 }
2383
2384 return 0;
2385}
2386
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002387typedef struct BdrvReplaceChildState {
2388 BdrvChild *child;
2389 BlockDriverState *old_bs;
2390} BdrvReplaceChildState;
2391
2392static void bdrv_replace_child_commit(void *opaque)
2393{
2394 BdrvReplaceChildState *s = opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002395 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002396
2397 bdrv_unref(s->old_bs);
2398}
2399
2400static void bdrv_replace_child_abort(void *opaque)
2401{
2402 BdrvReplaceChildState *s = opaque;
2403 BlockDriverState *new_bs = s->child->bs;
2404
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002405 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002406 /* old_bs reference is transparently moved from @s to @s->child */
Kevin Wolf23987472022-11-18 18:41:09 +01002407 if (!s->child->bs) {
2408 /*
2409 * The parents were undrained when removing old_bs from the child. New
2410 * requests can't have been made, though, because the child was empty.
2411 *
2412 * TODO Make bdrv_replace_child_noperm() transactionable to avoid
2413 * undraining the parent in the first place. Once this is done, having
2414 * new_bs drained when calling bdrv_replace_child_tran() is not a
2415 * requirement any more.
2416 */
Kevin Wolf606ed752022-11-18 18:41:10 +01002417 bdrv_parent_drained_begin_single(s->child);
Kevin Wolf23987472022-11-18 18:41:09 +01002418 assert(!bdrv_parent_drained_poll_single(s->child));
2419 }
2420 assert(s->child->quiesced_parent);
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03002421 bdrv_replace_child_noperm(s->child, s->old_bs);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002422 bdrv_unref(new_bs);
2423}
2424
2425static TransactionActionDrv bdrv_replace_child_drv = {
2426 .commit = bdrv_replace_child_commit,
2427 .abort = bdrv_replace_child_abort,
2428 .clean = g_free,
2429};
2430
2431/*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002432 * bdrv_replace_child_tran
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002433 *
2434 * Note: real unref of old_bs is done only on commit.
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002435 *
Kevin Wolf23987472022-11-18 18:41:09 +01002436 * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
2437 * kept drained until the transaction is completed.
2438 *
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002439 * The function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002440 */
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002441static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002442 Transaction *tran)
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002443{
2444 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
Kevin Wolf23987472022-11-18 18:41:09 +01002445
2446 assert(child->quiesced_parent);
2447 assert(!new_bs || new_bs->quiesce_counter);
2448
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002449 *s = (BdrvReplaceChildState) {
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002450 .child = child,
2451 .old_bs = child->bs,
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002452 };
2453 tran_add(tran, &bdrv_replace_child_drv, s);
2454
2455 if (new_bs) {
2456 bdrv_ref(new_bs);
2457 }
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03002458 bdrv_replace_child_noperm(child, new_bs);
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002459 /* old_bs reference is transparently moved from @child to @s */
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002460}
2461
Kevin Wolf33a610c2016-12-15 13:04:20 +01002462/*
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002463 * Refresh permissions in @bs subtree. The function is intended to be called
2464 * after some graph modification that was done without permission update.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002465 */
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002466static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2467 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002468{
2469 BlockDriver *drv = bs->drv;
2470 BdrvChild *c;
2471 int ret;
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002472 uint64_t cumulative_perms, cumulative_shared_perms;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002473 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002474
2475 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002476
2477 /* Write permissions never work with read-only images */
2478 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002479 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002480 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002481 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2482 error_setg(errp, "Block node is read-only");
2483 } else {
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002484 error_setg(errp, "Read-only block node '%s' cannot support "
2485 "read-write users", bdrv_get_node_name(bs));
Max Reitz481e0ee2019-05-15 22:15:00 +02002486 }
2487
Kevin Wolf33a610c2016-12-15 13:04:20 +01002488 return -EPERM;
2489 }
2490
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002491 /*
2492 * Unaligned requests will automatically be aligned to bl.request_alignment
2493 * and without RESIZE we can't extend requests to write to space beyond the
2494 * end of the image, so it's required that the image size is aligned.
2495 */
2496 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2497 !(cumulative_perms & BLK_PERM_RESIZE))
2498 {
2499 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2500 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2501 "Image size is not a multiple of request "
2502 "alignment");
2503 return -EPERM;
2504 }
2505 }
2506
Kevin Wolf33a610c2016-12-15 13:04:20 +01002507 /* Check this node */
2508 if (!drv) {
2509 return 0;
2510 }
2511
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002512 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002513 errp);
2514 if (ret < 0) {
2515 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002516 }
2517
Kevin Wolf78e421c2016-12-20 23:25:12 +01002518 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002519 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002520 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002521 return 0;
2522 }
2523
2524 /* Check all children */
2525 QLIST_FOREACH(c, &bs->children, next) {
2526 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002527
Max Reitze5d8a402020-05-13 13:05:44 +02002528 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002529 cumulative_perms, cumulative_shared_perms,
2530 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002531 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002532 }
2533
2534 return 0;
2535}
2536
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03002537/*
2538 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2539 * a topologically sorted subgraph.
2540 */
2541static int bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q,
2542 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002543{
2544 int ret;
2545 BlockDriverState *bs;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002546 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002547
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002548 for ( ; list; list = list->next) {
2549 bs = list->data;
2550
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002551 if (bdrv_parent_perms_conflict(bs, errp)) {
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002552 return -EINVAL;
2553 }
2554
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002555 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002556 if (ret < 0) {
2557 return ret;
2558 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002559 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002560
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002561 return 0;
2562}
2563
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03002564/*
2565 * @list is any list of nodes. List is completed by all subtrees and
2566 * topologically sorted. It's not a problem if some node occurs in the @list
2567 * several times.
2568 */
2569static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2570 Transaction *tran, Error **errp)
2571{
2572 g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2573 g_autoptr(GSList) refresh_list = NULL;
2574
2575 for ( ; list; list = list->next) {
2576 refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2577 }
2578
2579 return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2580}
2581
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002582void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2583 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002584{
2585 BdrvChild *c;
2586 uint64_t cumulative_perms = 0;
2587 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2588
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002589 GLOBAL_STATE_CODE();
2590
Kevin Wolf33a610c2016-12-15 13:04:20 +01002591 QLIST_FOREACH(c, &bs->parents, next_parent) {
2592 cumulative_perms |= c->perm;
2593 cumulative_shared_perms &= c->shared_perm;
2594 }
2595
2596 *perm = cumulative_perms;
2597 *shared_perm = cumulative_shared_perms;
2598}
2599
Fam Zheng51761962017-05-03 00:35:36 +08002600char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002601{
2602 struct perm_name {
2603 uint64_t perm;
2604 const char *name;
2605 } permissions[] = {
2606 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2607 { BLK_PERM_WRITE, "write" },
2608 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2609 { BLK_PERM_RESIZE, "resize" },
Kevin Wolfd0833192017-01-16 18:26:20 +01002610 { 0, NULL }
2611 };
2612
Alberto Garciae2a74232020-01-10 18:15:18 +01002613 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002614 struct perm_name *p;
2615
2616 for (p = permissions; p->name; p++) {
2617 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002618 if (result->len > 0) {
2619 g_string_append(result, ", ");
2620 }
2621 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002622 }
2623 }
2624
Alberto Garciae2a74232020-01-10 18:15:18 +01002625 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002626}
2627
Kevin Wolf33a610c2016-12-15 13:04:20 +01002628
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002629/* @tran is allowed to be NULL. In this case no rollback is possible */
2630static int bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran,
2631 Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002632{
2633 int ret;
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002634 Transaction *local_tran = NULL;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002635 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002636 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002637
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002638 if (!tran) {
2639 tran = local_tran = tran_new();
2640 }
2641
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03002642 ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002643
2644 if (local_tran) {
2645 tran_finalize(local_tran, ret);
2646 }
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002647
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002648 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002649}
2650
Kevin Wolf33a610c2016-12-15 13:04:20 +01002651int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2652 Error **errp)
2653{
Max Reitz10467792019-05-22 19:03:51 +02002654 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002655 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002656 int ret;
2657
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002658 GLOBAL_STATE_CODE();
2659
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002660 bdrv_child_set_perm(c, perm, shared, tran);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002661
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002662 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002663
2664 tran_finalize(tran, ret);
2665
Kevin Wolf33a610c2016-12-15 13:04:20 +01002666 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002667 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2668 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002669 error_propagate(errp, local_err);
2670 } else {
2671 /*
2672 * Our caller may intend to only loosen restrictions and
2673 * does not expect this function to fail. Errors are not
2674 * fatal in such a case, so we can just hide them from our
2675 * caller.
2676 */
2677 error_free(local_err);
2678 ret = 0;
2679 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002680 }
2681
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002682 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002683}
2684
Max Reitzc1087f12019-05-22 19:03:46 +02002685int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2686{
2687 uint64_t parent_perms, parent_shared;
2688 uint64_t perms, shared;
2689
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002690 GLOBAL_STATE_CODE();
2691
Max Reitzc1087f12019-05-22 19:03:46 +02002692 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002693 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002694 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002695
2696 return bdrv_child_try_set_perm(c, perms, shared, errp);
2697}
2698
Max Reitz87278af2020-05-13 13:05:40 +02002699/*
2700 * Default implementation for .bdrv_child_perm() for block filters:
2701 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2702 * filtered child.
2703 */
2704static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002705 BdrvChildRole role,
2706 BlockReopenQueue *reopen_queue,
2707 uint64_t perm, uint64_t shared,
2708 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002709{
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002710 GLOBAL_STATE_CODE();
Kevin Wolfe444fa82019-08-02 15:59:41 +02002711 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2712 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002713}
2714
Max Reitz70082db2020-05-13 13:05:26 +02002715static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002716 BdrvChildRole role,
2717 BlockReopenQueue *reopen_queue,
2718 uint64_t perm, uint64_t shared,
2719 uint64_t *nperm, uint64_t *nshared)
2720{
Max Reitze5d8a402020-05-13 13:05:44 +02002721 assert(role & BDRV_CHILD_COW);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002722 GLOBAL_STATE_CODE();
Max Reitz70082db2020-05-13 13:05:26 +02002723
2724 /*
2725 * We want consistent read from backing files if the parent needs it.
2726 * No other operations are performed on backing files.
2727 */
2728 perm &= BLK_PERM_CONSISTENT_READ;
2729
2730 /*
2731 * If the parent can deal with changing data, we're okay with a
2732 * writable and resizable backing file.
2733 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2734 */
2735 if (shared & BLK_PERM_WRITE) {
2736 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2737 } else {
2738 shared = 0;
2739 }
2740
Vladimir Sementsov-Ogievskiy64631f32021-09-02 12:37:54 +03002741 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
Max Reitz70082db2020-05-13 13:05:26 +02002742
2743 if (bs->open_flags & BDRV_O_INACTIVE) {
2744 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2745 }
2746
2747 *nperm = perm;
2748 *nshared = shared;
2749}
2750
Max Reitz6f838a42020-05-13 13:05:27 +02002751static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002752 BdrvChildRole role,
2753 BlockReopenQueue *reopen_queue,
2754 uint64_t perm, uint64_t shared,
2755 uint64_t *nperm, uint64_t *nshared)
2756{
2757 int flags;
2758
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002759 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002760 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002761
2762 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2763
2764 /*
2765 * Apart from the modifications below, the same permissions are
2766 * forwarded and left alone as for filters
2767 */
Max Reitze5d8a402020-05-13 13:05:44 +02002768 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002769 perm, shared, &perm, &shared);
2770
Max Reitzf8890542020-05-13 13:05:28 +02002771 if (role & BDRV_CHILD_METADATA) {
2772 /* Format drivers may touch metadata even if the guest doesn't write */
2773 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2774 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2775 }
2776
2777 /*
2778 * bs->file always needs to be consistent because of the
2779 * metadata. We can never allow other users to resize or write
2780 * to it.
2781 */
2782 if (!(flags & BDRV_O_NO_IO)) {
2783 perm |= BLK_PERM_CONSISTENT_READ;
2784 }
2785 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002786 }
2787
Max Reitzf8890542020-05-13 13:05:28 +02002788 if (role & BDRV_CHILD_DATA) {
2789 /*
2790 * Technically, everything in this block is a subset of the
2791 * BDRV_CHILD_METADATA path taken above, and so this could
2792 * be an "else if" branch. However, that is not obvious, and
2793 * this function is not performance critical, therefore we let
2794 * this be an independent "if".
2795 */
2796
2797 /*
2798 * We cannot allow other users to resize the file because the
2799 * format driver might have some assumptions about the size
2800 * (e.g. because it is stored in metadata, or because the file
2801 * is split into fixed-size data files).
2802 */
2803 shared &= ~BLK_PERM_RESIZE;
2804
2805 /*
2806 * WRITE_UNCHANGED often cannot be performed as such on the
2807 * data file. For example, the qcow2 driver may still need to
2808 * write copied clusters on copy-on-read.
2809 */
2810 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2811 perm |= BLK_PERM_WRITE;
2812 }
2813
2814 /*
2815 * If the data file is written to, the format driver may
2816 * expect to be able to resize it by writing beyond the EOF.
2817 */
2818 if (perm & BLK_PERM_WRITE) {
2819 perm |= BLK_PERM_RESIZE;
2820 }
Max Reitz6f838a42020-05-13 13:05:27 +02002821 }
Max Reitz6f838a42020-05-13 13:05:27 +02002822
2823 if (bs->open_flags & BDRV_O_INACTIVE) {
2824 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2825 }
2826
2827 *nperm = perm;
2828 *nshared = shared;
2829}
2830
Max Reitz2519f542020-05-13 13:05:29 +02002831void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002832 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002833 uint64_t perm, uint64_t shared,
2834 uint64_t *nperm, uint64_t *nshared)
2835{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002836 GLOBAL_STATE_CODE();
Max Reitz2519f542020-05-13 13:05:29 +02002837 if (role & BDRV_CHILD_FILTERED) {
2838 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2839 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002840 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002841 perm, shared, nperm, nshared);
2842 } else if (role & BDRV_CHILD_COW) {
2843 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002844 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002845 perm, shared, nperm, nshared);
2846 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002847 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002848 perm, shared, nperm, nshared);
2849 } else {
2850 g_assert_not_reached();
2851 }
2852}
2853
Max Reitz7b1d9c42019-11-08 13:34:51 +01002854uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2855{
2856 static const uint64_t permissions[] = {
2857 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2858 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2859 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2860 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
Max Reitz7b1d9c42019-11-08 13:34:51 +01002861 };
2862
2863 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2864 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2865
2866 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2867
2868 return permissions[qapi_perm];
2869}
2870
Kevin Wolf23987472022-11-18 18:41:09 +01002871/*
2872 * Replaces the node that a BdrvChild points to without updating permissions.
2873 *
2874 * If @new_bs is non-NULL, the parent of @child must already be drained through
2875 * @child.
2876 *
2877 * This function does not poll.
2878 */
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03002879static void bdrv_replace_child_noperm(BdrvChild *child,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002880 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002881{
2882 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002883 int new_bs_quiesce_counter;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002884
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002885 assert(!child->frozen);
Kevin Wolf23987472022-11-18 18:41:09 +01002886
2887 /*
2888 * If we want to change the BdrvChild to point to a drained node as its new
2889 * child->bs, we need to make sure that its new parent is drained, too. In
2890 * other words, either child->quiesce_parent must already be true or we must
2891 * be able to set it and keep the parent's quiesce_counter consistent with
2892 * that, but without polling or starting new requests (this function
2893 * guarantees that it doesn't poll, and starting new requests would be
2894 * against the invariants of drain sections).
2895 *
2896 * To keep things simple, we pick the first option (child->quiesce_parent
2897 * must already be true). We also generalise the rule a bit to make it
2898 * easier to verify in callers and more likely to be covered in test cases:
2899 * The parent must be quiesced through this child even if new_bs isn't
2900 * currently drained.
2901 *
2902 * The only exception is for callers that always pass new_bs == NULL. In
2903 * this case, we obviously never need to consider the case of a drained
2904 * new_bs, so we can keep the callers simpler by allowing them not to drain
2905 * the parent.
2906 */
2907 assert(!new_bs || child->quiesced_parent);
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02002908 assert(old_bs != new_bs);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002909 GLOBAL_STATE_CODE();
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002910
Fam Zhengbb2614e2017-04-07 14:54:10 +08002911 if (old_bs && new_bs) {
2912 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2913 }
Max Reitzdebc2922019-07-22 15:33:44 +02002914
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002915 if (old_bs) {
Max Reitzbd86fb92020-05-13 13:05:13 +02002916 if (child->klass->detach) {
2917 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002918 }
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002919 assert_bdrv_graph_writable(old_bs);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002920 QLIST_REMOVE(child, next_parent);
2921 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002922
2923 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002924
2925 if (new_bs) {
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002926 assert_bdrv_graph_writable(new_bs);
Kevin Wolf36fe1332016-05-17 14:51:55 +02002927 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzbd86fb92020-05-13 13:05:13 +02002928 if (child->klass->attach) {
2929 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002930 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002931 }
Max Reitzdebc2922019-07-22 15:33:44 +02002932
2933 /*
Kevin Wolf23987472022-11-18 18:41:09 +01002934 * If the parent was drained through this BdrvChild previously, but new_bs
2935 * is not drained, allow requests to come in only after the new node has
2936 * been attached.
Max Reitzdebc2922019-07-22 15:33:44 +02002937 */
Kevin Wolf57e05be2022-11-18 18:41:06 +01002938 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2939 if (!new_bs_quiesce_counter && child->quiesced_parent) {
Max Reitzdebc2922019-07-22 15:33:44 +02002940 bdrv_parent_drained_end_single(child);
Max Reitzdebc2922019-07-22 15:33:44 +02002941 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002942}
2943
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002944/**
2945 * Free the given @child.
2946 *
2947 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2948 * unused (i.e. not in a children list).
2949 */
2950static void bdrv_child_free(BdrvChild *child)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002951{
2952 assert(!child->bs);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002953 GLOBAL_STATE_CODE();
Hanna Reitza2253692021-11-15 15:53:58 +01002954 assert(!child->next.le_prev); /* not in children list */
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002955
2956 g_free(child->name);
2957 g_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002958}
2959
2960typedef struct BdrvAttachChildCommonState {
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002961 BdrvChild *child;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002962 AioContext *old_parent_ctx;
2963 AioContext *old_child_ctx;
2964} BdrvAttachChildCommonState;
2965
2966static void bdrv_attach_child_common_abort(void *opaque)
2967{
2968 BdrvAttachChildCommonState *s = opaque;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002969 BlockDriverState *bs = s->child->bs;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002970
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002971 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002972 bdrv_replace_child_noperm(s->child, NULL);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002973
2974 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
Emanuele Giuseppe Esposito142e6902022-10-25 04:49:52 -04002975 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002976 }
2977
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002978 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04002979 Transaction *tran;
2980 GHashTable *visited;
2981 bool ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002982
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04002983 tran = tran_new();
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002984
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04002985 /* No need to visit `child`, because it has been detached already */
2986 visited = g_hash_table_new(NULL, NULL);
2987 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2988 visited, tran, &error_abort);
2989 g_hash_table_destroy(visited);
2990
2991 /* transaction is supposed to always succeed */
2992 assert(ret == true);
2993 tran_commit(tran);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002994 }
2995
2996 bdrv_unref(bs);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002997 bdrv_child_free(s->child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002998}
2999
3000static TransactionActionDrv bdrv_attach_child_common_drv = {
3001 .abort = bdrv_attach_child_common_abort,
3002 .clean = g_free,
3003};
3004
3005/*
3006 * Common part of attaching bdrv child to bs or to blk or to job
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003007 *
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003008 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003009 *
3010 * Returns new created child.
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003011 */
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003012static BdrvChild *bdrv_attach_child_common(BlockDriverState *child_bs,
3013 const char *child_name,
3014 const BdrvChildClass *child_class,
3015 BdrvChildRole child_role,
3016 uint64_t perm, uint64_t shared_perm,
3017 void *opaque,
3018 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003019{
3020 BdrvChild *new_child;
3021 AioContext *parent_ctx;
3022 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3023
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03003024 assert(child_class->get_parent_desc);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003025 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003026
3027 new_child = g_new(BdrvChild, 1);
3028 *new_child = (BdrvChild) {
3029 .bs = NULL,
3030 .name = g_strdup(child_name),
3031 .klass = child_class,
3032 .role = child_role,
3033 .perm = perm,
3034 .shared_perm = shared_perm,
3035 .opaque = opaque,
3036 };
3037
3038 /*
3039 * If the AioContexts don't match, first try to move the subtree of
3040 * child_bs into the AioContext of the new parent. If this doesn't work,
3041 * try moving the parent into the AioContext of child_bs instead.
3042 */
3043 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3044 if (child_ctx != parent_ctx) {
3045 Error *local_err = NULL;
Emanuele Giuseppe Esposito142e6902022-10-25 04:49:52 -04003046 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3047 &local_err);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003048
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04003049 if (ret < 0 && child_class->change_aio_ctx) {
3050 Transaction *tran = tran_new();
3051 GHashTable *visited = g_hash_table_new(NULL, NULL);
3052 bool ret_child;
3053
3054 g_hash_table_add(visited, new_child);
3055 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3056 visited, tran, NULL);
3057 if (ret_child == true) {
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003058 error_free(local_err);
3059 ret = 0;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003060 }
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04003061 tran_finalize(tran, ret_child == true ? 0 : -1);
3062 g_hash_table_destroy(visited);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003063 }
3064
3065 if (ret < 0) {
3066 error_propagate(errp, local_err);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01003067 bdrv_child_free(new_child);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003068 return NULL;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003069 }
3070 }
3071
3072 bdrv_ref(child_bs);
Kevin Wolf23987472022-11-18 18:41:09 +01003073 /*
3074 * Let every new BdrvChild start with a drained parent. Inserting the child
3075 * in the graph with bdrv_replace_child_noperm() will undrain it if
3076 * @child_bs is not drained.
3077 *
3078 * The child was only just created and is not yet visible in global state
3079 * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
3080 * could have sent requests and polling is not necessary.
3081 *
3082 * Note that this means that the parent isn't fully drained yet, we only
3083 * stop new requests from coming in. This is fine, we don't care about the
3084 * old requests here, they are not for this child. If another place enters a
3085 * drain section for the same parent, but wants it to be fully quiesced, it
3086 * will not run most of the the code in .drained_begin() again (which is not
3087 * a problem, we already did this), but it will still poll until the parent
3088 * is fully quiesced, so it will not be negatively affected either.
3089 */
Kevin Wolf606ed752022-11-18 18:41:10 +01003090 bdrv_parent_drained_begin_single(new_child);
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03003091 bdrv_replace_child_noperm(new_child, child_bs);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003092
3093 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3094 *s = (BdrvAttachChildCommonState) {
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003095 .child = new_child,
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003096 .old_parent_ctx = parent_ctx,
3097 .old_child_ctx = child_ctx,
3098 };
3099 tran_add(tran, &bdrv_attach_child_common_drv, s);
3100
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003101 return new_child;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003102}
3103
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003104/*
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003105 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003106 */
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003107static BdrvChild *bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3108 BlockDriverState *child_bs,
3109 const char *child_name,
3110 const BdrvChildClass *child_class,
3111 BdrvChildRole child_role,
3112 Transaction *tran,
3113 Error **errp)
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003114{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003115 uint64_t perm, shared_perm;
3116
3117 assert(parent_bs->drv);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003118 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003119
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02003120 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3121 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3122 child_bs->node_name, child_name, parent_bs->node_name);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003123 return NULL;
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02003124 }
3125
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003126 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3127 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3128 perm, shared_perm, &perm, &shared_perm);
3129
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003130 return bdrv_attach_child_common(child_bs, child_name, child_class,
3131 child_role, perm, shared_perm, parent_bs,
3132 tran, errp);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003133}
3134
Alberto Garciab441dc72019-05-13 16:46:18 +03003135/*
3136 * This function steals the reference to child_bs from the caller.
3137 * That reference is later dropped by bdrv_root_unref_child().
3138 *
3139 * On failure NULL is returned, errp is set and the reference to
3140 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003141 *
3142 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3143 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003144 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003145BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3146 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003147 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003148 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003149 uint64_t perm, uint64_t shared_perm,
3150 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003151{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003152 int ret;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003153 BdrvChild *child;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003154 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003155
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05003156 GLOBAL_STATE_CODE();
3157
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003158 child = bdrv_attach_child_common(child_bs, child_name, child_class,
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003159 child_role, perm, shared_perm, opaque,
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003160 tran, errp);
3161 if (!child) {
3162 ret = -EINVAL;
Kevin Wolfe878bb12021-05-03 13:05:54 +02003163 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003164 }
3165
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003166 ret = bdrv_refresh_perms(child_bs, tran, errp);
Kevin Wolfdf581792015-06-15 11:53:47 +02003167
Kevin Wolfe878bb12021-05-03 13:05:54 +02003168out:
3169 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003170
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003171 bdrv_unref(child_bs);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003172
3173 return ret < 0 ? NULL : child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003174}
3175
Alberto Garciab441dc72019-05-13 16:46:18 +03003176/*
3177 * This function transfers the reference to child_bs from the caller
3178 * to parent_bs. That reference is later dropped by parent_bs on
3179 * bdrv_close() or if someone calls bdrv_unref_child().
3180 *
3181 * On failure NULL is returned, errp is set and the reference to
3182 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003183 *
3184 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3185 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003186 */
Wen Congyang98292c62016-05-10 15:36:38 +08003187BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3188 BlockDriverState *child_bs,
3189 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003190 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003191 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003192 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003193{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003194 int ret;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003195 BdrvChild *child;
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003196 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003197
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003198 GLOBAL_STATE_CODE();
3199
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003200 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3201 child_class, child_role, tran, errp);
3202 if (!child) {
3203 ret = -EINVAL;
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003204 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003205 }
3206
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003207 ret = bdrv_refresh_perms(parent_bs, tran, errp);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003208 if (ret < 0) {
3209 goto out;
3210 }
3211
3212out:
3213 tran_finalize(tran, ret);
3214
3215 bdrv_unref(child_bs);
3216
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003217 return ret < 0 ? NULL : child;
Kevin Wolff21d96d2016-03-08 13:47:46 +01003218}
3219
Max Reitz7b99a262019-06-12 16:07:11 +02003220/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003221void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003222{
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003223 BlockDriverState *child_bs = child->bs;
Kevin Wolf779020c2015-10-13 14:09:44 +02003224
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003225 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003226 bdrv_replace_child_noperm(child, NULL);
3227 bdrv_child_free(child);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003228
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003229 if (child_bs) {
3230 /*
3231 * Update permissions for old node. We're just taking a parent away, so
3232 * we're loosening restrictions. Errors of permission update are not
3233 * fatal in this case, ignore them.
3234 */
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003235 bdrv_refresh_perms(child_bs, NULL, NULL);
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003236
3237 /*
3238 * When the parent requiring a non-default AioContext is removed, the
3239 * node moves back to the main AioContext
3240 */
3241 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3242 NULL);
3243 }
3244
Kevin Wolff21d96d2016-03-08 13:47:46 +01003245 bdrv_unref(child_bs);
3246}
3247
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003248typedef struct BdrvSetInheritsFrom {
3249 BlockDriverState *bs;
3250 BlockDriverState *old_inherits_from;
3251} BdrvSetInheritsFrom;
3252
3253static void bdrv_set_inherits_from_abort(void *opaque)
3254{
3255 BdrvSetInheritsFrom *s = opaque;
3256
3257 s->bs->inherits_from = s->old_inherits_from;
3258}
3259
3260static TransactionActionDrv bdrv_set_inherits_from_drv = {
3261 .abort = bdrv_set_inherits_from_abort,
3262 .clean = g_free,
3263};
3264
3265/* @tran is allowed to be NULL. In this case no rollback is possible */
3266static void bdrv_set_inherits_from(BlockDriverState *bs,
3267 BlockDriverState *new_inherits_from,
3268 Transaction *tran)
3269{
3270 if (tran) {
3271 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3272
3273 *s = (BdrvSetInheritsFrom) {
3274 .bs = bs,
3275 .old_inherits_from = bs->inherits_from,
3276 };
3277
3278 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3279 }
3280
3281 bs->inherits_from = new_inherits_from;
3282}
3283
Max Reitz3cf746b2019-07-03 19:28:07 +02003284/**
3285 * Clear all inherits_from pointers from children and grandchildren of
3286 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003287 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003288 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003289static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3290 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003291{
Max Reitz3cf746b2019-07-03 19:28:07 +02003292 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003293
Max Reitz3cf746b2019-07-03 19:28:07 +02003294 if (child->bs->inherits_from == root) {
3295 /*
3296 * Remove inherits_from only when the last reference between root and
3297 * child->bs goes away.
3298 */
3299 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003300 if (c != child && c->bs == child->bs) {
3301 break;
3302 }
3303 }
3304 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003305 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003306 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003307 }
3308
Max Reitz3cf746b2019-07-03 19:28:07 +02003309 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003310 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003311 }
3312}
3313
Max Reitz7b99a262019-06-12 16:07:11 +02003314/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003315void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3316{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003317 GLOBAL_STATE_CODE();
Max Reitz3cf746b2019-07-03 19:28:07 +02003318 if (child == NULL) {
3319 return;
3320 }
3321
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003322 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003323 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003324}
3325
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003326
3327static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3328{
3329 BdrvChild *c;
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003330 GLOBAL_STATE_CODE();
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003331 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003332 if (c->klass->change_media) {
3333 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003334 }
3335 }
3336}
3337
Alberto Garcia0065c452018-10-31 18:16:37 +02003338/* Return true if you can reach parent going through child->inherits_from
3339 * recursively. If parent or child are NULL, return false */
3340static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3341 BlockDriverState *parent)
3342{
3343 while (child && child != parent) {
3344 child = child->inherits_from;
3345 }
3346
3347 return child != NULL;
3348}
3349
Kevin Wolf5db15a52015-09-14 15:33:33 +02003350/*
Max Reitz25191e52020-05-13 13:05:33 +02003351 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3352 * mostly used for COW backing children (role = COW), but also for
3353 * filtered children (role = FILTERED | PRIMARY).
3354 */
3355static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3356{
3357 if (bs->drv && bs->drv->is_filter) {
3358 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3359 } else {
3360 return BDRV_CHILD_COW;
3361 }
3362}
3363
3364/*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003365 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3366 * callers which don't need their own reference any more must call bdrv_unref().
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003367 *
3368 * Function doesn't update permissions, caller is responsible for this.
Kevin Wolf5db15a52015-09-14 15:33:33 +02003369 */
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003370static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3371 BlockDriverState *child_bs,
3372 bool is_backing,
3373 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003374{
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003375 bool update_inherits_from =
3376 bdrv_inherits_from_recursive(child_bs, parent_bs);
3377 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3378 BdrvChildRole role;
Alberto Garcia0065c452018-10-31 18:16:37 +02003379
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003380 GLOBAL_STATE_CODE();
3381
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003382 if (!parent_bs->drv) {
3383 /*
3384 * Node without drv is an object without a class :/. TODO: finally fix
3385 * qcow2 driver to never clear bs->drv and implement format corruption
3386 * handling in other way.
3387 */
3388 error_setg(errp, "Node corrupted");
3389 return -EINVAL;
3390 }
3391
3392 if (child && child->frozen) {
3393 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3394 child->name, parent_bs->node_name, child->bs->node_name);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003395 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003396 }
3397
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03003398 if (is_backing && !parent_bs->drv->is_filter &&
3399 !parent_bs->drv->supports_backing)
3400 {
3401 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3402 "files", parent_bs->drv->format_name, parent_bs->node_name);
3403 return -EINVAL;
3404 }
3405
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003406 if (parent_bs->drv->is_filter) {
3407 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3408 } else if (is_backing) {
3409 role = BDRV_CHILD_COW;
3410 } else {
3411 /*
3412 * We only can use same role as it is in existing child. We don't have
3413 * infrastructure to determine role of file child in generic way
3414 */
3415 if (!child) {
3416 error_setg(errp, "Cannot set file child to format node without "
3417 "file child");
3418 return -EINVAL;
3419 }
3420 role = child->role;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003421 }
3422
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003423 if (child) {
3424 bdrv_unset_inherits_from(parent_bs, child, tran);
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03003425 bdrv_remove_child(child, tran);
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003426 }
3427
3428 if (!child_bs) {
Fam Zheng8d24cce2014-05-23 21:29:45 +08003429 goto out;
3430 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003431
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003432 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3433 is_backing ? "backing" : "file",
3434 &child_of_bds, role,
3435 tran, errp);
3436 if (!child) {
3437 return -EINVAL;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003438 }
3439
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003440
3441 /*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003442 * If inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003443 * point directly to bs (else it will become NULL).
3444 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003445 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003446 bdrv_set_inherits_from(child_bs, parent_bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003447 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003448
Fam Zheng8d24cce2014-05-23 21:29:45 +08003449out:
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003450 bdrv_refresh_limits(parent_bs, tran, NULL);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003451
3452 return 0;
3453}
3454
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003455static int bdrv_set_backing_noperm(BlockDriverState *bs,
3456 BlockDriverState *backing_hd,
3457 Transaction *tran, Error **errp)
3458{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003459 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003460 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3461}
3462
Kevin Wolf92140b92022-11-18 18:41:04 +01003463int bdrv_set_backing_hd_drained(BlockDriverState *bs,
3464 BlockDriverState *backing_hd,
3465 Error **errp)
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003466{
3467 int ret;
3468 Transaction *tran = tran_new();
3469
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003470 GLOBAL_STATE_CODE();
Kevin Wolf92140b92022-11-18 18:41:04 +01003471 assert(bs->quiesce_counter > 0);
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003472
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003473 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3474 if (ret < 0) {
3475 goto out;
3476 }
3477
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003478 ret = bdrv_refresh_perms(bs, tran, errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003479out:
3480 tran_finalize(tran, ret);
Kevin Wolf92140b92022-11-18 18:41:04 +01003481 return ret;
3482}
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003483
Kevin Wolf92140b92022-11-18 18:41:04 +01003484int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3485 Error **errp)
3486{
3487 int ret;
3488 GLOBAL_STATE_CODE();
3489
3490 bdrv_drained_begin(bs);
3491 ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003492 bdrv_drained_end(bs);
3493
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003494 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003495}
3496
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003497/*
3498 * Opens the backing file for a BlockDriverState if not yet open
3499 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003500 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3501 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3502 * itself, all options starting with "${bdref_key}." are considered part of the
3503 * BlockdevRef.
3504 *
3505 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003506 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003507int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3508 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003509{
Max Reitz6b6833c2019-02-01 20:29:15 +01003510 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003511 char *bdref_key_dot;
3512 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003513 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003514 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003515 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003516 QDict *options;
3517 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003518 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003519
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003520 GLOBAL_STATE_CODE();
3521
Kevin Wolf760e0062015-06-17 14:55:21 +02003522 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003523 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003524 }
3525
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003526 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003527 if (parent_options == NULL) {
3528 tmp_parent_options = qdict_new();
3529 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003530 }
3531
Paolo Bonzini9156df12012-10-18 16:49:17 +02003532 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003533
3534 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3535 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3536 g_free(bdref_key_dot);
3537
Markus Armbruster129c7d12017-03-30 19:43:12 +02003538 /*
3539 * Caution: while qdict_get_try_str() is fine, getting non-string
3540 * types would require more care. When @parent_options come from
3541 * -blockdev or blockdev_add, its members are typed according to
3542 * the QAPI schema, but when they come from -drive, they're all
3543 * QString.
3544 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003545 reference = qdict_get_try_str(parent_options, bdref_key);
3546 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003547 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003548 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003549 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003550 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003551 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003552 if (qdict_size(options) == 0) {
3553 /* If the user specifies options that do not modify the
3554 * backing file's behavior, we might still consider it the
3555 * implicit backing file. But it's easier this way, and
3556 * just specifying some of the backing BDS's options is
3557 * only possible with -drive anyway (otherwise the QAPI
3558 * schema forces the user to specify everything). */
3559 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3560 }
3561
Max Reitz6b6833c2019-02-01 20:29:15 +01003562 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003563 if (local_err) {
3564 ret = -EINVAL;
3565 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003566 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003567 goto free_exit;
3568 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003569 }
3570
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003571 if (!bs->drv || !bs->drv->supports_backing) {
3572 ret = -EINVAL;
3573 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003574 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003575 goto free_exit;
3576 }
3577
Peter Krempa6bff5972017-10-12 16:14:10 +02003578 if (!reference &&
3579 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003580 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003581 }
3582
Max Reitz6b6833c2019-02-01 20:29:15 +01003583 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003584 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003585 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003586 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003587 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003588 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003589 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003590 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003591
Max Reitz998c2012019-02-01 20:29:08 +01003592 if (implicit_backing) {
3593 bdrv_refresh_filename(backing_hd);
3594 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3595 backing_hd->filename);
3596 }
3597
Kevin Wolf5db15a52015-09-14 15:33:33 +02003598 /* Hook up the backing file link; drop our reference, bs owns the
3599 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003600 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003601 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003602 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003603 goto free_exit;
3604 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003605
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003606 qdict_del(parent_options, bdref_key);
3607
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003608free_exit:
3609 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003610 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003611 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003612}
3613
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003614static BlockDriverState *
3615bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003616 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003617 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003618{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003619 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003620 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003621 char *bdref_key_dot;
3622 const char *reference;
3623
Max Reitzbd86fb92020-05-13 13:05:13 +02003624 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003625
Max Reitzda557aa2013-12-20 19:28:11 +01003626 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3627 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3628 g_free(bdref_key_dot);
3629
Markus Armbruster129c7d12017-03-30 19:43:12 +02003630 /*
3631 * Caution: while qdict_get_try_str() is fine, getting non-string
3632 * types would require more care. When @options come from
3633 * -blockdev or blockdev_add, its members are typed according to
3634 * the QAPI schema, but when they come from -drive, they're all
3635 * QString.
3636 */
Max Reitzda557aa2013-12-20 19:28:11 +01003637 reference = qdict_get_try_str(options, bdref_key);
3638 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003639 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003640 error_setg(errp, "A block device must be specified for \"%s\"",
3641 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003642 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003643 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003644 goto done;
3645 }
3646
Max Reitz5b363932016-05-17 16:41:31 +02003647 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003648 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003649 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003650 goto done;
3651 }
3652
Max Reitzda557aa2013-12-20 19:28:11 +01003653done:
3654 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003655 return bs;
3656}
3657
3658/*
3659 * Opens a disk image whose options are given as BlockdevRef in another block
3660 * device's options.
3661 *
3662 * If allow_none is true, no image will be opened if filename is false and no
3663 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3664 *
3665 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3666 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3667 * itself, all options starting with "${bdref_key}." are considered part of the
3668 * BlockdevRef.
3669 *
3670 * The BlockdevRef will be removed from the options QDict.
3671 */
3672BdrvChild *bdrv_open_child(const char *filename,
3673 QDict *options, const char *bdref_key,
3674 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003675 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003676 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003677 bool allow_none, Error **errp)
3678{
3679 BlockDriverState *bs;
3680
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003681 GLOBAL_STATE_CODE();
3682
Max Reitzbd86fb92020-05-13 13:05:13 +02003683 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003684 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003685 if (bs == NULL) {
3686 return NULL;
3687 }
3688
Max Reitz258b7762020-05-13 13:05:15 +02003689 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3690 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003691}
3692
Max Reitzbd86fb92020-05-13 13:05:13 +02003693/*
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003694 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3695 */
3696int bdrv_open_file_child(const char *filename,
3697 QDict *options, const char *bdref_key,
3698 BlockDriverState *parent, Error **errp)
3699{
3700 BdrvChildRole role;
3701
3702 /* commit_top and mirror_top don't use this function */
3703 assert(!parent->drv->filtered_child_is_backing);
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003704 role = parent->drv->is_filter ?
3705 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3706
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003707 if (!bdrv_open_child(filename, options, bdref_key, parent,
3708 &child_of_bds, role, false, errp))
3709 {
3710 return -EINVAL;
3711 }
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003712
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003713 return 0;
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003714}
3715
3716/*
Max Reitzbd86fb92020-05-13 13:05:13 +02003717 * TODO Future callers may need to specify parent/child_class in order for
3718 * option inheritance to work. Existing callers use it for the root node.
3719 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003720BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3721{
3722 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003723 QObject *obj = NULL;
3724 QDict *qdict = NULL;
3725 const char *reference = NULL;
3726 Visitor *v = NULL;
3727
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003728 GLOBAL_STATE_CODE();
3729
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003730 if (ref->type == QTYPE_QSTRING) {
3731 reference = ref->u.reference;
3732 } else {
3733 BlockdevOptions *options = &ref->u.definition;
3734 assert(ref->type == QTYPE_QDICT);
3735
3736 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003737 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003738 visit_complete(v, &obj);
3739
Max Reitz7dc847e2018-02-24 16:40:29 +01003740 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003741 qdict_flatten(qdict);
3742
3743 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3744 * compatibility with other callers) rather than what we want as the
3745 * real defaults. Apply the defaults here instead. */
3746 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3747 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3748 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003749 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3750
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003751 }
3752
Max Reitz272c02e2020-05-13 13:05:17 +02003753 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003754 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003755 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003756 visit_free(v);
3757 return bs;
3758}
3759
Max Reitz66836182016-05-17 16:41:27 +02003760static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3761 int flags,
3762 QDict *snapshot_options,
3763 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003764{
Bin Meng69fbfff2022-10-10 12:04:31 +08003765 g_autofree char *tmp_filename = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003766 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003767 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003768 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003769 int ret;
3770
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003771 GLOBAL_STATE_CODE();
3772
Kevin Wolfb9988752014-04-03 12:09:34 +02003773 /* if snapshot, we create a temporary backing file and open it
3774 instead of opening 'filename' directly */
3775
3776 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003777 total_size = bdrv_getlength(bs);
3778 if (total_size < 0) {
3779 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003780 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003781 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003782
3783 /* Create the temporary image */
Bin Meng69fbfff2022-10-10 12:04:31 +08003784 tmp_filename = create_tmp_file(errp);
3785 if (!tmp_filename) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003786 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003787 }
3788
Max Reitzef810432014-12-02 18:32:42 +01003789 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003790 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003791 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003792 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003793 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003794 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003795 error_prepend(errp, "Could not create temporary overlay '%s': ",
3796 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003797 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003798 }
3799
Kevin Wolf73176be2016-03-07 13:02:15 +01003800 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003801 qdict_put_str(snapshot_options, "file.driver", "file");
3802 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3803 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003804
Max Reitz5b363932016-05-17 16:41:31 +02003805 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003806 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003807 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003808 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003809 }
3810
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003811 ret = bdrv_append(bs_snapshot, bs, errp);
3812 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003813 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003814 goto out;
3815 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003816
3817out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003818 qobject_unref(snapshot_options);
Eric Blakeff6ed712017-04-27 16:58:18 -05003819 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003820}
3821
Max Reitzda557aa2013-12-20 19:28:11 +01003822/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003823 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003824 *
3825 * options is a QDict of options to pass to the block drivers, or NULL for an
3826 * empty set of options. The reference to the QDict belongs to the block layer
3827 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003828 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003829 *
3830 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3831 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003832 *
3833 * The reference parameter may be used to specify an existing block device which
3834 * should be opened. If specified, neither options nor a filename may be given,
3835 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003836 */
Max Reitz5b363932016-05-17 16:41:31 +02003837static BlockDriverState *bdrv_open_inherit(const char *filename,
3838 const char *reference,
3839 QDict *options, int flags,
3840 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003841 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003842 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003843 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003844{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003845 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003846 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003847 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003848 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003849 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003850 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003851 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003852 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003853 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003854 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003855
Max Reitzbd86fb92020-05-13 13:05:13 +02003856 assert(!child_class || !flags);
3857 assert(!child_class == !parent);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003858 GLOBAL_STATE_CODE();
Max Reitzf67503e2014-02-18 18:33:05 +01003859
Max Reitzddf56362014-02-18 18:33:06 +01003860 if (reference) {
3861 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003862 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003863
Max Reitzddf56362014-02-18 18:33:06 +01003864 if (filename || options_non_empty) {
3865 error_setg(errp, "Cannot reference an existing block device with "
3866 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003867 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003868 }
3869
3870 bs = bdrv_lookup_bs(reference, reference, errp);
3871 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003872 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003873 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003874
Max Reitzddf56362014-02-18 18:33:06 +01003875 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003876 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003877 }
3878
Max Reitz5b363932016-05-17 16:41:31 +02003879 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003880
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003881 /* NULL means an empty set of options */
3882 if (options == NULL) {
3883 options = qdict_new();
3884 }
3885
Kevin Wolf145f5982015-05-08 16:15:03 +02003886 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003887 parse_json_protocol(options, &filename, &local_err);
3888 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003889 goto fail;
3890 }
3891
Kevin Wolf145f5982015-05-08 16:15:03 +02003892 bs->explicit_options = qdict_clone_shallow(options);
3893
Max Reitzbd86fb92020-05-13 13:05:13 +02003894 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003895 bool parent_is_format;
3896
3897 if (parent->drv) {
3898 parent_is_format = parent->drv->is_format;
3899 } else {
3900 /*
3901 * parent->drv is not set yet because this node is opened for
3902 * (potential) format probing. That means that @parent is going
3903 * to be a format node.
3904 */
3905 parent_is_format = true;
3906 }
3907
Kevin Wolfbddcec32015-04-09 18:47:50 +02003908 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003909 child_class->inherit_options(child_role, parent_is_format,
3910 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003911 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003912 }
3913
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003914 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003915 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003916 goto fail;
3917 }
3918
Markus Armbruster129c7d12017-03-30 19:43:12 +02003919 /*
3920 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3921 * Caution: getting a boolean member of @options requires care.
3922 * When @options come from -blockdev or blockdev_add, members are
3923 * typed according to the QAPI schema, but when they come from
3924 * -drive, they're all QString.
3925 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003926 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3927 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3928 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3929 } else {
3930 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003931 }
3932
3933 if (flags & BDRV_O_SNAPSHOT) {
3934 snapshot_options = qdict_new();
3935 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3936 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003937 /* Let bdrv_backing_options() override "read-only" */
3938 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003939 bdrv_inherited_options(BDRV_CHILD_COW, true,
3940 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003941 }
3942
Kevin Wolf62392eb2015-04-24 16:38:02 +02003943 bs->open_flags = flags;
3944 bs->options = options;
3945 options = qdict_clone_shallow(options);
3946
Kevin Wolf76c591b2014-06-04 14:19:44 +02003947 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003948 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003949 drvname = qdict_get_try_str(options, "driver");
3950 if (drvname) {
3951 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003952 if (!drv) {
3953 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003954 goto fail;
3955 }
3956 }
3957
3958 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003959
Markus Armbruster129c7d12017-03-30 19:43:12 +02003960 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003961 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003962 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3963 (backing && *backing == '\0'))
3964 {
Max Reitz4f7be282018-02-24 16:40:33 +01003965 if (backing) {
3966 warn_report("Use of \"backing\": \"\" is deprecated; "
3967 "use \"backing\": null instead");
3968 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003969 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003970 qdict_del(bs->explicit_options, "backing");
3971 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003972 qdict_del(options, "backing");
3973 }
3974
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003975 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003976 * probing, the block drivers will do their own bdrv_open_child() for the
3977 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003978 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003979 BlockDriverState *file_bs;
3980
3981 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003982 &child_of_bds, BDRV_CHILD_IMAGE,
3983 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003984 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003985 goto fail;
3986 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003987 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003988 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3989 * looking at the header to guess the image format. This works even
3990 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003991 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003992 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003993 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003994 if (local_err) {
3995 goto fail;
3996 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003997
Eric Blake46f5ac22017-04-27 16:58:17 -05003998 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003999 }
Max Reitz5469a2a2014-02-18 18:33:10 +01004000 }
4001
Kevin Wolf76c591b2014-06-04 14:19:44 +02004002 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01004003 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02004004 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02004005 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02004006 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02004007 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01004008 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02004009 /*
4010 * This option update would logically belong in bdrv_fill_options(),
4011 * but we first need to open bs->file for the probing to work, while
4012 * opening bs->file already requires the (mostly) final set of options
4013 * so that cache mode etc. can be inherited.
4014 *
4015 * Adding the driver later is somewhat ugly, but it's not an option
4016 * that would ever be inherited, so it's correct. We just need to make
4017 * sure to update both bs->options (which has the full effective
4018 * options for bs) and options (which has file.* already removed).
4019 */
Eric Blake46f5ac22017-04-27 16:58:17 -05004020 qdict_put_str(bs->options, "driver", drv->format_name);
4021 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02004022 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02004023 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02004024 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01004025 }
4026
Max Reitz53a29512015-03-19 14:53:16 -04004027 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
4028 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
4029 /* file must be NULL if a protocol BDS is about to be created
4030 * (the inverse results in an error message from bdrv_open_common()) */
4031 assert(!(flags & BDRV_O_PROTOCOL) || !file);
4032
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004033 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01004034 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004035 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02004036 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01004037 }
4038
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01004039 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01004040 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01004041 file = NULL;
4042 }
4043
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004044 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02004045 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01004046 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004047 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004048 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004049 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004050 }
4051
Alberto Garcia50196d72018-09-06 12:37:03 +03004052 /* Remove all children options and references
4053 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03004054 QLIST_FOREACH(child, &bs->children, next) {
4055 char *child_key_dot;
4056 child_key_dot = g_strdup_printf("%s.", child->name);
4057 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4058 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03004059 qdict_del(bs->explicit_options, child->name);
4060 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03004061 g_free(child_key_dot);
4062 }
4063
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004064 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01004065 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004066 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01004067 if (flags & BDRV_O_PROTOCOL) {
4068 error_setg(errp, "Block protocol '%s' doesn't support the option "
4069 "'%s'", drv->format_name, entry->key);
4070 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01004071 error_setg(errp,
4072 "Block format '%s' does not support the option '%s'",
4073 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01004074 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004075
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004076 goto close_and_fail;
4077 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004078
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01004079 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004080
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004081 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03004082 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004083
4084 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4085 * temporary snapshot afterwards. */
4086 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02004087 BlockDriverState *snapshot_bs;
4088 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4089 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01004090 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004091 if (local_err) {
4092 goto close_and_fail;
4093 }
Max Reitz5b363932016-05-17 16:41:31 +02004094 /* We are not going to return bs but the overlay on top of it
4095 * (snapshot_bs); thus, we have to drop the strong reference to bs
4096 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4097 * though, because the overlay still has a reference to it. */
4098 bdrv_unref(bs);
4099 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02004100 }
4101
Max Reitz5b363932016-05-17 16:41:31 +02004102 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004103
Kevin Wolf8bfea152014-04-11 19:16:36 +02004104fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01004105 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004106 qobject_unref(snapshot_options);
4107 qobject_unref(bs->explicit_options);
4108 qobject_unref(bs->options);
4109 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004110 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03004111 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02004112 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004113 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004114 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004115
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004116close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02004117 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004118 qobject_unref(snapshot_options);
4119 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004120 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004121 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004122}
4123
Max Reitz5b363932016-05-17 16:41:31 +02004124BlockDriverState *bdrv_open(const char *filename, const char *reference,
4125 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02004126{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004127 GLOBAL_STATE_CODE();
4128
Max Reitz5b363932016-05-17 16:41:31 +02004129 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02004130 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02004131}
4132
Alberto Garciafaf116b2019-03-12 18:48:49 +02004133/* Return true if the NULL-terminated @list contains @str */
4134static bool is_str_in_list(const char *str, const char *const *list)
4135{
4136 if (str && list) {
4137 int i;
4138 for (i = 0; list[i] != NULL; i++) {
4139 if (!strcmp(str, list[i])) {
4140 return true;
4141 }
4142 }
4143 }
4144 return false;
4145}
4146
4147/*
4148 * Check that every option set in @bs->options is also set in
4149 * @new_opts.
4150 *
4151 * Options listed in the common_options list and in
4152 * @bs->drv->mutable_opts are skipped.
4153 *
4154 * Return 0 on success, otherwise return -EINVAL and set @errp.
4155 */
4156static int bdrv_reset_options_allowed(BlockDriverState *bs,
4157 const QDict *new_opts, Error **errp)
4158{
4159 const QDictEntry *e;
4160 /* These options are common to all block drivers and are handled
4161 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4162 const char *const common_options[] = {
4163 "node-name", "discard", "cache.direct", "cache.no-flush",
4164 "read-only", "auto-read-only", "detect-zeroes", NULL
4165 };
4166
4167 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4168 if (!qdict_haskey(new_opts, e->key) &&
4169 !is_str_in_list(e->key, common_options) &&
4170 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4171 error_setg(errp, "Option '%s' cannot be reset "
4172 "to its default value", e->key);
4173 return -EINVAL;
4174 }
4175 }
4176
4177 return 0;
4178}
4179
Jeff Codye971aa12012-09-20 15:13:19 -04004180/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004181 * Returns true if @child can be reached recursively from @bs
4182 */
4183static bool bdrv_recurse_has_child(BlockDriverState *bs,
4184 BlockDriverState *child)
4185{
4186 BdrvChild *c;
4187
4188 if (bs == child) {
4189 return true;
4190 }
4191
4192 QLIST_FOREACH(c, &bs->children, next) {
4193 if (bdrv_recurse_has_child(c->bs, child)) {
4194 return true;
4195 }
4196 }
4197
4198 return false;
4199}
4200
4201/*
Jeff Codye971aa12012-09-20 15:13:19 -04004202 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4203 * reopen of multiple devices.
4204 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004205 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04004206 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4207 * be created and initialized. This newly created BlockReopenQueue should be
4208 * passed back in for subsequent calls that are intended to be of the same
4209 * atomic 'set'.
4210 *
4211 * bs is the BlockDriverState to add to the reopen queue.
4212 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004213 * options contains the changed options for the associated bs
4214 * (the BlockReopenQueue takes ownership)
4215 *
Jeff Codye971aa12012-09-20 15:13:19 -04004216 * flags contains the open flags for the associated bs
4217 *
4218 * returns a pointer to bs_queue, which is either the newly allocated
4219 * bs_queue, or the existing bs_queue being used.
4220 *
Kevin Wolfd22933a2022-11-18 18:41:02 +01004221 * bs is drained here and undrained by bdrv_reopen_queue_free().
Kevin Wolf2e117862022-11-18 18:41:01 +01004222 *
4223 * To be called with bs->aio_context locked.
Jeff Codye971aa12012-09-20 15:13:19 -04004224 */
Kevin Wolf28518102015-05-08 17:07:31 +02004225static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4226 BlockDriverState *bs,
4227 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02004228 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02004229 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004230 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02004231 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004232 int parent_flags,
4233 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04004234{
4235 assert(bs != NULL);
4236
4237 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02004238 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004239 QDict *old_options, *explicit_options, *options_copy;
4240 int flags;
4241 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004242
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05004243 GLOBAL_STATE_CODE();
Kevin Wolf1a63a902017-12-06 20:24:44 +01004244
Kevin Wolfd22933a2022-11-18 18:41:02 +01004245 bdrv_drained_begin(bs);
4246
Jeff Codye971aa12012-09-20 15:13:19 -04004247 if (bs_queue == NULL) {
4248 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004249 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04004250 }
4251
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004252 if (!options) {
4253 options = qdict_new();
4254 }
4255
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004256 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004257 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004258 if (bs == bs_entry->state.bs) {
4259 break;
4260 }
4261 }
4262
Kevin Wolf28518102015-05-08 17:07:31 +02004263 /*
4264 * Precedence of options:
4265 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004266 * 2. Retained from explicitly set options of bs
4267 * 3. Inherited from parent node
4268 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004269 */
4270
Kevin Wolf145f5982015-05-08 16:15:03 +02004271 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004272 if (bs_entry || keep_old_opts) {
4273 old_options = qdict_clone_shallow(bs_entry ?
4274 bs_entry->state.explicit_options :
4275 bs->explicit_options);
4276 bdrv_join_options(bs, options, old_options);
4277 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004278 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004279
4280 explicit_options = qdict_clone_shallow(options);
4281
Kevin Wolf28518102015-05-08 17:07:31 +02004282 /* Inherit from parent node */
4283 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004284 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004285 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004286 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004287 } else {
4288 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004289 }
4290
Alberto Garcia077e8e22019-03-12 18:48:44 +02004291 if (keep_old_opts) {
4292 /* Old values are used for options that aren't set yet */
4293 old_options = qdict_clone_shallow(bs->options);
4294 bdrv_join_options(bs, options, old_options);
4295 qobject_unref(old_options);
4296 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004297
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004298 /* We have the final set of options so let's update the flags */
4299 options_copy = qdict_clone_shallow(options);
4300 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4301 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4302 update_flags_from_options(&flags, opts);
4303 qemu_opts_del(opts);
4304 qobject_unref(options_copy);
4305
Kevin Wolffd452022017-08-03 17:02:59 +02004306 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004307 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004308 if (flags & BDRV_O_RDWR) {
4309 flags |= BDRV_O_ALLOW_RDWR;
4310 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004311
Kevin Wolf1857c972017-09-14 14:53:46 +02004312 if (!bs_entry) {
4313 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004314 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004315 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004316 qobject_unref(bs_entry->state.options);
4317 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004318 }
4319
4320 bs_entry->state.bs = bs;
4321 bs_entry->state.options = options;
4322 bs_entry->state.explicit_options = explicit_options;
4323 bs_entry->state.flags = flags;
4324
Alberto Garcia85466322019-03-12 18:48:45 +02004325 /*
4326 * If keep_old_opts is false then it means that unspecified
4327 * options must be reset to their original value. We don't allow
4328 * resetting 'backing' but we need to know if the option is
4329 * missing in order to decide if we have to return an error.
4330 */
4331 if (!keep_old_opts) {
4332 bs_entry->state.backing_missing =
4333 !qdict_haskey(options, "backing") &&
4334 !qdict_haskey(options, "backing.driver");
4335 }
4336
Kevin Wolf67251a32015-04-09 18:54:04 +02004337 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004338 QDict *new_child_options = NULL;
4339 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004340
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004341 /* reopen can only change the options of block devices that were
4342 * implicitly created and inherited options. For other (referenced)
4343 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004344 if (child->bs->inherits_from != bs) {
4345 continue;
4346 }
4347
Alberto Garcia85466322019-03-12 18:48:45 +02004348 /* Check if the options contain a child reference */
4349 if (qdict_haskey(options, child->name)) {
4350 const char *childref = qdict_get_try_str(options, child->name);
4351 /*
4352 * The current child must not be reopened if the child
4353 * reference is null or points to a different node.
4354 */
4355 if (g_strcmp0(childref, child->bs->node_name)) {
4356 continue;
4357 }
4358 /*
4359 * If the child reference points to the current child then
4360 * reopen it with its existing set of options (note that
4361 * it can still inherit new options from the parent).
4362 */
4363 child_keep_old = true;
4364 } else {
4365 /* Extract child options ("child-name.*") */
4366 char *child_key_dot = g_strdup_printf("%s.", child->name);
4367 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4368 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4369 g_free(child_key_dot);
4370 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004371
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004372 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004373 child->klass, child->role, bs->drv->is_format,
4374 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004375 }
4376
Jeff Codye971aa12012-09-20 15:13:19 -04004377 return bs_queue;
4378}
4379
Kevin Wolf2e117862022-11-18 18:41:01 +01004380/* To be called with bs->aio_context locked */
Kevin Wolf28518102015-05-08 17:07:31 +02004381BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4382 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004383 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004384{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004385 GLOBAL_STATE_CODE();
4386
Max Reitz3cdc69d2020-05-13 13:05:18 +02004387 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4388 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004389}
4390
Alberto Garciaab5b52282021-07-08 13:47:05 +02004391void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4392{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004393 GLOBAL_STATE_CODE();
Alberto Garciaab5b52282021-07-08 13:47:05 +02004394 if (bs_queue) {
4395 BlockReopenQueueEntry *bs_entry, *next;
4396 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Kevin Wolfd22933a2022-11-18 18:41:02 +01004397 AioContext *ctx = bdrv_get_aio_context(bs_entry->state.bs);
4398
4399 aio_context_acquire(ctx);
4400 bdrv_drained_end(bs_entry->state.bs);
4401 aio_context_release(ctx);
4402
Alberto Garciaab5b52282021-07-08 13:47:05 +02004403 qobject_unref(bs_entry->state.explicit_options);
4404 qobject_unref(bs_entry->state.options);
4405 g_free(bs_entry);
4406 }
4407 g_free(bs_queue);
4408 }
4409}
4410
Jeff Codye971aa12012-09-20 15:13:19 -04004411/*
4412 * Reopen multiple BlockDriverStates atomically & transactionally.
4413 *
4414 * The queue passed in (bs_queue) must have been built up previous
4415 * via bdrv_reopen_queue().
4416 *
4417 * Reopens all BDS specified in the queue, with the appropriate
4418 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004419 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004420 * data cleaned up.
4421 *
4422 * If all devices prepare successfully, then the changes are committed
4423 * to all devices.
4424 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004425 * All affected nodes must be drained between bdrv_reopen_queue() and
4426 * bdrv_reopen_multiple().
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004427 *
4428 * To be called from the main thread, with all other AioContexts unlocked.
Jeff Codye971aa12012-09-20 15:13:19 -04004429 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004430int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004431{
4432 int ret = -1;
4433 BlockReopenQueueEntry *bs_entry, *next;
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004434 AioContext *ctx;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004435 Transaction *tran = tran_new();
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004436 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004437
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004438 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Jeff Codye971aa12012-09-20 15:13:19 -04004439 assert(bs_queue != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004440 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004441
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004442 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004443 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4444 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004445 ret = bdrv_flush(bs_entry->state.bs);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004446 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004447 if (ret < 0) {
4448 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004449 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004450 }
4451 }
4452
4453 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004454 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004455 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4456 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004457 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004458 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004459 if (ret < 0) {
4460 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004461 }
4462 bs_entry->prepared = true;
4463 }
4464
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004465 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004466 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004467
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03004468 refresh_list = g_slist_prepend(refresh_list, state->bs);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004469 if (state->old_backing_bs) {
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03004470 refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004471 }
Alberto Garciaecd30d22021-06-10 15:05:36 +03004472 if (state->old_file_bs) {
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03004473 refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
Alberto Garciaecd30d22021-06-10 15:05:36 +03004474 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004475 }
4476
4477 /*
4478 * Note that file-posix driver rely on permission update done during reopen
4479 * (even if no permission changed), because it wants "new" permissions for
4480 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4481 * in raw_reopen_prepare() which is called with "old" permissions.
4482 */
4483 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4484 if (ret < 0) {
4485 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004486 }
4487
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004488 /*
4489 * If we reach this point, we have success and just need to apply the
4490 * changes.
4491 *
4492 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4493 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4494 * children are usually goes after parents in reopen-queue, so go from last
4495 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004496 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004497 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004498 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4499 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004500 bdrv_reopen_commit(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004501 aio_context_release(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004502 }
4503
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004504 tran_commit(tran);
4505
4506 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4507 BlockDriverState *bs = bs_entry->state.bs;
4508
4509 if (bs->drv->bdrv_reopen_commit_post) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004510 ctx = bdrv_get_aio_context(bs);
4511 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004512 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004513 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004514 }
4515 }
4516
Jeff Codye971aa12012-09-20 15:13:19 -04004517 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004518 goto cleanup;
4519
4520abort:
4521 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004522 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004523 if (bs_entry->prepared) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004524 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4525 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004526 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004527 aio_context_release(ctx);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004528 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004529 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004530
Jeff Codye971aa12012-09-20 15:13:19 -04004531cleanup:
Alberto Garciaab5b52282021-07-08 13:47:05 +02004532 bdrv_reopen_queue_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004533
Jeff Codye971aa12012-09-20 15:13:19 -04004534 return ret;
4535}
4536
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004537int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4538 Error **errp)
4539{
4540 AioContext *ctx = bdrv_get_aio_context(bs);
4541 BlockReopenQueue *queue;
4542 int ret;
4543
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004544 GLOBAL_STATE_CODE();
4545
Kevin Wolf2e117862022-11-18 18:41:01 +01004546 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4547
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004548 if (ctx != qemu_get_aio_context()) {
4549 aio_context_release(ctx);
4550 }
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004551 ret = bdrv_reopen_multiple(queue, errp);
4552
4553 if (ctx != qemu_get_aio_context()) {
4554 aio_context_acquire(ctx);
4555 }
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004556
4557 return ret;
4558}
4559
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004560int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4561 Error **errp)
4562{
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004563 QDict *opts = qdict_new();
4564
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004565 GLOBAL_STATE_CODE();
4566
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004567 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4568
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004569 return bdrv_reopen(bs, opts, true, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004570}
4571
Jeff Codye971aa12012-09-20 15:13:19 -04004572/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004573 * Take a BDRVReopenState and check if the value of 'backing' in the
4574 * reopen_state->options QDict is valid or not.
4575 *
4576 * If 'backing' is missing from the QDict then return 0.
4577 *
4578 * If 'backing' contains the node name of the backing file of
4579 * reopen_state->bs then return 0.
4580 *
4581 * If 'backing' contains a different node name (or is null) then check
4582 * whether the current backing file can be replaced with the new one.
4583 * If that's the case then reopen_state->replace_backing_bs is set to
4584 * true and reopen_state->new_backing_bs contains a pointer to the new
4585 * backing BlockDriverState (or NULL).
4586 *
4587 * Return 0 on success, otherwise return < 0 and set @errp.
4588 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004589static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4590 bool is_backing, Transaction *tran,
4591 Error **errp)
Alberto Garciacb828c32019-03-12 18:48:47 +02004592{
4593 BlockDriverState *bs = reopen_state->bs;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004594 BlockDriverState *new_child_bs;
4595 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4596 child_bs(bs->file);
4597 const char *child_name = is_backing ? "backing" : "file";
Alberto Garciacb828c32019-03-12 18:48:47 +02004598 QObject *value;
4599 const char *str;
4600
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05004601 GLOBAL_STATE_CODE();
4602
Alberto Garciaecd30d22021-06-10 15:05:36 +03004603 value = qdict_get(reopen_state->options, child_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004604 if (value == NULL) {
4605 return 0;
4606 }
4607
4608 switch (qobject_type(value)) {
4609 case QTYPE_QNULL:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004610 assert(is_backing); /* The 'file' option does not allow a null value */
4611 new_child_bs = NULL;
Alberto Garciacb828c32019-03-12 18:48:47 +02004612 break;
4613 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004614 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciaecd30d22021-06-10 15:05:36 +03004615 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4616 if (new_child_bs == NULL) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004617 return -EINVAL;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004618 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4619 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4620 "cycle", str, child_name, bs->node_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004621 return -EINVAL;
4622 }
4623 break;
4624 default:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004625 /*
4626 * The options QDict has been flattened, so 'backing' and 'file'
4627 * do not allow any other data type here.
4628 */
Alberto Garciacb828c32019-03-12 18:48:47 +02004629 g_assert_not_reached();
4630 }
4631
Alberto Garciaecd30d22021-06-10 15:05:36 +03004632 if (old_child_bs == new_child_bs) {
4633 return 0;
4634 }
4635
4636 if (old_child_bs) {
4637 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004638 return 0;
4639 }
4640
Alberto Garciaecd30d22021-06-10 15:05:36 +03004641 if (old_child_bs->implicit) {
4642 error_setg(errp, "Cannot replace implicit %s child of %s",
4643 child_name, bs->node_name);
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004644 return -EPERM;
4645 }
4646 }
4647
Alberto Garciaecd30d22021-06-10 15:05:36 +03004648 if (bs->drv->is_filter && !old_child_bs) {
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004649 /*
4650 * Filters always have a file or a backing child, so we are trying to
4651 * change wrong child
4652 */
4653 error_setg(errp, "'%s' is a %s filter node that does not support a "
Alberto Garciaecd30d22021-06-10 15:05:36 +03004654 "%s child", bs->node_name, bs->drv->format_name, child_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004655 return -EINVAL;
4656 }
4657
Alberto Garciaecd30d22021-06-10 15:05:36 +03004658 if (is_backing) {
4659 reopen_state->old_backing_bs = old_child_bs;
4660 } else {
4661 reopen_state->old_file_bs = old_child_bs;
4662 }
4663
4664 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4665 tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004666}
4667
4668/*
Jeff Codye971aa12012-09-20 15:13:19 -04004669 * Prepares a BlockDriverState for reopen. All changes are staged in the
4670 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4671 * the block driver layer .bdrv_reopen_prepare()
4672 *
4673 * bs is the BlockDriverState to reopen
4674 * flags are the new open flags
4675 * queue is the reopen queue
4676 *
4677 * Returns 0 on success, non-zero on error. On error errp will be set
4678 * as well.
4679 *
4680 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4681 * It is the responsibility of the caller to then call the abort() or
4682 * commit() for any other BDS that have been left in a prepare() state
4683 *
4684 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004685static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004686 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +03004687 Transaction *change_child_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004688{
4689 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004690 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004691 Error *local_err = NULL;
4692 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004693 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004694 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004695 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004696 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004697 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004698
4699 assert(reopen_state != NULL);
4700 assert(reopen_state->bs->drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004701 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004702 drv = reopen_state->bs->drv;
4703
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004704 /* This function and each driver's bdrv_reopen_prepare() remove
4705 * entries from reopen_state->options as they are processed, so
4706 * we need to make a copy of the original QDict. */
4707 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4708
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004709 /* Process generic block layer options */
4710 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004711 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004712 ret = -EINVAL;
4713 goto error;
4714 }
4715
Alberto Garciae6d79c42018-11-12 16:00:47 +02004716 /* This was already called in bdrv_reopen_queue_child() so the flags
4717 * are up-to-date. This time we simply want to remove the options from
4718 * QemuOpts in order to indicate that they have been processed. */
4719 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004720 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004721 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004722
Alberto Garcia415bbca2018-10-03 13:23:13 +03004723 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004724 if (discard != NULL) {
4725 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4726 error_setg(errp, "Invalid discard option");
4727 ret = -EINVAL;
4728 goto error;
4729 }
4730 }
4731
Alberto Garcia543770b2018-09-06 12:37:09 +03004732 reopen_state->detect_zeroes =
4733 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4734 if (local_err) {
4735 error_propagate(errp, local_err);
4736 ret = -EINVAL;
4737 goto error;
4738 }
4739
Alberto Garcia57f9db92018-09-06 12:37:06 +03004740 /* All other options (including node-name and driver) must be unchanged.
4741 * Put them back into the QDict, so that they are checked at the end
4742 * of this function. */
4743 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004744
Jeff Cody3d8ce172017-04-07 16:55:30 -04004745 /* If we are to stay read-only, do not allow permission change
4746 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4747 * not set, or if the BDS still has copy_on_read enabled */
4748 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004749 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004750 if (local_err) {
4751 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004752 goto error;
4753 }
4754
Jeff Codye971aa12012-09-20 15:13:19 -04004755 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004756 /*
4757 * If a driver-specific option is missing, it means that we
4758 * should reset it to its default value.
4759 * But not all options allow that, so we need to check it first.
4760 */
4761 ret = bdrv_reset_options_allowed(reopen_state->bs,
4762 reopen_state->options, errp);
4763 if (ret) {
4764 goto error;
4765 }
4766
Jeff Codye971aa12012-09-20 15:13:19 -04004767 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4768 if (ret) {
4769 if (local_err != NULL) {
4770 error_propagate(errp, local_err);
4771 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004772 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004773 error_setg(errp, "failed while preparing to reopen image '%s'",
4774 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004775 }
4776 goto error;
4777 }
4778 } else {
4779 /* It is currently mandatory to have a bdrv_reopen_prepare()
4780 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004781 error_setg(errp, "Block format '%s' used by node '%s' "
4782 "does not support reopening files", drv->format_name,
4783 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004784 ret = -1;
4785 goto error;
4786 }
4787
Max Reitz9ad08c42018-11-16 17:45:24 +01004788 drv_prepared = true;
4789
Alberto Garciabacd9b82019-03-12 18:48:46 +02004790 /*
4791 * We must provide the 'backing' option if the BDS has a backing
4792 * file or if the image file has a backing file name as part of
4793 * its metadata. Otherwise the 'backing' option can be omitted.
4794 */
4795 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004796 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004797 error_setg(errp, "backing is missing for '%s'",
4798 reopen_state->bs->node_name);
4799 ret = -EINVAL;
4800 goto error;
4801 }
4802
Alberto Garciacb828c32019-03-12 18:48:47 +02004803 /*
4804 * Allow changing the 'backing' option. The new value can be
4805 * either a reference to an existing node (using its node name)
4806 * or NULL to simply detach the current backing file.
4807 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004808 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4809 change_child_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004810 if (ret < 0) {
4811 goto error;
4812 }
4813 qdict_del(reopen_state->options, "backing");
4814
Alberto Garciaecd30d22021-06-10 15:05:36 +03004815 /* Allow changing the 'file' option. In this case NULL is not allowed */
4816 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4817 change_child_tran, errp);
4818 if (ret < 0) {
4819 goto error;
4820 }
4821 qdict_del(reopen_state->options, "file");
4822
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004823 /* Options that are not handled are only okay if they are unchanged
4824 * compared to the old state. It is expected that some options are only
4825 * used for the initial open, but not reopen (e.g. filename) */
4826 if (qdict_size(reopen_state->options)) {
4827 const QDictEntry *entry = qdict_first(reopen_state->options);
4828
4829 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004830 QObject *new = entry->value;
4831 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004832
Alberto Garciadb905282018-09-06 12:37:05 +03004833 /* Allow child references (child_name=node_name) as long as they
4834 * point to the current child (i.e. everything stays the same). */
4835 if (qobject_type(new) == QTYPE_QSTRING) {
4836 BdrvChild *child;
4837 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4838 if (!strcmp(child->name, entry->key)) {
4839 break;
4840 }
4841 }
4842
4843 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004844 if (!strcmp(child->bs->node_name,
4845 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004846 continue; /* Found child with this name, skip option */
4847 }
4848 }
4849 }
4850
Max Reitz54fd1b02017-11-14 19:01:26 +01004851 /*
4852 * TODO: When using -drive to specify blockdev options, all values
4853 * will be strings; however, when using -blockdev, blockdev-add or
4854 * filenames using the json:{} pseudo-protocol, they will be
4855 * correctly typed.
4856 * In contrast, reopening options are (currently) always strings
4857 * (because you can only specify them through qemu-io; all other
4858 * callers do not specify any options).
4859 * Therefore, when using anything other than -drive to create a BDS,
4860 * this cannot detect non-string options as unchanged, because
4861 * qobject_is_equal() always returns false for objects of different
4862 * type. In the future, this should be remedied by correctly typing
4863 * all options. For now, this is not too big of an issue because
4864 * the user can simply omit options which cannot be changed anyway,
4865 * so they will stay unchanged.
4866 */
4867 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004868 error_setg(errp, "Cannot change the option '%s'", entry->key);
4869 ret = -EINVAL;
4870 goto error;
4871 }
4872 } while ((entry = qdict_next(reopen_state->options, entry)));
4873 }
4874
Jeff Codye971aa12012-09-20 15:13:19 -04004875 ret = 0;
4876
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004877 /* Restore the original reopen_state->options QDict */
4878 qobject_unref(reopen_state->options);
4879 reopen_state->options = qobject_ref(orig_reopen_opts);
4880
Jeff Codye971aa12012-09-20 15:13:19 -04004881error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004882 if (ret < 0 && drv_prepared) {
4883 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4884 * call drv->bdrv_reopen_abort() before signaling an error
4885 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4886 * when the respective bdrv_reopen_prepare() has failed) */
4887 if (drv->bdrv_reopen_abort) {
4888 drv->bdrv_reopen_abort(reopen_state);
4889 }
4890 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004891 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004892 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004893 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004894 return ret;
4895}
4896
4897/*
4898 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4899 * makes them final by swapping the staging BlockDriverState contents into
4900 * the active BlockDriverState contents.
4901 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004902static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004903{
4904 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004905 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004906 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004907
4908 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004909 bs = reopen_state->bs;
4910 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004911 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004912 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004913
4914 /* If there are any driver level actions to take */
4915 if (drv->bdrv_reopen_commit) {
4916 drv->bdrv_reopen_commit(reopen_state);
4917 }
4918
4919 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004920 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004921 qobject_unref(bs->options);
Alberto Garciaab5b52282021-07-08 13:47:05 +02004922 qobject_ref(reopen_state->explicit_options);
4923 qobject_ref(reopen_state->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004924
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004925 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004926 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004927 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004928 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004929
Alberto Garcia50196d72018-09-06 12:37:03 +03004930 /* Remove child references from bs->options and bs->explicit_options.
4931 * Child options were already removed in bdrv_reopen_queue_child() */
4932 QLIST_FOREACH(child, &bs->children, next) {
4933 qdict_del(bs->explicit_options, child->name);
4934 qdict_del(bs->options, child->name);
4935 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004936 /* backing is probably removed, so it's not handled by previous loop */
4937 qdict_del(bs->explicit_options, "backing");
4938 qdict_del(bs->options, "backing");
4939
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004940 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004941}
4942
4943/*
4944 * Abort the reopen, and delete and free the staged changes in
4945 * reopen_state
4946 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004947static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004948{
4949 BlockDriver *drv;
4950
4951 assert(reopen_state != NULL);
4952 drv = reopen_state->bs->drv;
4953 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004954 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004955
4956 if (drv->bdrv_reopen_abort) {
4957 drv->bdrv_reopen_abort(reopen_state);
4958 }
4959}
4960
4961
Max Reitz64dff522016-01-29 16:36:10 +01004962static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004963{
Max Reitz33384422014-06-20 21:57:33 +02004964 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004965 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004966
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004967 GLOBAL_STATE_CODE();
Max Reitz30f55fb2016-05-17 16:41:32 +02004968 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004969
Paolo Bonzinifc272912015-12-23 11:48:24 +01004970 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004971 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004972 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004973
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004974 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004975 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004976 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004977 bs->drv->bdrv_close(bs);
4978 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004979 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004980 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004981
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004982 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004983 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004984 }
4985
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03004986 assert(!bs->backing);
4987 assert(!bs->file);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004988 g_free(bs->opaque);
4989 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004990 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004991 bs->backing_file[0] = '\0';
4992 bs->backing_format[0] = '\0';
4993 bs->total_sectors = 0;
4994 bs->encrypted = false;
4995 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004996 qobject_unref(bs->options);
4997 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004998 bs->options = NULL;
4999 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02005000 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02005001 bs->full_open_options = NULL;
Hanna Reitz0bc329f2021-08-12 10:41:44 +02005002 g_free(bs->block_status_cache);
5003 bs->block_status_cache = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02005004
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03005005 bdrv_release_named_dirty_bitmaps(bs);
5006 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
5007
Max Reitz33384422014-06-20 21:57:33 +02005008 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
5009 g_free(ban);
5010 }
5011 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01005012 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02005013
5014 /*
5015 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
5016 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
5017 * gets called.
5018 */
5019 if (bs->quiesce_counter) {
5020 bdrv_drain_all_end_quiesce(bs);
5021 }
bellardb3380822004-03-14 21:38:54 +00005022}
5023
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09005024void bdrv_close_all(void)
5025{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005026 GLOBAL_STATE_CODE();
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04005027 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09005028
Max Reitzca9bd242016-01-29 16:36:14 +01005029 /* Drop references from requests still in flight, such as canceled block
5030 * jobs whose AIO context has not been polled yet */
5031 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02005032
Max Reitzca9bd242016-01-29 16:36:14 +01005033 blk_remove_all_bs();
5034 blockdev_close_all_bdrv_states();
5035
Kevin Wolfa1a2af02016-04-08 18:26:37 +02005036 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09005037}
5038
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005039static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005040{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005041 GQueue *queue;
5042 GHashTable *found;
5043 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005044
Max Reitzbd86fb92020-05-13 13:05:13 +02005045 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005046 return false;
5047 }
5048
Max Reitzec9f10f2018-06-13 20:18:15 +02005049 /* If the child @c belongs to the BDS @to, replacing the current
5050 * c->bs by @to would mean to create a loop.
5051 *
5052 * Such a case occurs when appending a BDS to a backing chain.
5053 * For instance, imagine the following chain:
5054 *
5055 * guest device -> node A -> further backing chain...
5056 *
5057 * Now we create a new BDS B which we want to put on top of this
5058 * chain, so we first attach A as its backing node:
5059 *
5060 * node B
5061 * |
5062 * v
5063 * guest device -> node A -> further backing chain...
5064 *
5065 * Finally we want to replace A by B. When doing that, we want to
5066 * replace all pointers to A by pointers to B -- except for the
5067 * pointer from B because (1) that would create a loop, and (2)
5068 * that pointer should simply stay intact:
5069 *
5070 * guest device -> node B
5071 * |
5072 * v
5073 * node A -> further backing chain...
5074 *
5075 * In general, when replacing a node A (c->bs) by a node B (@to),
5076 * if A is a child of B, that means we cannot replace A by B there
5077 * because that would create a loop. Silently detaching A from B
5078 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005079 * place there is the most sensible choice.
5080 *
5081 * We would also create a loop in any cases where @c is only
5082 * indirectly referenced by @to. Prevent this by returning false
5083 * if @c is found (by breadth-first search) anywhere in the whole
5084 * subtree of @to.
5085 */
5086
5087 ret = true;
5088 found = g_hash_table_new(NULL, NULL);
5089 g_hash_table_add(found, to);
5090 queue = g_queue_new();
5091 g_queue_push_tail(queue, to);
5092
5093 while (!g_queue_is_empty(queue)) {
5094 BlockDriverState *v = g_queue_pop_head(queue);
5095 BdrvChild *c2;
5096
5097 QLIST_FOREACH(c2, &v->children, next) {
5098 if (c2 == c) {
5099 ret = false;
5100 break;
5101 }
5102
5103 if (g_hash_table_contains(found, c2->bs)) {
5104 continue;
5105 }
5106
5107 g_queue_push_tail(queue, c2->bs);
5108 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005109 }
5110 }
5111
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005112 g_queue_free(queue);
5113 g_hash_table_destroy(found);
5114
5115 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005116}
5117
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005118static void bdrv_remove_child_commit(void *opaque)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005119{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005120 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03005121 bdrv_child_free(opaque);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005122}
5123
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005124static TransactionActionDrv bdrv_remove_child_drv = {
5125 .commit = bdrv_remove_child_commit,
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005126};
5127
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005128/* Function doesn't update permissions, caller is responsible for this. */
5129static void bdrv_remove_child(BdrvChild *child, Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005130{
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005131 if (!child) {
5132 return;
5133 }
5134
5135 if (child->bs) {
Kevin Wolf23987472022-11-18 18:41:09 +01005136 BlockDriverState *bs = child->bs;
5137 bdrv_drained_begin(bs);
Vladimir Sementsov-Ogievskiya2c37a32022-07-26 23:11:30 +03005138 bdrv_replace_child_tran(child, NULL, tran);
Kevin Wolf23987472022-11-18 18:41:09 +01005139 bdrv_drained_end(bs);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005140 }
5141
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005142 tran_add(tran, &bdrv_remove_child_drv, child);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005143}
5144
Kevin Wolf23987472022-11-18 18:41:09 +01005145static void undrain_on_clean_cb(void *opaque)
5146{
5147 bdrv_drained_end(opaque);
5148}
5149
5150static TransactionActionDrv undrain_on_clean = {
5151 .clean = undrain_on_clean_cb,
5152};
5153
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005154static int bdrv_replace_node_noperm(BlockDriverState *from,
5155 BlockDriverState *to,
5156 bool auto_skip, Transaction *tran,
5157 Error **errp)
5158{
5159 BdrvChild *c, *next;
5160
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005161 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005162
Kevin Wolf23987472022-11-18 18:41:09 +01005163 bdrv_drained_begin(from);
5164 bdrv_drained_begin(to);
5165 tran_add(tran, &undrain_on_clean, from);
5166 tran_add(tran, &undrain_on_clean, to);
5167
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005168 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5169 assert(c->bs == from);
5170 if (!should_update_child(c, to)) {
5171 if (auto_skip) {
5172 continue;
5173 }
5174 error_setg(errp, "Should not change '%s' link to '%s'",
5175 c->name, from->node_name);
5176 return -EINVAL;
5177 }
5178 if (c->frozen) {
5179 error_setg(errp, "Cannot change '%s' link to '%s'",
5180 c->name, from->node_name);
5181 return -EPERM;
5182 }
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03005183 bdrv_replace_child_tran(c, to, tran);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005184 }
5185
5186 return 0;
5187}
5188
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005189/*
5190 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5191 * if it creates a parent-child relation loop or if parent is block-job.
5192 *
5193 * With auto_skip=false the error is returned if from has a parent which should
5194 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005195 *
5196 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5197 * case backing link of the cow-parent of @to is removed.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005198 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005199static int bdrv_replace_node_common(BlockDriverState *from,
5200 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005201 bool auto_skip, bool detach_subchain,
5202 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005203{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005204 Transaction *tran = tran_new();
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005205 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04005206 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005207 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005208
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005209 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005210
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005211 if (detach_subchain) {
5212 assert(bdrv_chain_contains(from, to));
5213 assert(from != to);
5214 for (to_cow_parent = from;
5215 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5216 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5217 {
5218 ;
5219 }
5220 }
5221
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005222 /* Make sure that @from doesn't go away until we have successfully attached
5223 * all of its parents to @to. */
5224 bdrv_ref(from);
5225
Kevin Wolff871abd2019-05-21 19:00:25 +02005226 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01005227 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02005228 bdrv_drained_begin(from);
5229
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005230 /*
5231 * Do the replacement without permission update.
5232 * Replacement may influence the permissions, we should calculate new
5233 * permissions based on new graph. If we fail, we'll roll-back the
5234 * replacement.
5235 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005236 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5237 if (ret < 0) {
5238 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005239 }
5240
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005241 if (detach_subchain) {
Vladimir Sementsov-Ogievskiyf38eaec2022-11-07 19:35:56 +03005242 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005243 }
5244
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03005245 refresh_list = g_slist_prepend(refresh_list, to);
5246 refresh_list = g_slist_prepend(refresh_list, from);
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005247
5248 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005249 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005250 goto out;
5251 }
5252
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005253 ret = 0;
5254
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005255out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005256 tran_finalize(tran, ret);
5257
Kevin Wolff871abd2019-05-21 19:00:25 +02005258 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005259 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005260
5261 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005262}
5263
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005264int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5265 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005266{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005267 GLOBAL_STATE_CODE();
5268
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005269 return bdrv_replace_node_common(from, to, true, false, errp);
5270}
5271
5272int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5273{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005274 GLOBAL_STATE_CODE();
5275
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005276 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5277 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005278}
5279
Jeff Cody8802d1f2012-02-28 15:54:06 -05005280/*
5281 * Add new bs contents at the top of an image chain while the chain is
5282 * live, while keeping required fields on the top layer.
5283 *
5284 * This will modify the BlockDriverState fields, and swap contents
5285 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5286 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005287 * bs_new must not be attached to a BlockBackend and must not have backing
5288 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005289 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005290 * This function does not create any image files.
5291 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005292int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5293 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005294{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005295 int ret;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03005296 BdrvChild *child;
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005297 Transaction *tran = tran_new();
5298
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005299 GLOBAL_STATE_CODE();
5300
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005301 assert(!bs_new->backing);
5302
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03005303 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5304 &child_of_bds, bdrv_backing_role(bs_new),
5305 tran, errp);
5306 if (!child) {
5307 ret = -EINVAL;
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005308 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005309 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005310
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005311 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005312 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005313 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005314 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005315
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03005316 ret = bdrv_refresh_perms(bs_new, tran, errp);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005317out:
5318 tran_finalize(tran, ret);
5319
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005320 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005321
5322 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005323}
5324
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005325/* Not for empty child */
5326int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5327 Error **errp)
5328{
5329 int ret;
5330 Transaction *tran = tran_new();
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005331 g_autoptr(GSList) refresh_list = NULL;
5332 BlockDriverState *old_bs = child->bs;
5333
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005334 GLOBAL_STATE_CODE();
5335
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005336 bdrv_ref(old_bs);
5337 bdrv_drained_begin(old_bs);
5338 bdrv_drained_begin(new_bs);
5339
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03005340 bdrv_replace_child_tran(child, new_bs, tran);
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005341
Vladimir Sementsov-Ogievskiyfb0ff4d2022-11-07 19:35:58 +03005342 refresh_list = g_slist_prepend(refresh_list, old_bs);
5343 refresh_list = g_slist_prepend(refresh_list, new_bs);
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005344
5345 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5346
5347 tran_finalize(tran, ret);
5348
5349 bdrv_drained_end(old_bs);
5350 bdrv_drained_end(new_bs);
5351 bdrv_unref(old_bs);
5352
5353 return ret;
5354}
5355
Fam Zheng4f6fd342013-08-23 09:14:47 +08005356static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005357{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005358 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005359 assert(!bs->refcnt);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005360 GLOBAL_STATE_CODE();
Markus Armbruster18846de2010-06-29 16:58:30 +02005361
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005362 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005363 if (bs->node_name[0] != '\0') {
5364 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5365 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005366 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5367
Anton Kuchin30c321f2019-05-07 11:12:56 +03005368 bdrv_close(bs);
5369
Anthony Liguori7267c092011-08-20 22:09:37 -05005370 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005371}
5372
Vladimir Sementsov-Ogievskiy96796fa2021-09-20 14:55:36 +03005373
5374/*
5375 * Replace @bs by newly created block node.
5376 *
5377 * @options is a QDict of options to pass to the block drivers, or NULL for an
5378 * empty set of options. The reference to the QDict belongs to the block layer
5379 * after the call (even on failure), so if the caller intends to reuse the
5380 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5381 */
5382BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005383 int flags, Error **errp)
5384{
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005385 ERRP_GUARD();
5386 int ret;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005387 BlockDriverState *new_node_bs = NULL;
5388 const char *drvname, *node_name;
5389 BlockDriver *drv;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005390
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005391 drvname = qdict_get_try_str(options, "driver");
5392 if (!drvname) {
5393 error_setg(errp, "driver is not specified");
5394 goto fail;
5395 }
5396
5397 drv = bdrv_find_format(drvname);
5398 if (!drv) {
5399 error_setg(errp, "Unknown driver: '%s'", drvname);
5400 goto fail;
5401 }
5402
5403 node_name = qdict_get_try_str(options, "node-name");
5404
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005405 GLOBAL_STATE_CODE();
5406
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005407 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5408 errp);
5409 options = NULL; /* bdrv_new_open_driver() eats options */
5410 if (!new_node_bs) {
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005411 error_prepend(errp, "Could not create node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005412 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005413 }
5414
5415 bdrv_drained_begin(bs);
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005416 ret = bdrv_replace_node(bs, new_node_bs, errp);
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005417 bdrv_drained_end(bs);
5418
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005419 if (ret < 0) {
5420 error_prepend(errp, "Could not replace node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005421 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005422 }
5423
5424 return new_node_bs;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005425
5426fail:
5427 qobject_unref(options);
5428 bdrv_unref(new_node_bs);
5429 return NULL;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005430}
5431
aliguorie97fc192009-04-21 23:11:50 +00005432/*
5433 * Run consistency checks on an image
5434 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005435 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005436 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005437 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005438 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005439int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5440 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005441{
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05005442 IO_CODE();
Max Reitz908bcd52014-08-07 22:47:55 +02005443 if (bs->drv == NULL) {
5444 return -ENOMEDIUM;
5445 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005446 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005447 return -ENOTSUP;
5448 }
5449
Kevin Wolfe076f332010-06-29 11:43:13 +02005450 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005451 return bs->drv->bdrv_co_check(bs, res, fix);
5452}
5453
Kevin Wolf756e6732010-01-12 12:55:17 +01005454/*
5455 * Return values:
5456 * 0 - success
5457 * -EINVAL - backing format specified, but no file
5458 * -ENOSPC - can't update the backing file because no space is left in the
5459 * image file header
5460 * -ENOTSUP - format driver doesn't support changing the backing file
5461 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005462int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
Eric Blake497a30d2021-05-03 14:36:00 -07005463 const char *backing_fmt, bool require)
Kevin Wolf756e6732010-01-12 12:55:17 +01005464{
5465 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005466 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005467
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005468 GLOBAL_STATE_CODE();
5469
Max Reitzd470ad42017-11-10 21:31:09 +01005470 if (!drv) {
5471 return -ENOMEDIUM;
5472 }
5473
Paolo Bonzini5f377792012-04-12 14:01:01 +02005474 /* Backing file format doesn't make sense without a backing file */
5475 if (backing_fmt && !backing_file) {
5476 return -EINVAL;
5477 }
5478
Eric Blake497a30d2021-05-03 14:36:00 -07005479 if (require && backing_file && !backing_fmt) {
5480 return -EINVAL;
Eric Blakee54ee1b2020-07-06 15:39:53 -05005481 }
5482
Kevin Wolf756e6732010-01-12 12:55:17 +01005483 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005484 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005485 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005486 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005487 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005488
5489 if (ret == 0) {
5490 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5491 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005492 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5493 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005494 }
5495 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005496}
5497
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005498/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005499 * Finds the first non-filter node above bs in the chain between
5500 * active and bs. The returned node is either an immediate parent of
5501 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005502 *
5503 * Returns NULL if bs is not found in active's image chain,
5504 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005505 *
5506 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005507 */
5508BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5509 BlockDriverState *bs)
5510{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005511
5512 GLOBAL_STATE_CODE();
5513
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005514 bs = bdrv_skip_filters(bs);
5515 active = bdrv_skip_filters(active);
5516
5517 while (active) {
5518 BlockDriverState *next = bdrv_backing_chain_next(active);
5519 if (bs == next) {
5520 return active;
5521 }
5522 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005523 }
5524
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005525 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005526}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005527
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005528/* Given a BDS, searches for the base layer. */
5529BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5530{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005531 GLOBAL_STATE_CODE();
5532
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005533 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005534}
5535
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005536/*
Max Reitz7b99a262019-06-12 16:07:11 +02005537 * Return true if at least one of the COW (backing) and filter links
5538 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005539 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005540 */
5541bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5542 Error **errp)
5543{
5544 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005545 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005546
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005547 GLOBAL_STATE_CODE();
5548
Max Reitz7b99a262019-06-12 16:07:11 +02005549 for (i = bs; i != base; i = child_bs(child)) {
5550 child = bdrv_filter_or_cow_child(i);
5551
5552 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005553 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005554 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005555 return true;
5556 }
5557 }
5558
5559 return false;
5560}
5561
5562/*
Max Reitz7b99a262019-06-12 16:07:11 +02005563 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005564 * If any of the links is already frozen the operation is aborted and
5565 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005566 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005567 * Returns 0 on success. On failure returns < 0 and sets @errp.
5568 */
5569int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5570 Error **errp)
5571{
5572 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005573 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005574
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005575 GLOBAL_STATE_CODE();
5576
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005577 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5578 return -EPERM;
5579 }
5580
Max Reitz7b99a262019-06-12 16:07:11 +02005581 for (i = bs; i != base; i = child_bs(child)) {
5582 child = bdrv_filter_or_cow_child(i);
5583 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005584 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005585 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005586 return -EPERM;
5587 }
5588 }
5589
Max Reitz7b99a262019-06-12 16:07:11 +02005590 for (i = bs; i != base; i = child_bs(child)) {
5591 child = bdrv_filter_or_cow_child(i);
5592 if (child) {
5593 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005594 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005595 }
5596
5597 return 0;
5598}
5599
5600/*
Max Reitz7b99a262019-06-12 16:07:11 +02005601 * Unfreeze all COW (backing) and filter links between @bs and @base.
5602 * The caller must ensure that all links are frozen before using this
5603 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005604 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005605 */
5606void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5607{
5608 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005609 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005610
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005611 GLOBAL_STATE_CODE();
5612
Max Reitz7b99a262019-06-12 16:07:11 +02005613 for (i = bs; i != base; i = child_bs(child)) {
5614 child = bdrv_filter_or_cow_child(i);
5615 if (child) {
5616 assert(child->frozen);
5617 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005618 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005619 }
5620}
5621
5622/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005623 * Drops images above 'base' up to and including 'top', and sets the image
5624 * above 'top' to have base as its backing file.
5625 *
5626 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5627 * information in 'bs' can be properly updated.
5628 *
5629 * E.g., this will convert the following chain:
5630 * bottom <- base <- intermediate <- top <- active
5631 *
5632 * to
5633 *
5634 * bottom <- base <- active
5635 *
5636 * It is allowed for bottom==base, in which case it converts:
5637 *
5638 * base <- intermediate <- top <- active
5639 *
5640 * to
5641 *
5642 * base <- active
5643 *
Jeff Cody54e26902014-06-25 15:40:10 -04005644 * If backing_file_str is non-NULL, it will be used when modifying top's
5645 * overlay image metadata.
5646 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005647 * Error conditions:
5648 * if active == top, that is considered an error
5649 *
5650 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005651int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5652 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005653{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005654 BlockDriverState *explicit_top = top;
5655 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005656 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005657 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005658 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005659 g_autoptr(GSList) updated_children = NULL;
5660 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005661
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005662 GLOBAL_STATE_CODE();
5663
Kevin Wolf6858eba2017-06-29 19:32:21 +02005664 bdrv_ref(top);
Kevin Wolf631086d2022-11-18 18:41:03 +01005665 bdrv_drained_begin(base);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005666
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005667 if (!top->drv || !base->drv) {
5668 goto exit;
5669 }
5670
Kevin Wolf5db15a52015-09-14 15:33:33 +02005671 /* Make sure that base is in the backing chain of top */
5672 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005673 goto exit;
5674 }
5675
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005676 /* If 'base' recursively inherits from 'top' then we should set
5677 * base->inherits_from to top->inherits_from after 'top' and all
5678 * other intermediate nodes have been dropped.
5679 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5680 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005681 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005682 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5683
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005684 /* success - we can delete the intermediate states, and link top->base */
Max Reitzf30c66b2019-02-01 20:29:05 +01005685 if (!backing_file_str) {
5686 bdrv_refresh_filename(base);
5687 backing_file_str = base->filename;
5688 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005689
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005690 QLIST_FOREACH(c, &top->parents, next_parent) {
5691 updated_children = g_slist_prepend(updated_children, c);
5692 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005693
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005694 /*
5695 * It seems correct to pass detach_subchain=true here, but it triggers
5696 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5697 * another drained section, which modify the graph (for example, removing
5698 * the child, which we keep in updated_children list). So, it's a TODO.
5699 *
5700 * Note, bug triggered if pass detach_subchain=true here and run
5701 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5702 * That's a FIXME.
5703 */
5704 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005705 if (local_err) {
5706 error_report_err(local_err);
5707 goto exit;
5708 }
5709
5710 for (p = updated_children; p; p = p->next) {
5711 c = p->data;
5712
Max Reitzbd86fb92020-05-13 13:05:13 +02005713 if (c->klass->update_filename) {
5714 ret = c->klass->update_filename(c, base, backing_file_str,
5715 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005716 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005717 /*
5718 * TODO: Actually, we want to rollback all previous iterations
5719 * of this loop, and (which is almost impossible) previous
5720 * bdrv_replace_node()...
5721 *
5722 * Note, that c->klass->update_filename may lead to permission
5723 * update, so it's a bad idea to call it inside permission
5724 * update transaction of bdrv_replace_node.
5725 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005726 error_report_err(local_err);
5727 goto exit;
5728 }
5729 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005730 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005731
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005732 if (update_inherits_from) {
5733 base->inherits_from = explicit_top->inherits_from;
5734 }
5735
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005736 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005737exit:
Kevin Wolf631086d2022-11-18 18:41:03 +01005738 bdrv_drained_end(base);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005739 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005740 return ret;
5741}
5742
bellard83f64092006-08-01 16:21:11 +00005743/**
Max Reitz081e4652019-06-12 18:14:13 +02005744 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5745 * sums the size of all data-bearing children. (This excludes backing
5746 * children.)
5747 */
5748static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5749{
5750 BdrvChild *child;
5751 int64_t child_size, sum = 0;
5752
5753 QLIST_FOREACH(child, &bs->children, next) {
5754 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5755 BDRV_CHILD_FILTERED))
5756 {
5757 child_size = bdrv_get_allocated_file_size(child->bs);
5758 if (child_size < 0) {
5759 return child_size;
5760 }
5761 sum += child_size;
5762 }
5763 }
5764
5765 return sum;
5766}
5767
5768/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005769 * Length of a allocated file in bytes. Sparse files are counted by actual
5770 * allocated space. Return < 0 if error or unknown.
5771 */
5772int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5773{
5774 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005775 IO_CODE();
5776
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005777 if (!drv) {
5778 return -ENOMEDIUM;
5779 }
5780 if (drv->bdrv_get_allocated_file_size) {
5781 return drv->bdrv_get_allocated_file_size(bs);
5782 }
Max Reitz081e4652019-06-12 18:14:13 +02005783
5784 if (drv->bdrv_file_open) {
5785 /*
5786 * Protocol drivers default to -ENOTSUP (most of their data is
5787 * not stored in any of their children (if they even have any),
5788 * so there is no generic way to figure it out).
5789 */
5790 return -ENOTSUP;
5791 } else if (drv->is_filter) {
5792 /* Filter drivers default to the size of their filtered child */
5793 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5794 } else {
5795 /* Other drivers default to summing their children's sizes */
5796 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005797 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005798}
5799
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005800/*
5801 * bdrv_measure:
5802 * @drv: Format driver
5803 * @opts: Creation options for new image
5804 * @in_bs: Existing image containing data for new image (may be NULL)
5805 * @errp: Error object
5806 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5807 * or NULL on error
5808 *
5809 * Calculate file size required to create a new image.
5810 *
5811 * If @in_bs is given then space for allocated clusters and zero clusters
5812 * from that image are included in the calculation. If @opts contains a
5813 * backing file that is shared by @in_bs then backing clusters may be omitted
5814 * from the calculation.
5815 *
5816 * If @in_bs is NULL then the calculation includes no allocated clusters
5817 * unless a preallocation option is given in @opts.
5818 *
5819 * Note that @in_bs may use a different BlockDriver from @drv.
5820 *
5821 * If an error occurs the @errp pointer is set.
5822 */
5823BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5824 BlockDriverState *in_bs, Error **errp)
5825{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005826 IO_CODE();
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005827 if (!drv->bdrv_measure) {
5828 error_setg(errp, "Block driver '%s' does not support size measurement",
5829 drv->format_name);
5830 return NULL;
5831 }
5832
5833 return drv->bdrv_measure(opts, in_bs, errp);
5834}
5835
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005836/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005837 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005838 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005839int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005840{
5841 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005842 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005843
bellard83f64092006-08-01 16:21:11 +00005844 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005845 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005846
Kevin Wolfb94a2612013-10-29 12:18:58 +01005847 if (drv->has_variable_length) {
5848 int ret = refresh_total_sectors(bs, bs->total_sectors);
5849 if (ret < 0) {
5850 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005851 }
bellard83f64092006-08-01 16:21:11 +00005852 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005853 return bs->total_sectors;
5854}
5855
5856/**
5857 * Return length in bytes on success, -errno on error.
5858 * The length is always a multiple of BDRV_SECTOR_SIZE.
5859 */
5860int64_t bdrv_getlength(BlockDriverState *bs)
5861{
5862 int64_t ret = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005863 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005864
Eric Blake122860b2020-11-05 09:51:22 -06005865 if (ret < 0) {
5866 return ret;
5867 }
5868 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5869 return -EFBIG;
5870 }
5871 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005872}
5873
bellard19cb3732006-08-19 11:45:59 +00005874/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005875void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005876{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005877 int64_t nb_sectors = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005878 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005879
5880 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005881}
bellardcf989512004-02-16 21:56:36 +00005882
Eric Blake54115412016-06-23 16:37:26 -06005883bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005884{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005885 IO_CODE();
ths985a03b2007-12-24 16:10:43 +00005886 return bs->sg;
5887}
5888
Max Reitzae23f782019-06-12 22:57:15 +02005889/**
5890 * Return whether the given node supports compressed writes.
5891 */
5892bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5893{
5894 BlockDriverState *filtered;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005895 IO_CODE();
Max Reitzae23f782019-06-12 22:57:15 +02005896
5897 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5898 return false;
5899 }
5900
5901 filtered = bdrv_filter_bs(bs);
5902 if (filtered) {
5903 /*
5904 * Filters can only forward compressed writes, so we have to
5905 * check the child.
5906 */
5907 return bdrv_supports_compressed_writes(filtered);
5908 }
5909
5910 return true;
5911}
5912
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005913const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005914{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005915 IO_CODE();
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005916 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005917}
5918
Stefan Hajnocziada42402014-08-27 12:08:55 +01005919static int qsort_strcmp(const void *a, const void *b)
5920{
Max Reitzceff5bd2016-10-12 22:49:05 +02005921 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005922}
5923
ths5fafdf22007-09-16 21:08:06 +00005924void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005925 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005926{
5927 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005928 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005929 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005930 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005931
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005932 GLOBAL_STATE_CODE();
5933
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005934 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005935 if (drv->format_name) {
5936 bool found = false;
5937 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005938
5939 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5940 continue;
5941 }
5942
Jeff Codye855e4f2014-04-28 18:29:54 -04005943 while (formats && i && !found) {
5944 found = !strcmp(formats[--i], drv->format_name);
5945 }
5946
5947 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005948 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005949 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005950 }
5951 }
bellardea2384d2004-08-01 21:59:26 +00005952 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005953
Max Reitzeb0df692016-10-12 22:49:06 +02005954 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5955 const char *format_name = block_driver_modules[i].format_name;
5956
5957 if (format_name) {
5958 bool found = false;
5959 int j = count;
5960
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005961 if (use_bdrv_whitelist &&
5962 !bdrv_format_is_whitelisted(format_name, read_only)) {
5963 continue;
5964 }
5965
Max Reitzeb0df692016-10-12 22:49:06 +02005966 while (formats && j && !found) {
5967 found = !strcmp(formats[--j], format_name);
5968 }
5969
5970 if (!found) {
5971 formats = g_renew(const char *, formats, count + 1);
5972 formats[count++] = format_name;
5973 }
5974 }
5975 }
5976
Stefan Hajnocziada42402014-08-27 12:08:55 +01005977 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5978
5979 for (i = 0; i < count; i++) {
5980 it(opaque, formats[i]);
5981 }
5982
Jeff Codye855e4f2014-04-28 18:29:54 -04005983 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005984}
5985
Benoît Canetdc364f42014-01-23 21:31:32 +01005986/* This function is to find a node in the bs graph */
5987BlockDriverState *bdrv_find_node(const char *node_name)
5988{
5989 BlockDriverState *bs;
5990
5991 assert(node_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005992 GLOBAL_STATE_CODE();
Benoît Canetdc364f42014-01-23 21:31:32 +01005993
5994 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5995 if (!strcmp(node_name, bs->node_name)) {
5996 return bs;
5997 }
5998 }
5999 return NULL;
6000}
6001
Benoît Canetc13163f2014-01-23 21:31:34 +01006002/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01006003BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6004 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01006005{
Eric Blake9812e712020-10-27 00:05:47 -05006006 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01006007 BlockDriverState *bs;
6008
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006009 GLOBAL_STATE_CODE();
6010
Benoît Canetc13163f2014-01-23 21:31:34 +01006011 list = NULL;
6012 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01006013 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03006014 if (!info) {
6015 qapi_free_BlockDeviceInfoList(list);
6016 return NULL;
6017 }
Eric Blake9812e712020-10-27 00:05:47 -05006018 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01006019 }
6020
6021 return list;
6022}
6023
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006024typedef struct XDbgBlockGraphConstructor {
6025 XDbgBlockGraph *graph;
6026 GHashTable *graph_nodes;
6027} XDbgBlockGraphConstructor;
6028
6029static XDbgBlockGraphConstructor *xdbg_graph_new(void)
6030{
6031 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
6032
6033 gr->graph = g_new0(XDbgBlockGraph, 1);
6034 gr->graph_nodes = g_hash_table_new(NULL, NULL);
6035
6036 return gr;
6037}
6038
6039static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
6040{
6041 XDbgBlockGraph *graph = gr->graph;
6042
6043 g_hash_table_destroy(gr->graph_nodes);
6044 g_free(gr);
6045
6046 return graph;
6047}
6048
6049static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
6050{
6051 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
6052
6053 if (ret != 0) {
6054 return ret;
6055 }
6056
6057 /*
6058 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6059 * answer of g_hash_table_lookup.
6060 */
6061 ret = g_hash_table_size(gr->graph_nodes) + 1;
6062 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6063
6064 return ret;
6065}
6066
6067static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6068 XDbgBlockGraphNodeType type, const char *name)
6069{
6070 XDbgBlockGraphNode *n;
6071
6072 n = g_new0(XDbgBlockGraphNode, 1);
6073
6074 n->id = xdbg_graph_node_num(gr, node);
6075 n->type = type;
6076 n->name = g_strdup(name);
6077
Eric Blake9812e712020-10-27 00:05:47 -05006078 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006079}
6080
6081static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6082 const BdrvChild *child)
6083{
Max Reitzcdb1cec2019-11-08 13:34:52 +01006084 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006085 XDbgBlockGraphEdge *edge;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05006086 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006087
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006088 edge = g_new0(XDbgBlockGraphEdge, 1);
6089
6090 edge->parent = xdbg_graph_node_num(gr, parent);
6091 edge->child = xdbg_graph_node_num(gr, child->bs);
6092 edge->name = g_strdup(child->name);
6093
Max Reitzcdb1cec2019-11-08 13:34:52 +01006094 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6095 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6096
6097 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006098 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006099 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01006100 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006101 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006102 }
6103 }
6104
Eric Blake9812e712020-10-27 00:05:47 -05006105 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006106}
6107
6108
6109XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6110{
6111 BlockBackend *blk;
6112 BlockJob *job;
6113 BlockDriverState *bs;
6114 BdrvChild *child;
6115 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6116
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006117 GLOBAL_STATE_CODE();
6118
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006119 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6120 char *allocated_name = NULL;
6121 const char *name = blk_name(blk);
6122
6123 if (!*name) {
6124 name = allocated_name = blk_get_attached_dev_id(blk);
6125 }
6126 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6127 name);
6128 g_free(allocated_name);
6129 if (blk_root(blk)) {
6130 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6131 }
6132 }
6133
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04006134 WITH_JOB_LOCK_GUARD() {
6135 for (job = block_job_next_locked(NULL); job;
6136 job = block_job_next_locked(job)) {
6137 GSList *el;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006138
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04006139 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6140 job->job.id);
6141 for (el = job->nodes; el; el = el->next) {
6142 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6143 }
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006144 }
6145 }
6146
6147 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6148 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6149 bs->node_name);
6150 QLIST_FOREACH(child, &bs->children, next) {
6151 xdbg_graph_add_edge(gr, bs, child);
6152 }
6153 }
6154
6155 return xdbg_graph_finalize(gr);
6156}
6157
Benoît Canet12d3ba82014-01-23 21:31:35 +01006158BlockDriverState *bdrv_lookup_bs(const char *device,
6159 const char *node_name,
6160 Error **errp)
6161{
Markus Armbruster7f06d472014-10-07 13:59:12 +02006162 BlockBackend *blk;
6163 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006164
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006165 GLOBAL_STATE_CODE();
6166
Benoît Canet12d3ba82014-01-23 21:31:35 +01006167 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02006168 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006169
Markus Armbruster7f06d472014-10-07 13:59:12 +02006170 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006171 bs = blk_bs(blk);
6172 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02006173 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02006174 }
6175
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006176 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006177 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006178 }
6179
Benoît Canetdd67fa52014-02-12 17:15:06 +01006180 if (node_name) {
6181 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006182
Benoît Canetdd67fa52014-02-12 17:15:06 +01006183 if (bs) {
6184 return bs;
6185 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006186 }
6187
Connor Kuehl785ec4b2021-03-05 09:19:28 -06006188 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01006189 device ? device : "",
6190 node_name ? node_name : "");
6191 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006192}
6193
Jeff Cody5a6684d2014-06-25 15:40:09 -04006194/* If 'base' is in the same chain as 'top', return true. Otherwise,
6195 * return false. If either argument is NULL, return false. */
6196bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6197{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006198
6199 GLOBAL_STATE_CODE();
6200
Jeff Cody5a6684d2014-06-25 15:40:09 -04006201 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006202 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04006203 }
6204
6205 return top != NULL;
6206}
6207
Fam Zheng04df7652014-10-31 11:32:54 +08006208BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6209{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006210 GLOBAL_STATE_CODE();
Fam Zheng04df7652014-10-31 11:32:54 +08006211 if (!bs) {
6212 return QTAILQ_FIRST(&graph_bdrv_states);
6213 }
6214 return QTAILQ_NEXT(bs, node_list);
6215}
6216
Kevin Wolf0f122642018-03-28 18:29:18 +02006217BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6218{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006219 GLOBAL_STATE_CODE();
Kevin Wolf0f122642018-03-28 18:29:18 +02006220 if (!bs) {
6221 return QTAILQ_FIRST(&all_bdrv_states);
6222 }
6223 return QTAILQ_NEXT(bs, bs_list);
6224}
6225
Fam Zheng20a9e772014-10-31 11:32:55 +08006226const char *bdrv_get_node_name(const BlockDriverState *bs)
6227{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006228 IO_CODE();
Fam Zheng20a9e772014-10-31 11:32:55 +08006229 return bs->node_name;
6230}
6231
Kevin Wolf1f0c4612016-03-22 18:38:44 +01006232const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006233{
6234 BdrvChild *c;
6235 const char *name;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05006236 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006237
6238 /* If multiple parents have a name, just pick the first one. */
6239 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006240 if (c->klass->get_name) {
6241 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006242 if (name && *name) {
6243 return name;
6244 }
6245 }
6246 }
6247
6248 return NULL;
6249}
6250
Markus Armbruster7f06d472014-10-07 13:59:12 +02006251/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02006252const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00006253{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006254 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006255 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00006256}
6257
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006258/* This can be used to identify nodes that might not have a device
6259 * name associated. Since node and device names live in the same
6260 * namespace, the result is unambiguous. The exception is if both are
6261 * absent, then this returns an empty (non-null) string. */
6262const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6263{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006264 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006265 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006266}
6267
Markus Armbrusterc8433282012-06-05 16:49:24 +02006268int bdrv_get_flags(BlockDriverState *bs)
6269{
Hanna Reitz15aee7a2022-04-27 13:40:54 +02006270 IO_CODE();
Markus Armbrusterc8433282012-06-05 16:49:24 +02006271 return bs->open_flags;
6272}
6273
Peter Lieven3ac21622013-06-28 12:47:42 +02006274int bdrv_has_zero_init_1(BlockDriverState *bs)
6275{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006276 GLOBAL_STATE_CODE();
Peter Lieven3ac21622013-06-28 12:47:42 +02006277 return 1;
6278}
6279
Kevin Wolff2feebb2010-04-14 17:30:35 +02006280int bdrv_has_zero_init(BlockDriverState *bs)
6281{
Max Reitz93393e62019-06-12 17:03:38 +02006282 BlockDriverState *filtered;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006283 GLOBAL_STATE_CODE();
Max Reitz93393e62019-06-12 17:03:38 +02006284
Max Reitzd470ad42017-11-10 21:31:09 +01006285 if (!bs->drv) {
6286 return 0;
6287 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006288
Paolo Bonzini11212d82013-09-04 19:00:27 +02006289 /* If BS is a copy on write image, it is initialized to
6290 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02006291 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02006292 return 0;
6293 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02006294 if (bs->drv->bdrv_has_zero_init) {
6295 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02006296 }
Max Reitz93393e62019-06-12 17:03:38 +02006297
6298 filtered = bdrv_filter_bs(bs);
6299 if (filtered) {
6300 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006301 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006302
Peter Lieven3ac21622013-06-28 12:47:42 +02006303 /* safe default */
6304 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02006305}
6306
Peter Lieven4ce78692013-10-24 12:06:54 +02006307bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6308{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006309 IO_CODE();
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03006310 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02006311 return false;
6312 }
6313
Eric Blakee24d8132018-01-26 13:34:39 -06006314 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02006315}
6316
ths5fafdf22007-09-16 21:08:06 +00006317void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00006318 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00006319{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006320 IO_CODE();
Kevin Wolf3574c602011-10-26 11:02:11 +02006321 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00006322}
6323
bellardfaea38e2006-08-05 21:31:00 +00006324int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6325{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006326 int ret;
bellardfaea38e2006-08-05 21:31:00 +00006327 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006328 IO_CODE();
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006329 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6330 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00006331 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006332 }
6333 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02006334 BlockDriverState *filtered = bdrv_filter_bs(bs);
6335 if (filtered) {
6336 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006337 }
bellardfaea38e2006-08-05 21:31:00 +00006338 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006339 }
bellardfaea38e2006-08-05 21:31:00 +00006340 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006341 ret = drv->bdrv_get_info(bs, bdi);
6342 if (ret < 0) {
6343 return ret;
6344 }
6345
6346 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6347 return -EINVAL;
6348 }
6349
6350 return 0;
bellardfaea38e2006-08-05 21:31:00 +00006351}
6352
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006353ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6354 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02006355{
6356 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006357 IO_CODE();
Max Reitzeae041f2013-10-09 10:46:16 +02006358 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006359 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02006360 }
6361 return NULL;
6362}
6363
Anton Nefedovd9245592019-09-23 15:17:37 +03006364BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6365{
6366 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006367 IO_CODE();
Anton Nefedovd9245592019-09-23 15:17:37 +03006368 if (!drv || !drv->bdrv_get_specific_stats) {
6369 return NULL;
6370 }
6371 return drv->bdrv_get_specific_stats(bs);
6372}
6373
Eric Blakea31939e2015-11-18 01:52:54 -07006374void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006375{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006376 IO_CODE();
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006377 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006378 return;
6379 }
6380
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006381 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006382}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006383
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006384static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01006385{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006386 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006387 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02006388 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006389 }
6390
6391 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006392 assert(bs->drv->bdrv_debug_remove_breakpoint);
6393 return bs;
6394 }
6395
6396 return NULL;
6397}
6398
6399int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6400 const char *tag)
6401{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006402 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006403 bs = bdrv_find_debug_node(bs);
6404 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006405 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6406 }
6407
6408 return -ENOTSUP;
6409}
6410
Fam Zheng4cc70e92013-11-20 10:01:54 +08006411int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6412{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006413 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006414 bs = bdrv_find_debug_node(bs);
6415 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006416 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6417 }
6418
6419 return -ENOTSUP;
6420}
6421
Kevin Wolf41c695c2012-12-06 14:32:58 +01006422int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6423{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006424 GLOBAL_STATE_CODE();
Max Reitz938789e2014-03-10 23:44:08 +01006425 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006426 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006427 }
6428
6429 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6430 return bs->drv->bdrv_debug_resume(bs, tag);
6431 }
6432
6433 return -ENOTSUP;
6434}
6435
6436bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6437{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006438 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006439 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006440 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006441 }
6442
6443 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6444 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6445 }
6446
6447 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006448}
6449
Jeff Codyb1b1d782012-10-16 15:49:09 -04006450/* backing_file can either be relative, or absolute, or a protocol. If it is
6451 * relative, it must be relative to the chain. So, passing in bs->filename
6452 * from a BDS as backing_file should not be done, as that may be relative to
6453 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006454BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6455 const char *backing_file)
6456{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006457 char *filename_full = NULL;
6458 char *backing_file_full = NULL;
6459 char *filename_tmp = NULL;
6460 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006461 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006462 BlockDriverState *curr_bs = NULL;
6463 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006464 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006465
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006466 GLOBAL_STATE_CODE();
6467
Jeff Codyb1b1d782012-10-16 15:49:09 -04006468 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006469 return NULL;
6470 }
6471
Jeff Codyb1b1d782012-10-16 15:49:09 -04006472 filename_full = g_malloc(PATH_MAX);
6473 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006474
6475 is_protocol = path_has_protocol(backing_file);
6476
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006477 /*
6478 * Being largely a legacy function, skip any filters here
6479 * (because filters do not have normal filenames, so they cannot
6480 * match anyway; and allowing json:{} filenames is a bit out of
6481 * scope).
6482 */
6483 for (curr_bs = bdrv_skip_filters(bs);
6484 bdrv_cow_child(curr_bs) != NULL;
6485 curr_bs = bs_below)
6486 {
6487 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006488
Max Reitz0b877d02018-08-01 20:34:11 +02006489 if (bdrv_backing_overridden(curr_bs)) {
6490 /*
6491 * If the backing file was overridden, we can only compare
6492 * directly against the backing node's filename.
6493 */
6494
6495 if (!filenames_refreshed) {
6496 /*
6497 * This will automatically refresh all of the
6498 * filenames in the rest of the backing chain, so we
6499 * only need to do this once.
6500 */
6501 bdrv_refresh_filename(bs_below);
6502 filenames_refreshed = true;
6503 }
6504
6505 if (strcmp(backing_file, bs_below->filename) == 0) {
6506 retval = bs_below;
6507 break;
6508 }
6509 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6510 /*
6511 * If either of the filename paths is actually a protocol, then
6512 * compare unmodified paths; otherwise make paths relative.
6513 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006514 char *backing_file_full_ret;
6515
Jeff Codyb1b1d782012-10-16 15:49:09 -04006516 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006517 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006518 break;
6519 }
Jeff Cody418661e2017-01-25 20:08:20 -05006520 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006521 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6522 NULL);
6523 if (backing_file_full_ret) {
6524 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6525 g_free(backing_file_full_ret);
6526 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006527 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006528 break;
6529 }
Jeff Cody418661e2017-01-25 20:08:20 -05006530 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006531 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006532 /* If not an absolute filename path, make it relative to the current
6533 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006534 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6535 NULL);
6536 /* We are going to compare canonicalized absolute pathnames */
6537 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6538 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006539 continue;
6540 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006541 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006542
6543 /* We need to make sure the backing filename we are comparing against
6544 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006545 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6546 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6547 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006548 continue;
6549 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006550 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006551
6552 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006553 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006554 break;
6555 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006556 }
6557 }
6558
Jeff Codyb1b1d782012-10-16 15:49:09 -04006559 g_free(filename_full);
6560 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006561 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006562}
6563
bellardea2384d2004-08-01 21:59:26 +00006564void bdrv_init(void)
6565{
Kevin Wolfe5f05f82021-07-09 18:41:41 +02006566#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6567 use_bdrv_whitelist = 1;
6568#endif
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006569 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006570}
pbrookce1a14d2006-08-07 02:38:06 +00006571
Markus Armbrustereb852012009-10-27 18:41:44 +01006572void bdrv_init_with_whitelist(void)
6573{
6574 use_bdrv_whitelist = 1;
6575 bdrv_init();
6576}
6577
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006578int bdrv_activate(BlockDriverState *bs, Error **errp)
6579{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006580 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006581 Error *local_err = NULL;
6582 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006583 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006584
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006585 GLOBAL_STATE_CODE();
6586
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006587 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006588 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006589 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006590
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006591 QLIST_FOREACH(child, &bs->children, next) {
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006592 bdrv_activate(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006593 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006594 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006595 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006596 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006597 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006598
Kevin Wolfdafe0962017-11-16 13:00:01 +01006599 /*
6600 * Update permissions, they may differ for inactive nodes.
6601 *
6602 * Note that the required permissions of inactive images are always a
6603 * subset of the permissions required after activating the image. This
6604 * allows us to just get the permissions upfront without restricting
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006605 * bdrv_co_invalidate_cache().
Kevin Wolfdafe0962017-11-16 13:00:01 +01006606 *
6607 * It also means that in error cases, we don't have to try and revert to
6608 * the old permissions (which is an operation that could fail, too). We can
6609 * just keep the extended permissions for the next time that an activation
6610 * of the image is tried.
6611 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006612 if (bs->open_flags & BDRV_O_INACTIVE) {
6613 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03006614 ret = bdrv_refresh_perms(bs, NULL, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006615 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006616 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006617 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006618 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006619
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006620 ret = bdrv_invalidate_cache(bs, errp);
6621 if (ret < 0) {
6622 bs->open_flags |= BDRV_O_INACTIVE;
6623 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006624 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006625
Kevin Wolf7bb49412019-12-17 15:06:38 +01006626 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6627 bdrv_dirty_bitmap_skip_store(bm, false);
6628 }
6629
6630 ret = refresh_total_sectors(bs, bs->total_sectors);
6631 if (ret < 0) {
6632 bs->open_flags |= BDRV_O_INACTIVE;
6633 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006634 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006635 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006636 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006637
6638 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006639 if (parent->klass->activate) {
6640 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006641 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006642 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006643 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006644 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006645 }
6646 }
6647 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006648
6649 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006650}
6651
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006652int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6653{
6654 Error *local_err = NULL;
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05006655 IO_CODE();
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006656
6657 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6658
6659 if (bs->drv->bdrv_co_invalidate_cache) {
6660 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6661 if (local_err) {
6662 error_propagate(errp, local_err);
6663 return -EINVAL;
6664 }
6665 }
6666
6667 return 0;
6668}
6669
Emanuele Giuseppe Esposito3b717192022-02-09 05:54:51 -05006670void bdrv_activate_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006671{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006672 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006673 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006674
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006675 GLOBAL_STATE_CODE();
6676
Kevin Wolf88be7b42016-05-20 18:49:07 +02006677 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006678 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006679 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006680
6681 aio_context_acquire(aio_context);
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006682 ret = bdrv_activate(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006683 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006684 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006685 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006686 return;
6687 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006688 }
6689}
6690
Kevin Wolf9e372712018-11-23 15:11:14 +01006691static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6692{
6693 BdrvChild *parent;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006694 GLOBAL_STATE_CODE();
Kevin Wolf9e372712018-11-23 15:11:14 +01006695
6696 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006697 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006698 BlockDriverState *parent_bs = parent->opaque;
6699 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6700 return true;
6701 }
6702 }
6703 }
6704
6705 return false;
6706}
6707
6708static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006709{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006710 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006711 int ret;
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006712 uint64_t cumulative_perms, cumulative_shared_perms;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006713
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05006714 GLOBAL_STATE_CODE();
6715
Max Reitzd470ad42017-11-10 21:31:09 +01006716 if (!bs->drv) {
6717 return -ENOMEDIUM;
6718 }
6719
Kevin Wolf9e372712018-11-23 15:11:14 +01006720 /* Make sure that we don't inactivate a child before its parent.
6721 * It will be covered by recursion from the yet active parent. */
6722 if (bdrv_has_bds_parent(bs, true)) {
6723 return 0;
6724 }
6725
6726 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6727
6728 /* Inactivate this node */
6729 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006730 ret = bs->drv->bdrv_inactivate(bs);
6731 if (ret < 0) {
6732 return ret;
6733 }
6734 }
6735
Kevin Wolf9e372712018-11-23 15:11:14 +01006736 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006737 if (parent->klass->inactivate) {
6738 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006739 if (ret < 0) {
6740 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006741 }
6742 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006743 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006744
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006745 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6746 &cumulative_shared_perms);
6747 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6748 /* Our inactive parents still need write access. Inactivation failed. */
6749 return -EPERM;
6750 }
6751
Kevin Wolf9e372712018-11-23 15:11:14 +01006752 bs->open_flags |= BDRV_O_INACTIVE;
6753
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006754 /*
6755 * Update permissions, they may differ for inactive nodes.
6756 * We only tried to loosen restrictions, so errors are not fatal, ignore
6757 * them.
6758 */
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03006759 bdrv_refresh_perms(bs, NULL, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006760
6761 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006762 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006763 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006764 if (ret < 0) {
6765 return ret;
6766 }
6767 }
6768
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006769 return 0;
6770}
6771
6772int bdrv_inactivate_all(void)
6773{
Max Reitz79720af2016-03-16 19:54:44 +01006774 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006775 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006776 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006777 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006778
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006779 GLOBAL_STATE_CODE();
6780
Kevin Wolf88be7b42016-05-20 18:49:07 +02006781 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006782 AioContext *aio_context = bdrv_get_aio_context(bs);
6783
6784 if (!g_slist_find(aio_ctxs, aio_context)) {
6785 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6786 aio_context_acquire(aio_context);
6787 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006788 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006789
Kevin Wolf9e372712018-11-23 15:11:14 +01006790 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6791 /* Nodes with BDS parents are covered by recursion from the last
6792 * parent that gets inactivated. Don't inactivate them a second
6793 * time if that has already happened. */
6794 if (bdrv_has_bds_parent(bs, false)) {
6795 continue;
6796 }
6797 ret = bdrv_inactivate_recurse(bs);
6798 if (ret < 0) {
6799 bdrv_next_cleanup(&it);
6800 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006801 }
6802 }
6803
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006804out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006805 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6806 AioContext *aio_context = ctx->data;
6807 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006808 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006809 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006810
6811 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006812}
6813
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006814/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006815/* removable device support */
6816
6817/**
6818 * Return TRUE if the media is present
6819 */
Max Reitze031f752015-10-19 17:53:11 +02006820bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006821{
6822 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006823 BdrvChild *child;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006824 IO_CODE();
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006825
Max Reitze031f752015-10-19 17:53:11 +02006826 if (!drv) {
6827 return false;
6828 }
Max Reitz28d7a782015-10-19 17:53:13 +02006829 if (drv->bdrv_is_inserted) {
6830 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006831 }
Max Reitz28d7a782015-10-19 17:53:13 +02006832 QLIST_FOREACH(child, &bs->children, next) {
6833 if (!bdrv_is_inserted(child->bs)) {
6834 return false;
6835 }
6836 }
6837 return true;
bellard19cb3732006-08-19 11:45:59 +00006838}
6839
6840/**
bellard19cb3732006-08-19 11:45:59 +00006841 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6842 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006843void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006844{
6845 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006846 IO_CODE();
bellard19cb3732006-08-19 11:45:59 +00006847
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006848 if (drv && drv->bdrv_eject) {
6849 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006850 }
bellard19cb3732006-08-19 11:45:59 +00006851}
6852
bellard19cb3732006-08-19 11:45:59 +00006853/**
6854 * Lock or unlock the media (if it is locked, the user won't be able
6855 * to eject it manually).
6856 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006857void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006858{
6859 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006860 IO_CODE();
Markus Armbruster025e8492011-09-06 18:58:47 +02006861 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006862
Markus Armbruster025e8492011-09-06 18:58:47 +02006863 if (drv && drv->bdrv_lock_medium) {
6864 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006865 }
6866}
ths985a03b2007-12-24 16:10:43 +00006867
Fam Zheng9fcb0252013-08-23 09:14:46 +08006868/* Get a reference to bs */
6869void bdrv_ref(BlockDriverState *bs)
6870{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006871 GLOBAL_STATE_CODE();
Fam Zheng9fcb0252013-08-23 09:14:46 +08006872 bs->refcnt++;
6873}
6874
6875/* Release a previously grabbed reference to bs.
6876 * If after releasing, reference count is zero, the BlockDriverState is
6877 * deleted. */
6878void bdrv_unref(BlockDriverState *bs)
6879{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006880 GLOBAL_STATE_CODE();
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006881 if (!bs) {
6882 return;
6883 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006884 assert(bs->refcnt > 0);
6885 if (--bs->refcnt == 0) {
6886 bdrv_delete(bs);
6887 }
6888}
6889
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006890struct BdrvOpBlocker {
6891 Error *reason;
6892 QLIST_ENTRY(BdrvOpBlocker) list;
6893};
6894
6895bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6896{
6897 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006898 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006899 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6900 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6901 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006902 error_propagate_prepend(errp, error_copy(blocker->reason),
6903 "Node '%s' is busy: ",
6904 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006905 return true;
6906 }
6907 return false;
6908}
6909
6910void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6911{
6912 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006913 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006914 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6915
Markus Armbruster5839e532014-08-19 10:31:08 +02006916 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006917 blocker->reason = reason;
6918 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6919}
6920
6921void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6922{
6923 BdrvOpBlocker *blocker, *next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006924 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006925 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6926 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6927 if (blocker->reason == reason) {
6928 QLIST_REMOVE(blocker, list);
6929 g_free(blocker);
6930 }
6931 }
6932}
6933
6934void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6935{
6936 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006937 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006938 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6939 bdrv_op_block(bs, i, reason);
6940 }
6941}
6942
6943void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6944{
6945 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006946 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006947 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6948 bdrv_op_unblock(bs, i, reason);
6949 }
6950}
6951
6952bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6953{
6954 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006955 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006956 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6957 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6958 return false;
6959 }
6960 }
6961 return true;
6962}
6963
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006964void bdrv_img_create(const char *filename, const char *fmt,
6965 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006966 char *options, uint64_t img_size, int flags, bool quiet,
6967 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006968{
Chunyan Liu83d05212014-06-05 17:20:51 +08006969 QemuOptsList *create_opts = NULL;
6970 QemuOpts *opts = NULL;
6971 const char *backing_fmt, *backing_file;
6972 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006973 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006974 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006975 int ret = 0;
6976
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006977 GLOBAL_STATE_CODE();
6978
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006979 /* Find driver and parse its options */
6980 drv = bdrv_find_format(fmt);
6981 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006982 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006983 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006984 }
6985
Max Reitzb65a5e12015-02-05 13:58:12 -05006986 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006987 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006988 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006989 }
6990
Max Reitzc6149722014-12-02 18:32:45 +01006991 if (!drv->create_opts) {
6992 error_setg(errp, "Format driver '%s' does not support image creation",
6993 drv->format_name);
6994 return;
6995 }
6996
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006997 if (!proto_drv->create_opts) {
6998 error_setg(errp, "Protocol driver '%s' does not support image creation",
6999 proto_drv->format_name);
7000 return;
7001 }
7002
Kevin Wolff6dc1c32019-11-26 16:45:49 +01007003 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007004 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02007005 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007006
Chunyan Liu83d05212014-06-05 17:20:51 +08007007 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007008
7009 /* Parse -o options */
7010 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02007011 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007012 goto out;
7013 }
7014 }
7015
Kevin Wolff6dc1c32019-11-26 16:45:49 +01007016 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7017 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7018 } else if (img_size != UINT64_C(-1)) {
7019 error_setg(errp, "The image size must be specified only once");
7020 goto out;
7021 }
7022
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007023 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02007024 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02007025 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02007026 error_setg(errp, "Backing file not supported for file format '%s'",
7027 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007028 goto out;
7029 }
7030 }
7031
7032 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02007033 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02007034 error_setg(errp, "Backing file format not supported for file "
7035 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007036 goto out;
7037 }
7038 }
7039
Chunyan Liu83d05212014-06-05 17:20:51 +08007040 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
7041 if (backing_file) {
7042 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02007043 error_setg(errp, "Error: Trying to create an image with the "
7044 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01007045 goto out;
7046 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05007047 if (backing_file[0] == '\0') {
7048 error_setg(errp, "Expected backing file name, got empty string");
7049 goto out;
7050 }
Jes Sorensen792da932010-12-16 13:52:17 +01007051 }
7052
Chunyan Liu83d05212014-06-05 17:20:51 +08007053 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007054
John Snow6e6e55f2017-07-17 20:34:22 -04007055 /* The size for the image must always be specified, unless we have a backing
7056 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05007057 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04007058 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
7059 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01007060 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04007061 int back_flags;
7062 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02007063
Max Reitz645ae7d2019-02-01 20:29:14 +01007064 full_backing =
7065 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7066 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04007067 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007068 goto out;
7069 }
Max Reitz645ae7d2019-02-01 20:29:14 +01007070 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04007071
Max Reitzd5b23992021-06-22 16:00:30 +02007072 /*
7073 * No need to do I/O here, which allows us to open encrypted
7074 * backing images without needing the secret
7075 */
John Snow6e6e55f2017-07-17 20:34:22 -04007076 back_flags = flags;
7077 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02007078 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04007079
Fam Zhengcc954f02017-12-15 16:04:45 +08007080 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04007081 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04007082 qdict_put_str(backing_options, "driver", backing_fmt);
7083 }
Fam Zhengcc954f02017-12-15 16:04:45 +08007084 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04007085
7086 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7087 &local_err);
7088 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05007089 if (!bs) {
7090 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04007091 goto out;
7092 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05007093 if (!backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007094 error_setg(&local_err,
7095 "Backing file specified without backing format");
7096 error_append_hint(&local_err, "Detected format of %s.",
7097 bs->drv->format_name);
7098 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007099 }
John Snow6e6e55f2017-07-17 20:34:22 -04007100 if (size == -1) {
7101 /* Opened BS, have no size */
7102 size = bdrv_getlength(bs);
7103 if (size < 0) {
7104 error_setg_errno(errp, -size, "Could not get size of '%s'",
7105 backing_file);
7106 bdrv_unref(bs);
7107 goto out;
7108 }
7109 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7110 }
7111 bdrv_unref(bs);
7112 }
Eric Blaked9f059a2020-07-06 15:39:54 -05007113 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7114 } else if (backing_file && !backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007115 error_setg(&local_err,
7116 "Backing file specified without backing format");
7117 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007118 }
John Snow6e6e55f2017-07-17 20:34:22 -04007119
7120 if (size == -1) {
7121 error_setg(errp, "Image creation needs a size parameter");
7122 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007123 }
7124
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007125 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02007126 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08007127 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007128 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05007129 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007130 }
Chunyan Liu83d05212014-06-05 17:20:51 +08007131
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007132 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08007133
Max Reitzcc84d902013-09-06 17:14:26 +02007134 if (ret == -EFBIG) {
7135 /* This is generally a better message than whatever the driver would
7136 * deliver (especially because of the cluster_size_hint), since that
7137 * is most probably not much different from "image too large". */
7138 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08007139 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02007140 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007141 }
Max Reitzcc84d902013-09-06 17:14:26 +02007142 error_setg(errp, "The image size is too large for file format '%s'"
7143 "%s", fmt, cluster_size_hint);
7144 error_free(local_err);
7145 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007146 }
7147
7148out:
Chunyan Liu83d05212014-06-05 17:20:51 +08007149 qemu_opts_del(opts);
7150 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03007151 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007152}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007153
7154AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7155{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007156 IO_CODE();
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00007157 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007158}
7159
Kevin Wolfe336fd42020-10-05 17:58:53 +02007160AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7161{
7162 Coroutine *self = qemu_coroutine_self();
7163 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7164 AioContext *new_ctx;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007165 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007166
7167 /*
7168 * Increase bs->in_flight to ensure that this operation is completed before
7169 * moving the node to a different AioContext. Read new_ctx only afterwards.
7170 */
7171 bdrv_inc_in_flight(bs);
7172
7173 new_ctx = bdrv_get_aio_context(bs);
7174 aio_co_reschedule_self(new_ctx);
7175 return old_ctx;
7176}
7177
7178void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7179{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007180 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007181 aio_co_reschedule_self(old_ctx);
7182 bdrv_dec_in_flight(bs);
7183}
7184
Kevin Wolf18c6ac12020-10-05 17:58:54 +02007185void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7186{
7187 AioContext *ctx = bdrv_get_aio_context(bs);
7188
7189 /* In the main thread, bs->aio_context won't change concurrently */
7190 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7191
7192 /*
7193 * We're in coroutine context, so we already hold the lock of the main
7194 * loop AioContext. Don't lock it twice to avoid deadlocks.
7195 */
7196 assert(qemu_in_coroutine());
7197 if (ctx != qemu_get_aio_context()) {
7198 aio_context_acquire(ctx);
7199 }
7200}
7201
7202void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7203{
7204 AioContext *ctx = bdrv_get_aio_context(bs);
7205
7206 assert(qemu_in_coroutine());
7207 if (ctx != qemu_get_aio_context()) {
7208 aio_context_release(ctx);
7209 }
7210}
7211
Fam Zheng052a7572017-04-10 20:09:25 +08007212void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7213{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007214 IO_CODE();
Fam Zheng052a7572017-04-10 20:09:25 +08007215 aio_co_enter(bdrv_get_aio_context(bs), co);
7216}
7217
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007218static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7219{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05007220 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007221 QLIST_REMOVE(ban, list);
7222 g_free(ban);
7223}
7224
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007225static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007226{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007227 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007228
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007229 assert(!bs->walking_aio_notifiers);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007230 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007231 bs->walking_aio_notifiers = true;
7232 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7233 if (baf->deleted) {
7234 bdrv_do_remove_aio_context_notifier(baf);
7235 } else {
7236 baf->detach_aio_context(baf->opaque);
7237 }
Max Reitz33384422014-06-20 21:57:33 +02007238 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007239 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7240 * remove remaining aio notifiers if we aren't called again.
7241 */
7242 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02007243
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007244 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007245 bs->drv->bdrv_detach_aio_context(bs);
7246 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007247
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007248 if (bs->quiesce_counter) {
7249 aio_enable_external(bs->aio_context);
7250 }
Emanuele Giuseppe Esposito7f898612022-10-25 04:49:43 -04007251 assert_bdrv_graph_writable(bs);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007252 bs->aio_context = NULL;
7253}
7254
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007255static void bdrv_attach_aio_context(BlockDriverState *bs,
7256 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007257{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007258 BdrvAioNotifier *ban, *ban_tmp;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007259 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007260
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007261 if (bs->quiesce_counter) {
7262 aio_disable_external(new_context);
7263 }
7264
Emanuele Giuseppe Esposito7f898612022-10-25 04:49:43 -04007265 assert_bdrv_graph_writable(bs);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007266 bs->aio_context = new_context;
7267
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007268 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007269 bs->drv->bdrv_attach_aio_context(bs, new_context);
7270 }
Max Reitz33384422014-06-20 21:57:33 +02007271
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007272 assert(!bs->walking_aio_notifiers);
7273 bs->walking_aio_notifiers = true;
7274 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7275 if (ban->deleted) {
7276 bdrv_do_remove_aio_context_notifier(ban);
7277 } else {
7278 ban->attached_aio_context(new_context, ban->opaque);
7279 }
Max Reitz33384422014-06-20 21:57:33 +02007280 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007281 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007282}
7283
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007284typedef struct BdrvStateSetAioContext {
7285 AioContext *new_ctx;
7286 BlockDriverState *bs;
7287} BdrvStateSetAioContext;
7288
7289static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007290 GHashTable *visited,
7291 Transaction *tran,
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007292 Error **errp)
7293{
7294 GLOBAL_STATE_CODE();
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007295 if (g_hash_table_contains(visited, c)) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007296 return true;
7297 }
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007298 g_hash_table_add(visited, c);
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007299
7300 /*
7301 * A BdrvChildClass that doesn't handle AioContext changes cannot
7302 * tolerate any AioContext changes
7303 */
7304 if (!c->klass->change_aio_ctx) {
7305 char *user = bdrv_child_user_desc(c);
7306 error_setg(errp, "Changing iothreads is not supported by %s", user);
7307 g_free(user);
7308 return false;
7309 }
7310 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7311 assert(!errp || *errp);
7312 return false;
7313 }
7314 return true;
7315}
7316
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007317bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007318 GHashTable *visited, Transaction *tran,
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007319 Error **errp)
7320{
7321 GLOBAL_STATE_CODE();
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007322 if (g_hash_table_contains(visited, c)) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007323 return true;
7324 }
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007325 g_hash_table_add(visited, c);
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007326 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7327}
7328
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007329static void bdrv_set_aio_context_clean(void *opaque)
7330{
7331 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7332 BlockDriverState *bs = (BlockDriverState *) state->bs;
7333
7334 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7335 bdrv_drained_end(bs);
7336
7337 g_free(state);
7338}
7339
7340static void bdrv_set_aio_context_commit(void *opaque)
7341{
7342 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7343 BlockDriverState *bs = (BlockDriverState *) state->bs;
7344 AioContext *new_context = state->new_ctx;
7345 AioContext *old_context = bdrv_get_aio_context(bs);
7346 assert_bdrv_graph_writable(bs);
7347
7348 /*
7349 * Take the old AioContex when detaching it from bs.
7350 * At this point, new_context lock is already acquired, and we are now
7351 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7352 * does not call AIO_POLL_WHILE().
7353 */
7354 if (old_context != qemu_get_aio_context()) {
7355 aio_context_acquire(old_context);
7356 }
7357 bdrv_detach_aio_context(bs);
7358 if (old_context != qemu_get_aio_context()) {
7359 aio_context_release(old_context);
7360 }
7361 bdrv_attach_aio_context(bs, new_context);
7362}
7363
7364static TransactionActionDrv set_aio_context = {
7365 .commit = bdrv_set_aio_context_commit,
7366 .clean = bdrv_set_aio_context_clean,
7367};
7368
Kevin Wolf42a65f02019-05-07 18:31:38 +02007369/*
7370 * Changes the AioContext used for fd handlers, timers, and BHs by this
7371 * BlockDriverState and all its children and parents.
7372 *
Max Reitz43eaaae2019-07-22 15:30:54 +02007373 * Must be called from the main AioContext.
7374 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02007375 * The caller must own the AioContext lock for the old AioContext of bs, but it
7376 * must not own the AioContext lock for new_context (unless new_context is the
7377 * same as the current context of bs).
7378 *
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007379 * @visited will accumulate all visited BdrvChild objects. The caller is
Kevin Wolf42a65f02019-05-07 18:31:38 +02007380 * responsible for freeing the list afterwards.
7381 */
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007382static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007383 GHashTable *visited, Transaction *tran,
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007384 Error **errp)
Kevin Wolf5d231842019-05-06 19:17:56 +02007385{
7386 BdrvChild *c;
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007387 BdrvStateSetAioContext *state;
7388
7389 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007390
7391 if (bdrv_get_aio_context(bs) == ctx) {
7392 return true;
7393 }
7394
7395 QLIST_FOREACH(c, &bs->parents, next_parent) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007396 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007397 return false;
7398 }
7399 }
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007400
Kevin Wolf5d231842019-05-06 19:17:56 +02007401 QLIST_FOREACH(c, &bs->children, next) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007402 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007403 return false;
7404 }
7405 }
7406
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007407 state = g_new(BdrvStateSetAioContext, 1);
7408 *state = (BdrvStateSetAioContext) {
7409 .new_ctx = ctx,
7410 .bs = bs,
7411 };
7412
7413 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7414 bdrv_drained_begin(bs);
7415
7416 tran_add(tran, &set_aio_context, state);
7417
Kevin Wolf5d231842019-05-06 19:17:56 +02007418 return true;
7419}
7420
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007421/*
7422 * Change bs's and recursively all of its parents' and children's AioContext
7423 * to the given new context, returning an error if that isn't possible.
7424 *
7425 * If ignore_child is not NULL, that child (and its subgraph) will not
7426 * be touched.
7427 *
7428 * This function still requires the caller to take the bs current
7429 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7430 * assumes the lock is always held if bs is in another AioContext.
7431 * For the same reason, it temporarily also holds the new AioContext, since
7432 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7433 * Therefore the new AioContext lock must not be taken by the caller.
7434 */
Emanuele Giuseppe Espositoa41cfda2022-10-25 04:49:51 -04007435int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7436 BdrvChild *ignore_child, Error **errp)
Kevin Wolf5d231842019-05-06 19:17:56 +02007437{
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007438 Transaction *tran;
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007439 GHashTable *visited;
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007440 int ret;
7441 AioContext *old_context = bdrv_get_aio_context(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007442 GLOBAL_STATE_CODE();
7443
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007444 /*
7445 * Recursion phase: go through all nodes of the graph.
7446 * Take care of checking that all nodes support changing AioContext
7447 * and drain them, builing a linear list of callbacks to run if everything
7448 * is successful (the transaction itself).
7449 */
7450 tran = tran_new();
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007451 visited = g_hash_table_new(NULL, NULL);
7452 if (ignore_child) {
7453 g_hash_table_add(visited, ignore_child);
7454 }
7455 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7456 g_hash_table_destroy(visited);
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007457
7458 /*
7459 * Linear phase: go through all callbacks collected in the transaction.
7460 * Run all callbacks collected in the recursion to switch all nodes
7461 * AioContext lock (transaction commit), or undo all changes done in the
7462 * recursion (transaction abort).
7463 */
Kevin Wolf5d231842019-05-06 19:17:56 +02007464
7465 if (!ret) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007466 /* Just run clean() callbacks. No AioContext changed. */
7467 tran_abort(tran);
Kevin Wolf5d231842019-05-06 19:17:56 +02007468 return -EPERM;
7469 }
7470
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007471 /*
7472 * Release old AioContext, it won't be needed anymore, as all
7473 * bdrv_drained_begin() have been called already.
7474 */
7475 if (qemu_get_aio_context() != old_context) {
7476 aio_context_release(old_context);
7477 }
7478
7479 /*
7480 * Acquire new AioContext since bdrv_drained_end() is going to be called
7481 * after we switched all nodes in the new AioContext, and the function
7482 * assumes that the lock of the bs is always taken.
7483 */
7484 if (qemu_get_aio_context() != ctx) {
7485 aio_context_acquire(ctx);
7486 }
7487
7488 tran_commit(tran);
7489
7490 if (qemu_get_aio_context() != ctx) {
7491 aio_context_release(ctx);
7492 }
7493
7494 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7495 if (qemu_get_aio_context() != old_context) {
7496 aio_context_acquire(old_context);
7497 }
Kevin Wolf53a7d042019-05-06 19:17:59 +02007498
Kevin Wolf5d231842019-05-06 19:17:56 +02007499 return 0;
7500}
7501
Max Reitz33384422014-06-20 21:57:33 +02007502void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7503 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7504 void (*detach_aio_context)(void *opaque), void *opaque)
7505{
7506 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7507 *ban = (BdrvAioNotifier){
7508 .attached_aio_context = attached_aio_context,
7509 .detach_aio_context = detach_aio_context,
7510 .opaque = opaque
7511 };
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007512 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007513
7514 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7515}
7516
7517void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7518 void (*attached_aio_context)(AioContext *,
7519 void *),
7520 void (*detach_aio_context)(void *),
7521 void *opaque)
7522{
7523 BdrvAioNotifier *ban, *ban_next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007524 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007525
7526 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7527 if (ban->attached_aio_context == attached_aio_context &&
7528 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007529 ban->opaque == opaque &&
7530 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007531 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007532 if (bs->walking_aio_notifiers) {
7533 ban->deleted = true;
7534 } else {
7535 bdrv_do_remove_aio_context_notifier(ban);
7536 }
Max Reitz33384422014-06-20 21:57:33 +02007537 return;
7538 }
7539 }
7540
7541 abort();
7542}
7543
Max Reitz77485432014-10-27 11:12:50 +01007544int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007545 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007546 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007547 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007548{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007549 GLOBAL_STATE_CODE();
Max Reitzd470ad42017-11-10 21:31:09 +01007550 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007551 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007552 return -ENOMEDIUM;
7553 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007554 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007555 error_setg(errp, "Block driver '%s' does not support option amendment",
7556 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007557 return -ENOTSUP;
7558 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007559 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7560 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007561}
Benoît Canetf6186f42013-10-02 14:33:48 +02007562
Max Reitz5d69b5a2020-02-18 11:34:41 +01007563/*
7564 * This function checks whether the given @to_replace is allowed to be
7565 * replaced by a node that always shows the same data as @bs. This is
7566 * used for example to verify whether the mirror job can replace
7567 * @to_replace by the target mirrored from @bs.
7568 * To be replaceable, @bs and @to_replace may either be guaranteed to
7569 * always show the same data (because they are only connected through
7570 * filters), or some driver may allow replacing one of its children
7571 * because it can guarantee that this child's data is not visible at
7572 * all (for example, for dissenting quorum children that have no other
7573 * parents).
7574 */
7575bool bdrv_recurse_can_replace(BlockDriverState *bs,
7576 BlockDriverState *to_replace)
7577{
Max Reitz93393e62019-06-12 17:03:38 +02007578 BlockDriverState *filtered;
7579
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007580 GLOBAL_STATE_CODE();
7581
Max Reitz5d69b5a2020-02-18 11:34:41 +01007582 if (!bs || !bs->drv) {
7583 return false;
7584 }
7585
7586 if (bs == to_replace) {
7587 return true;
7588 }
7589
7590 /* See what the driver can do */
7591 if (bs->drv->bdrv_recurse_can_replace) {
7592 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7593 }
7594
7595 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007596 filtered = bdrv_filter_bs(bs);
7597 if (filtered) {
7598 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007599 }
7600
7601 /* Safe default */
7602 return false;
7603}
7604
Max Reitz810803a2020-02-18 11:34:44 +01007605/*
7606 * Check whether the given @node_name can be replaced by a node that
7607 * has the same data as @parent_bs. If so, return @node_name's BDS;
7608 * NULL otherwise.
7609 *
7610 * @node_name must be a (recursive) *child of @parent_bs (or this
7611 * function will return NULL).
7612 *
7613 * The result (whether the node can be replaced or not) is only valid
7614 * for as long as no graph or permission changes occur.
7615 */
Wen Congyange12f3782015-07-17 10:12:22 +08007616BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7617 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007618{
7619 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007620 AioContext *aio_context;
7621
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007622 GLOBAL_STATE_CODE();
7623
Benoît Canet09158f02014-06-27 18:25:25 +02007624 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007625 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007626 return NULL;
7627 }
7628
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007629 aio_context = bdrv_get_aio_context(to_replace_bs);
7630 aio_context_acquire(aio_context);
7631
Benoît Canet09158f02014-06-27 18:25:25 +02007632 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007633 to_replace_bs = NULL;
7634 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007635 }
7636
7637 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7638 * most non filter in order to prevent data corruption.
7639 * Another benefit is that this tests exclude backing files which are
7640 * blocked by the backing blockers.
7641 */
Max Reitz810803a2020-02-18 11:34:44 +01007642 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7643 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7644 "because it cannot be guaranteed that doing so would not "
7645 "lead to an abrupt change of visible data",
7646 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007647 to_replace_bs = NULL;
7648 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007649 }
7650
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007651out:
7652 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007653 return to_replace_bs;
7654}
Ming Lei448ad912014-07-04 18:04:33 +08007655
Max Reitz97e2f022019-02-01 20:29:27 +01007656/**
7657 * Iterates through the list of runtime option keys that are said to
7658 * be "strong" for a BDS. An option is called "strong" if it changes
7659 * a BDS's data. For example, the null block driver's "size" and
7660 * "read-zeroes" options are strong, but its "latency-ns" option is
7661 * not.
7662 *
7663 * If a key returned by this function ends with a dot, all options
7664 * starting with that prefix are strong.
7665 */
7666static const char *const *strong_options(BlockDriverState *bs,
7667 const char *const *curopt)
7668{
7669 static const char *const global_options[] = {
7670 "driver", "filename", NULL
7671 };
7672
7673 if (!curopt) {
7674 return &global_options[0];
7675 }
7676
7677 curopt++;
7678 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7679 curopt = bs->drv->strong_runtime_opts;
7680 }
7681
7682 return (curopt && *curopt) ? curopt : NULL;
7683}
7684
7685/**
7686 * Copies all strong runtime options from bs->options to the given
7687 * QDict. The set of strong option keys is determined by invoking
7688 * strong_options().
7689 *
7690 * Returns true iff any strong option was present in bs->options (and
7691 * thus copied to the target QDict) with the exception of "filename"
7692 * and "driver". The caller is expected to use this value to decide
7693 * whether the existence of strong options prevents the generation of
7694 * a plain filename.
7695 */
7696static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7697{
7698 bool found_any = false;
7699 const char *const *option_name = NULL;
7700
7701 if (!bs->drv) {
7702 return false;
7703 }
7704
7705 while ((option_name = strong_options(bs, option_name))) {
7706 bool option_given = false;
7707
7708 assert(strlen(*option_name) > 0);
7709 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7710 QObject *entry = qdict_get(bs->options, *option_name);
7711 if (!entry) {
7712 continue;
7713 }
7714
7715 qdict_put_obj(d, *option_name, qobject_ref(entry));
7716 option_given = true;
7717 } else {
7718 const QDictEntry *entry;
7719 for (entry = qdict_first(bs->options); entry;
7720 entry = qdict_next(bs->options, entry))
7721 {
7722 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7723 qdict_put_obj(d, qdict_entry_key(entry),
7724 qobject_ref(qdict_entry_value(entry)));
7725 option_given = true;
7726 }
7727 }
7728 }
7729
7730 /* While "driver" and "filename" need to be included in a JSON filename,
7731 * their existence does not prohibit generation of a plain filename. */
7732 if (!found_any && option_given &&
7733 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7734 {
7735 found_any = true;
7736 }
7737 }
7738
Max Reitz62a01a272019-02-01 20:29:34 +01007739 if (!qdict_haskey(d, "driver")) {
7740 /* Drivers created with bdrv_new_open_driver() may not have a
7741 * @driver option. Add it here. */
7742 qdict_put_str(d, "driver", bs->drv->format_name);
7743 }
7744
Max Reitz97e2f022019-02-01 20:29:27 +01007745 return found_any;
7746}
7747
Max Reitz90993622019-02-01 20:29:09 +01007748/* Note: This function may return false positives; it may return true
7749 * even if opening the backing file specified by bs's image header
7750 * would result in exactly bs->backing. */
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -05007751static bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007752{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007753 GLOBAL_STATE_CODE();
Max Reitz90993622019-02-01 20:29:09 +01007754 if (bs->backing) {
7755 return strcmp(bs->auto_backing_file,
7756 bs->backing->bs->filename);
7757 } else {
7758 /* No backing BDS, so if the image header reports any backing
7759 * file, it must have been suppressed */
7760 return bs->auto_backing_file[0] != '\0';
7761 }
7762}
7763
Max Reitz91af7012014-07-18 20:24:56 +02007764/* Updates the following BDS fields:
7765 * - exact_filename: A filename which may be used for opening a block device
7766 * which (mostly) equals the given BDS (even without any
7767 * other options; so reading and writing must return the same
7768 * results, but caching etc. may be different)
7769 * - full_open_options: Options which, when given when opening a block device
7770 * (without a filename), result in a BDS (mostly)
7771 * equalling the given one
7772 * - filename: If exact_filename is set, it is copied here. Otherwise,
7773 * full_open_options is converted to a JSON object, prefixed with
7774 * "json:" (for use through the JSON pseudo protocol) and put here.
7775 */
7776void bdrv_refresh_filename(BlockDriverState *bs)
7777{
7778 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007779 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007780 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007781 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007782 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007783 bool generate_json_filename; /* Whether our default implementation should
7784 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007785
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007786 GLOBAL_STATE_CODE();
7787
Max Reitz91af7012014-07-18 20:24:56 +02007788 if (!drv) {
7789 return;
7790 }
7791
Max Reitze24518e2019-02-01 20:29:06 +01007792 /* This BDS's file name may depend on any of its children's file names, so
7793 * refresh those first */
7794 QLIST_FOREACH(child, &bs->children, next) {
7795 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007796 }
7797
Max Reitzbb808d52019-02-01 20:29:07 +01007798 if (bs->implicit) {
7799 /* For implicit nodes, just copy everything from the single child */
7800 child = QLIST_FIRST(&bs->children);
7801 assert(QLIST_NEXT(child, next) == NULL);
7802
7803 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7804 child->bs->exact_filename);
7805 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7806
Pan Nengyuancb895612020-01-16 16:56:00 +08007807 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007808 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7809
7810 return;
7811 }
7812
Max Reitz90993622019-02-01 20:29:09 +01007813 backing_overridden = bdrv_backing_overridden(bs);
7814
7815 if (bs->open_flags & BDRV_O_NO_IO) {
7816 /* Without I/O, the backing file does not change anything.
7817 * Therefore, in such a case (primarily qemu-img), we can
7818 * pretend the backing file has not been overridden even if
7819 * it technically has been. */
7820 backing_overridden = false;
7821 }
7822
Max Reitz97e2f022019-02-01 20:29:27 +01007823 /* Gather the options QDict */
7824 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007825 generate_json_filename = append_strong_runtime_options(opts, bs);
7826 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007827
7828 if (drv->bdrv_gather_child_options) {
7829 /* Some block drivers may not want to present all of their children's
7830 * options, or name them differently from BdrvChild.name */
7831 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7832 } else {
7833 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007834 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007835 /* We can skip the backing BDS if it has not been overridden */
7836 continue;
7837 }
7838
7839 qdict_put(opts, child->name,
7840 qobject_ref(child->bs->full_open_options));
7841 }
7842
7843 if (backing_overridden && !bs->backing) {
7844 /* Force no backing file */
7845 qdict_put_null(opts, "backing");
7846 }
7847 }
7848
7849 qobject_unref(bs->full_open_options);
7850 bs->full_open_options = opts;
7851
Max Reitz52f72d62019-06-12 17:43:03 +02007852 primary_child_bs = bdrv_primary_bs(bs);
7853
Max Reitz998b3a12019-02-01 20:29:28 +01007854 if (drv->bdrv_refresh_filename) {
7855 /* Obsolete information is of no use here, so drop the old file name
7856 * information before refreshing it */
7857 bs->exact_filename[0] = '\0';
7858
7859 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007860 } else if (primary_child_bs) {
7861 /*
7862 * Try to reconstruct valid information from the underlying
7863 * file -- this only works for format nodes (filter nodes
7864 * cannot be probed and as such must be selected by the user
7865 * either through an options dict, or through a special
7866 * filename which the filter driver must construct in its
7867 * .bdrv_refresh_filename() implementation).
7868 */
Max Reitz998b3a12019-02-01 20:29:28 +01007869
7870 bs->exact_filename[0] = '\0';
7871
Max Reitzfb695c72019-02-01 20:29:29 +01007872 /*
7873 * We can use the underlying file's filename if:
7874 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007875 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007876 * - the file is a protocol BDS, and
7877 * - opening that file (as this BDS's format) will automatically create
7878 * the BDS tree we have right now, that is:
7879 * - the user did not significantly change this BDS's behavior with
7880 * some explicit (strong) options
7881 * - no non-file child of this BDS has been overridden by the user
7882 * Both of these conditions are represented by generate_json_filename.
7883 */
Max Reitz52f72d62019-06-12 17:43:03 +02007884 if (primary_child_bs->exact_filename[0] &&
7885 primary_child_bs->drv->bdrv_file_open &&
7886 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007887 {
Max Reitz52f72d62019-06-12 17:43:03 +02007888 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007889 }
7890 }
7891
Max Reitz91af7012014-07-18 20:24:56 +02007892 if (bs->exact_filename[0]) {
7893 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007894 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007895 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007896 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007897 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007898 /* Give user a hint if we truncated things. */
7899 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7900 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007901 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007902 }
7903}
Wen Congyange06018a2016-05-10 15:36:37 +08007904
Max Reitz1e89d0f2019-02-01 20:29:18 +01007905char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7906{
7907 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007908 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007909
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007910 GLOBAL_STATE_CODE();
7911
Max Reitz1e89d0f2019-02-01 20:29:18 +01007912 if (!drv) {
7913 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7914 return NULL;
7915 }
7916
7917 if (drv->bdrv_dirname) {
7918 return drv->bdrv_dirname(bs, errp);
7919 }
7920
Max Reitz52f72d62019-06-12 17:43:03 +02007921 child_bs = bdrv_primary_bs(bs);
7922 if (child_bs) {
7923 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007924 }
7925
7926 bdrv_refresh_filename(bs);
7927 if (bs->exact_filename[0] != '\0') {
7928 return path_combine(bs->exact_filename, "");
7929 }
7930
7931 error_setg(errp, "Cannot generate a base directory for %s nodes",
7932 drv->format_name);
7933 return NULL;
7934}
7935
Wen Congyange06018a2016-05-10 15:36:37 +08007936/*
7937 * Hot add/remove a BDS's child. So the user can take a child offline when
7938 * it is broken and take a new child online
7939 */
7940void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7941 Error **errp)
7942{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007943 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007944 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7945 error_setg(errp, "The node %s does not support adding a child",
7946 bdrv_get_device_or_node_name(parent_bs));
7947 return;
7948 }
7949
7950 if (!QLIST_EMPTY(&child_bs->parents)) {
7951 error_setg(errp, "The node %s already has a parent",
7952 child_bs->node_name);
7953 return;
7954 }
7955
7956 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7957}
7958
7959void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7960{
7961 BdrvChild *tmp;
7962
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007963 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007964 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7965 error_setg(errp, "The node %s does not support removing a child",
7966 bdrv_get_device_or_node_name(parent_bs));
7967 return;
7968 }
7969
7970 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7971 if (tmp == child) {
7972 break;
7973 }
7974 }
7975
7976 if (!tmp) {
7977 error_setg(errp, "The node %s does not have a child named %s",
7978 bdrv_get_device_or_node_name(parent_bs),
7979 bdrv_get_device_or_node_name(child->bs));
7980 return;
7981 }
7982
7983 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7984}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007985
7986int bdrv_make_empty(BdrvChild *c, Error **errp)
7987{
7988 BlockDriver *drv = c->bs->drv;
7989 int ret;
7990
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007991 GLOBAL_STATE_CODE();
Max Reitz6f7a3b52020-04-29 16:11:23 +02007992 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7993
7994 if (!drv->bdrv_make_empty) {
7995 error_setg(errp, "%s does not support emptying nodes",
7996 drv->format_name);
7997 return -ENOTSUP;
7998 }
7999
8000 ret = drv->bdrv_make_empty(c->bs);
8001 if (ret < 0) {
8002 error_setg_errno(errp, -ret, "Failed to empty %s",
8003 c->bs->filename);
8004 return ret;
8005 }
8006
8007 return 0;
8008}
Max Reitz9a6fc882019-05-31 15:23:11 +02008009
8010/*
8011 * Return the child that @bs acts as an overlay for, and from which data may be
8012 * copied in COW or COR operations. Usually this is the backing file.
8013 */
8014BdrvChild *bdrv_cow_child(BlockDriverState *bs)
8015{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008016 IO_CODE();
8017
Max Reitz9a6fc882019-05-31 15:23:11 +02008018 if (!bs || !bs->drv) {
8019 return NULL;
8020 }
8021
8022 if (bs->drv->is_filter) {
8023 return NULL;
8024 }
8025
8026 if (!bs->backing) {
8027 return NULL;
8028 }
8029
8030 assert(bs->backing->role & BDRV_CHILD_COW);
8031 return bs->backing;
8032}
8033
8034/*
8035 * If @bs acts as a filter for exactly one of its children, return
8036 * that child.
8037 */
8038BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8039{
8040 BdrvChild *c;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008041 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008042
8043 if (!bs || !bs->drv) {
8044 return NULL;
8045 }
8046
8047 if (!bs->drv->is_filter) {
8048 return NULL;
8049 }
8050
8051 /* Only one of @backing or @file may be used */
8052 assert(!(bs->backing && bs->file));
8053
8054 c = bs->backing ?: bs->file;
8055 if (!c) {
8056 return NULL;
8057 }
8058
8059 assert(c->role & BDRV_CHILD_FILTERED);
8060 return c;
8061}
8062
8063/*
8064 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8065 * whichever is non-NULL.
8066 *
8067 * Return NULL if both are NULL.
8068 */
8069BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8070{
8071 BdrvChild *cow_child = bdrv_cow_child(bs);
8072 BdrvChild *filter_child = bdrv_filter_child(bs);
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008073 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008074
8075 /* Filter nodes cannot have COW backing files */
8076 assert(!(cow_child && filter_child));
8077
8078 return cow_child ?: filter_child;
8079}
8080
8081/*
8082 * Return the primary child of this node: For filters, that is the
8083 * filtered child. For other nodes, that is usually the child storing
8084 * metadata.
8085 * (A generally more helpful description is that this is (usually) the
8086 * child that has the same filename as @bs.)
8087 *
8088 * Drivers do not necessarily have a primary child; for example quorum
8089 * does not.
8090 */
8091BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8092{
8093 BdrvChild *c, *found = NULL;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008094 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008095
8096 QLIST_FOREACH(c, &bs->children, next) {
8097 if (c->role & BDRV_CHILD_PRIMARY) {
8098 assert(!found);
8099 found = c;
8100 }
8101 }
8102
8103 return found;
8104}
Max Reitzd38d7eb2019-06-12 15:06:37 +02008105
8106static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8107 bool stop_on_explicit_filter)
8108{
8109 BdrvChild *c;
8110
8111 if (!bs) {
8112 return NULL;
8113 }
8114
8115 while (!(stop_on_explicit_filter && !bs->implicit)) {
8116 c = bdrv_filter_child(bs);
8117 if (!c) {
8118 /*
8119 * A filter that is embedded in a working block graph must
8120 * have a child. Assert this here so this function does
8121 * not return a filter node that is not expected by the
8122 * caller.
8123 */
8124 assert(!bs->drv || !bs->drv->is_filter);
8125 break;
8126 }
8127 bs = c->bs;
8128 }
8129 /*
8130 * Note that this treats nodes with bs->drv == NULL as not being
8131 * filters (bs->drv == NULL should be replaced by something else
8132 * anyway).
8133 * The advantage of this behavior is that this function will thus
8134 * always return a non-NULL value (given a non-NULL @bs).
8135 */
8136
8137 return bs;
8138}
8139
8140/*
8141 * Return the first BDS that has not been added implicitly or that
8142 * does not have a filtered child down the chain starting from @bs
8143 * (including @bs itself).
8144 */
8145BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8146{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05008147 GLOBAL_STATE_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008148 return bdrv_do_skip_filters(bs, true);
8149}
8150
8151/*
8152 * Return the first BDS that does not have a filtered child down the
8153 * chain starting from @bs (including @bs itself).
8154 */
8155BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8156{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008157 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008158 return bdrv_do_skip_filters(bs, false);
8159}
8160
8161/*
8162 * For a backing chain, return the first non-filter backing image of
8163 * the first non-filter image.
8164 */
8165BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8166{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008167 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008168 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8169}
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008170
8171/**
8172 * Check whether [offset, offset + bytes) overlaps with the cached
8173 * block-status data region.
8174 *
8175 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8176 * which is what bdrv_bsc_is_data()'s interface needs.
8177 * Otherwise, *pnum is not touched.
8178 */
8179static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8180 int64_t offset, int64_t bytes,
8181 int64_t *pnum)
8182{
8183 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8184 bool overlaps;
8185
8186 overlaps =
8187 qatomic_read(&bsc->valid) &&
8188 ranges_overlap(offset, bytes, bsc->data_start,
8189 bsc->data_end - bsc->data_start);
8190
8191 if (overlaps && pnum) {
8192 *pnum = bsc->data_end - offset;
8193 }
8194
8195 return overlaps;
8196}
8197
8198/**
8199 * See block_int.h for this function's documentation.
8200 */
8201bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8202{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008203 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008204 RCU_READ_LOCK_GUARD();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008205 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8206}
8207
8208/**
8209 * See block_int.h for this function's documentation.
8210 */
8211void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8212 int64_t offset, int64_t bytes)
8213{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008214 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008215 RCU_READ_LOCK_GUARD();
8216
8217 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8218 qatomic_set(&bs->block_status_cache->valid, false);
8219 }
8220}
8221
8222/**
8223 * See block_int.h for this function's documentation.
8224 */
8225void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8226{
8227 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8228 BdrvBlockStatusCache *old_bsc;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008229 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008230
8231 *new_bsc = (BdrvBlockStatusCache) {
8232 .valid = true,
8233 .data_start = offset,
8234 .data_end = offset + bytes,
8235 };
8236
8237 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8238
8239 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8240 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8241 if (old_bsc) {
8242 g_free_rcu(old_bsc, rcu);
8243 }
8244}