blob: f2f91788323aa8a8fb5989a40aa84236eeea4b2e [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
529static void coroutine_fn bdrv_create_co_entry(void *opaque)
530{
Max Reitzcc84d902013-09-06 17:14:26 +0200531 Error *local_err = NULL;
532 int ret;
533
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800534 CreateCo *cco = opaque;
535 assert(cco->drv);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -0500536 GLOBAL_STATE_CODE();
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800537
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200538 ret = cco->drv->bdrv_co_create_opts(cco->drv,
539 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300540 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200541 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800542}
543
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200544int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800545 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000546{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800547 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200548
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500549 GLOBAL_STATE_CODE();
550
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800551 Coroutine *co;
552 CreateCo cco = {
553 .drv = drv,
554 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800555 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800556 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200557 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800558 };
559
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100560 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200561 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300562 ret = -ENOTSUP;
563 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800564 }
565
566 if (qemu_in_coroutine()) {
567 /* Fast-path if already in coroutine context */
568 bdrv_create_co_entry(&cco);
569 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200570 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
571 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800572 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200573 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800574 }
575 }
576
577 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200578 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100579 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200580 error_propagate(errp, cco.err);
581 } else {
582 error_setg_errno(errp, -ret, "Could not create image");
583 }
584 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800585
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300586out:
587 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800588 return ret;
bellardea2384d2004-08-01 21:59:26 +0000589}
590
Max Reitzfd171462020-01-22 17:45:29 +0100591/**
592 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
593 * least the given @minimum_size.
594 *
595 * On success, return @blk's actual length.
596 * Otherwise, return -errno.
597 */
598static int64_t create_file_fallback_truncate(BlockBackend *blk,
599 int64_t minimum_size, Error **errp)
600{
601 Error *local_err = NULL;
602 int64_t size;
603 int ret;
604
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500605 GLOBAL_STATE_CODE();
606
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200607 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
608 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100609 if (ret < 0 && ret != -ENOTSUP) {
610 error_propagate(errp, local_err);
611 return ret;
612 }
613
614 size = blk_getlength(blk);
615 if (size < 0) {
616 error_free(local_err);
617 error_setg_errno(errp, -size,
618 "Failed to inquire the new image file's length");
619 return size;
620 }
621
622 if (size < minimum_size) {
623 /* Need to grow the image, but we failed to do that */
624 error_propagate(errp, local_err);
625 return -ENOTSUP;
626 }
627
628 error_free(local_err);
629 local_err = NULL;
630
631 return size;
632}
633
634/**
635 * Helper function for bdrv_create_file_fallback(): Zero the first
636 * sector to remove any potentially pre-existing image header.
637 */
Paolo Bonzini881a4c52022-09-22 10:49:00 +0200638static int coroutine_fn
639create_file_fallback_zero_first_sector(BlockBackend *blk,
640 int64_t current_size,
641 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100642{
643 int64_t bytes_to_clear;
644 int ret;
645
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500646 GLOBAL_STATE_CODE();
647
Max Reitzfd171462020-01-22 17:45:29 +0100648 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
649 if (bytes_to_clear) {
Alberto Fariace47ff22022-10-13 14:37:02 +0200650 ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
Max Reitzfd171462020-01-22 17:45:29 +0100651 if (ret < 0) {
652 error_setg_errno(errp, -ret,
653 "Failed to clear the new image's first sector");
654 return ret;
655 }
656 }
657
658 return 0;
659}
660
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200661/**
662 * Simple implementation of bdrv_co_create_opts for protocol drivers
663 * which only support creation via opening a file
664 * (usually existing raw storage device)
665 */
666int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
667 const char *filename,
668 QemuOpts *opts,
669 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100670{
671 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100672 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100673 int64_t size = 0;
674 char *buf = NULL;
675 PreallocMode prealloc;
676 Error *local_err = NULL;
677 int ret;
678
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -0500679 GLOBAL_STATE_CODE();
680
Max Reitzfd171462020-01-22 17:45:29 +0100681 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
682 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
683 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
684 PREALLOC_MODE_OFF, &local_err);
685 g_free(buf);
686 if (local_err) {
687 error_propagate(errp, local_err);
688 return -EINVAL;
689 }
690
691 if (prealloc != PREALLOC_MODE_OFF) {
692 error_setg(errp, "Unsupported preallocation mode '%s'",
693 PreallocMode_str(prealloc));
694 return -ENOTSUP;
695 }
696
Max Reitzeeea1fa2020-02-25 16:56:18 +0100697 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100698 qdict_put_str(options, "driver", drv->format_name);
699
700 blk = blk_new_open(filename, NULL, options,
701 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
702 if (!blk) {
703 error_prepend(errp, "Protocol driver '%s' does not support image "
704 "creation, and opening the image failed: ",
705 drv->format_name);
706 return -EINVAL;
707 }
708
709 size = create_file_fallback_truncate(blk, size, errp);
710 if (size < 0) {
711 ret = size;
712 goto out;
713 }
714
715 ret = create_file_fallback_zero_first_sector(blk, size, errp);
716 if (ret < 0) {
717 goto out;
718 }
719
720 ret = 0;
721out:
722 blk_unref(blk);
723 return ret;
724}
725
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800726int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200727{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100728 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200729 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100730 QDict *qdict;
731 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200732
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500733 GLOBAL_STATE_CODE();
734
Max Reitzb65a5e12015-02-05 13:58:12 -0500735 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200736 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000737 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200738 }
739
Stefano Garzarella729222a2021-03-08 17:12:32 +0100740 if (!drv->create_opts) {
741 error_setg(errp, "Driver '%s' does not support image creation",
742 drv->format_name);
743 return -ENOTSUP;
744 }
745
746 /*
747 * 'opts' contains a QemuOptsList with a combination of format and protocol
748 * default values.
749 *
750 * The format properly removes its options, but the default values remain
751 * in 'opts->list'. So if the protocol has options with the same name
752 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
753 * of the format, since for overlapping options, the format wins.
754 *
755 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
756 * only the set options, and then convert it back to QemuOpts, using the
757 * create_opts of the protocol. So the new QemuOpts, will contain only the
758 * protocol defaults.
759 */
760 qdict = qemu_opts_to_qdict(opts, NULL);
761 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
762 if (protocol_opts == NULL) {
763 ret = -EINVAL;
764 goto out;
765 }
766
767 ret = bdrv_create(drv, filename, protocol_opts, errp);
768out:
769 qemu_opts_del(protocol_opts);
770 qobject_unref(qdict);
771 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200772}
773
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300774int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
775{
776 Error *local_err = NULL;
777 int ret;
778
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500779 IO_CODE();
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300780 assert(bs != NULL);
781
782 if (!bs->drv) {
783 error_setg(errp, "Block node '%s' is not opened", bs->filename);
784 return -ENOMEDIUM;
785 }
786
787 if (!bs->drv->bdrv_co_delete_file) {
788 error_setg(errp, "Driver '%s' does not support image deletion",
789 bs->drv->format_name);
790 return -ENOTSUP;
791 }
792
793 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
794 if (ret < 0) {
795 error_propagate(errp, local_err);
796 }
797
798 return ret;
799}
800
Maxim Levitskya890f082020-12-17 19:09:03 +0200801void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
802{
803 Error *local_err = NULL;
804 int ret;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500805 IO_CODE();
Maxim Levitskya890f082020-12-17 19:09:03 +0200806
807 if (!bs) {
808 return;
809 }
810
811 ret = bdrv_co_delete_file(bs, &local_err);
812 /*
813 * ENOTSUP will happen if the block driver doesn't support
814 * the 'bdrv_co_delete_file' interface. This is a predictable
815 * scenario and shouldn't be reported back to the user.
816 */
817 if (ret == -ENOTSUP) {
818 error_free(local_err);
819 } else if (ret < 0) {
820 error_report_err(local_err);
821 }
822}
823
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100824/**
825 * Try to get @bs's logical and physical block size.
826 * On success, store them in @bsz struct and return 0.
827 * On failure return -errno.
828 * @bs must not be empty.
829 */
830int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
831{
832 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200833 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500834 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100835
836 if (drv && drv->bdrv_probe_blocksizes) {
837 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200838 } else if (filtered) {
839 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100840 }
841
842 return -ENOTSUP;
843}
844
845/**
846 * Try to get @bs's geometry (cyls, heads, sectors).
847 * On success, store them in @geo struct and return 0.
848 * On failure return -errno.
849 * @bs must not be empty.
850 */
851int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
852{
853 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200854 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500855 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100856
857 if (drv && drv->bdrv_probe_geometry) {
858 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200859 } else if (filtered) {
860 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100861 }
862
863 return -ENOTSUP;
864}
865
Jim Meyeringeba25052012-05-28 09:27:54 +0200866/*
867 * Create a uniquely-named empty temporary file.
Bin Meng69fbfff2022-10-10 12:04:31 +0800868 * Return the actual file name used upon success, otherwise NULL.
869 * This string should be freed with g_free() when not needed any longer.
870 *
871 * Note: creating a temporary file for the caller to (re)open is
872 * inherently racy. Use g_file_open_tmp() instead whenever practical.
Jim Meyeringeba25052012-05-28 09:27:54 +0200873 */
Bin Meng69fbfff2022-10-10 12:04:31 +0800874char *create_tmp_file(Error **errp)
Jim Meyeringeba25052012-05-28 09:27:54 +0200875{
bellardea2384d2004-08-01 21:59:26 +0000876 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000877 const char *tmpdir;
Bin Meng69fbfff2022-10-10 12:04:31 +0800878 g_autofree char *filename = NULL;
879
880 tmpdir = g_get_tmp_dir();
881#ifndef _WIN32
882 /*
883 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
884 *
885 * This function is used to create temporary disk images (like -snapshot),
886 * so the files can become very large. /tmp is often a tmpfs where as
887 * /var/tmp is usually on a disk, so more appropriate for disk images.
888 */
889 if (!g_strcmp0(tmpdir, "/tmp")) {
Amit Shah69bef792014-02-26 15:12:37 +0530890 tmpdir = "/var/tmp";
891 }
bellardd5249392004-08-03 21:14:23 +0000892#endif
Bin Meng69fbfff2022-10-10 12:04:31 +0800893
894 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
895 fd = g_mkstemp(filename);
bellardea2384d2004-08-01 21:59:26 +0000896 if (fd < 0) {
Bin Meng69fbfff2022-10-10 12:04:31 +0800897 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
898 filename);
899 return NULL;
bellardea2384d2004-08-01 21:59:26 +0000900 }
Bin Meng6b6471e2022-10-10 12:04:30 +0800901 close(fd);
Bin Meng69fbfff2022-10-10 12:04:31 +0800902
903 return g_steal_pointer(&filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200904}
bellardea2384d2004-08-01 21:59:26 +0000905
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200906/*
907 * Detect host devices. By convention, /dev/cdrom[N] is always
908 * recognized as a host CDROM.
909 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200910static BlockDriver *find_hdev_driver(const char *filename)
911{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200912 int score_max = 0, score;
913 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500914 GLOBAL_STATE_CODE();
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200915
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100916 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200917 if (d->bdrv_probe_device) {
918 score = d->bdrv_probe_device(filename);
919 if (score > score_max) {
920 score_max = score;
921 drv = d;
922 }
923 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200924 }
925
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200926 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200927}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200928
Marc Mari88d88792016-08-12 09:27:03 -0400929static BlockDriver *bdrv_do_find_protocol(const char *protocol)
930{
931 BlockDriver *drv1;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500932 GLOBAL_STATE_CODE();
Marc Mari88d88792016-08-12 09:27:03 -0400933
934 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
935 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
936 return drv1;
937 }
938 }
939
940 return NULL;
941}
942
Kevin Wolf98289622013-07-10 15:47:39 +0200943BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500944 bool allow_protocol_prefix,
945 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200946{
947 BlockDriver *drv1;
948 char protocol[128];
949 int len;
950 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400951 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200952
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500953 GLOBAL_STATE_CODE();
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200954 /* TODO Drivers without bdrv_file_open must be specified explicitly */
955
Christoph Hellwig39508e72010-06-23 12:25:17 +0200956 /*
957 * XXX(hch): we really should not let host device detection
958 * override an explicit protocol specification, but moving this
959 * later breaks access to device names with colons in them.
960 * Thanks to the brain-dead persistent naming schemes on udev-
961 * based Linux systems those actually are quite common.
962 */
963 drv1 = find_hdev_driver(filename);
964 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200965 return drv1;
966 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200967
Kevin Wolf98289622013-07-10 15:47:39 +0200968 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100969 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200970 }
Kevin Wolf98289622013-07-10 15:47:39 +0200971
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000972 p = strchr(filename, ':');
973 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200974 len = p - filename;
975 if (len > sizeof(protocol) - 1)
976 len = sizeof(protocol) - 1;
977 memcpy(protocol, filename, len);
978 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400979
980 drv1 = bdrv_do_find_protocol(protocol);
981 if (drv1) {
982 return drv1;
983 }
984
985 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
986 if (block_driver_modules[i].protocol_name &&
987 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
Claudio Fontanac551fb02022-09-29 11:30:33 +0200988 int rv = block_module_load(block_driver_modules[i].library_name, errp);
989 if (rv > 0) {
990 drv1 = bdrv_do_find_protocol(protocol);
991 } else if (rv < 0) {
992 return NULL;
993 }
Marc Mari88d88792016-08-12 09:27:03 -0400994 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200995 }
996 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500997
Marc Mari88d88792016-08-12 09:27:03 -0400998 if (!drv1) {
999 error_setg(errp, "Unknown protocol '%s'", protocol);
1000 }
1001 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +02001002}
1003
Markus Armbrusterc6684242014-11-20 16:27:10 +01001004/*
1005 * Guess image format by probing its contents.
1006 * This is not a good idea when your image is raw (CVE-2008-2004), but
1007 * we do it anyway for backward compatibility.
1008 *
1009 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +01001010 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1011 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001012 * @filename is its filename.
1013 *
1014 * For all block drivers, call the bdrv_probe() method to get its
1015 * probing score.
1016 * Return the first block driver with the highest probing score.
1017 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01001018BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1019 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001020{
1021 int score_max = 0, score;
1022 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001023 IO_CODE();
Markus Armbrusterc6684242014-11-20 16:27:10 +01001024
1025 QLIST_FOREACH(d, &bdrv_drivers, list) {
1026 if (d->bdrv_probe) {
1027 score = d->bdrv_probe(buf, buf_size, filename);
1028 if (score > score_max) {
1029 score_max = score;
1030 drv = d;
1031 }
1032 }
1033 }
1034
1035 return drv;
1036}
1037
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001038static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +02001039 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +00001040{
Markus Armbrusterc6684242014-11-20 16:27:10 +01001041 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +01001042 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +01001043 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001044
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001045 GLOBAL_STATE_CODE();
1046
Kevin Wolf08a00552010-06-01 18:37:31 +02001047 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001048 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +01001049 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +02001050 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -07001051 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001052
Alberto Fariaa9262f52022-07-05 17:15:11 +01001053 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
bellard83f64092006-08-01 16:21:11 +00001054 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001055 error_setg_errno(errp, -ret, "Could not read image for determining its "
1056 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +02001057 *pdrv = NULL;
1058 return ret;
bellard83f64092006-08-01 16:21:11 +00001059 }
1060
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001061 drv = bdrv_probe_all(buf, sizeof(buf), filename);
Stefan Weilc98ac352010-07-21 21:51:51 +02001062 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001063 error_setg(errp, "Could not determine image format: No compatible "
1064 "driver found");
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001065 *pdrv = NULL;
1066 return -ENOENT;
Stefan Weilc98ac352010-07-21 21:51:51 +02001067 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001068
Stefan Weilc98ac352010-07-21 21:51:51 +02001069 *pdrv = drv;
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001070 return 0;
bellardea2384d2004-08-01 21:59:26 +00001071}
1072
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001073/**
1074 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001075 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001076 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001077int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001078{
1079 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001080 IO_CODE();
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001081
Max Reitzd470ad42017-11-10 21:31:09 +01001082 if (!drv) {
1083 return -ENOMEDIUM;
1084 }
1085
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001086 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001087 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001088 return 0;
1089
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001090 /* query actual device if possible, otherwise just trust the hint */
1091 if (drv->bdrv_getlength) {
1092 int64_t length = drv->bdrv_getlength(bs);
1093 if (length < 0) {
1094 return length;
1095 }
Fam Zheng7e382002013-11-06 19:48:06 +08001096 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001097 }
1098
1099 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001100
1101 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1102 return -EFBIG;
1103 }
1104
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001105 return 0;
1106}
1107
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001108/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001109 * Combines a QDict of new block driver @options with any missing options taken
1110 * from @old_options, so that leaving out an option defaults to its old value.
1111 */
1112static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1113 QDict *old_options)
1114{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001115 GLOBAL_STATE_CODE();
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001116 if (bs->drv && bs->drv->bdrv_join_options) {
1117 bs->drv->bdrv_join_options(options, old_options);
1118 } else {
1119 qdict_join(options, old_options, false);
1120 }
1121}
1122
Alberto Garcia543770b2018-09-06 12:37:09 +03001123static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1124 int open_flags,
1125 Error **errp)
1126{
1127 Error *local_err = NULL;
1128 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1129 BlockdevDetectZeroesOptions detect_zeroes =
1130 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1131 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001132 GLOBAL_STATE_CODE();
Alberto Garcia543770b2018-09-06 12:37:09 +03001133 g_free(value);
1134 if (local_err) {
1135 error_propagate(errp, local_err);
1136 return detect_zeroes;
1137 }
1138
1139 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1140 !(open_flags & BDRV_O_UNMAP))
1141 {
1142 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1143 "without setting discard operation to unmap");
1144 }
1145
1146 return detect_zeroes;
1147}
1148
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001149/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001150 * Set open flags for aio engine
1151 *
1152 * Return 0 on success, -1 if the engine specified is invalid
1153 */
1154int bdrv_parse_aio(const char *mode, int *flags)
1155{
1156 if (!strcmp(mode, "threads")) {
1157 /* do nothing, default */
1158 } else if (!strcmp(mode, "native")) {
1159 *flags |= BDRV_O_NATIVE_AIO;
1160#ifdef CONFIG_LINUX_IO_URING
1161 } else if (!strcmp(mode, "io_uring")) {
1162 *flags |= BDRV_O_IO_URING;
1163#endif
1164 } else {
1165 return -1;
1166 }
1167
1168 return 0;
1169}
1170
1171/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001172 * Set open flags for a given discard mode
1173 *
1174 * Return 0 on success, -1 if the discard mode was invalid.
1175 */
1176int bdrv_parse_discard_flags(const char *mode, int *flags)
1177{
1178 *flags &= ~BDRV_O_UNMAP;
1179
1180 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1181 /* do nothing */
1182 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1183 *flags |= BDRV_O_UNMAP;
1184 } else {
1185 return -1;
1186 }
1187
1188 return 0;
1189}
1190
1191/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001192 * Set open flags for a given cache mode
1193 *
1194 * Return 0 on success, -1 if the cache mode was invalid.
1195 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001196int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001197{
1198 *flags &= ~BDRV_O_CACHE_MASK;
1199
1200 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001201 *writethrough = false;
1202 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001203 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001204 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001205 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001206 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001207 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001208 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001209 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001210 *flags |= BDRV_O_NO_FLUSH;
1211 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001212 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001213 } else {
1214 return -1;
1215 }
1216
1217 return 0;
1218}
1219
Kevin Wolfb5411552017-01-17 15:56:16 +01001220static char *bdrv_child_get_parent_desc(BdrvChild *c)
1221{
1222 BlockDriverState *parent = c->opaque;
Vladimir Sementsov-Ogievskiy2c0a3ac2021-06-01 10:52:15 +03001223 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
Kevin Wolfb5411552017-01-17 15:56:16 +01001224}
1225
Kevin Wolf20018e12016-05-23 18:46:59 +02001226static void bdrv_child_cb_drained_begin(BdrvChild *child)
1227{
1228 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001229 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001230}
1231
Kevin Wolf89bd0302018-03-22 14:11:20 +01001232static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1233{
1234 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001235 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001236}
1237
Max Reitze037c092019-07-19 11:26:14 +02001238static void bdrv_child_cb_drained_end(BdrvChild *child,
1239 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001240{
1241 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001242 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001243}
1244
Kevin Wolf38701b62017-05-04 18:52:39 +02001245static int bdrv_child_cb_inactivate(BdrvChild *child)
1246{
1247 BlockDriverState *bs = child->opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001248 GLOBAL_STATE_CODE();
Kevin Wolf38701b62017-05-04 18:52:39 +02001249 assert(bs->open_flags & BDRV_O_INACTIVE);
1250 return 0;
1251}
1252
Emanuele Giuseppe Esposito27633e72022-10-25 04:49:47 -04001253static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1254 GHashTable *visited, Transaction *tran,
1255 Error **errp)
Kevin Wolf5d231842019-05-06 19:17:56 +02001256{
1257 BlockDriverState *bs = child->opaque;
Emanuele Giuseppe Esposito27633e72022-10-25 04:49:47 -04001258 return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
Kevin Wolf53a7d042019-05-06 19:17:59 +02001259}
1260
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001261/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001262 * Returns the options and flags that a temporary snapshot should get, based on
1263 * the originally requested flags (the originally requested image will have
1264 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001265 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001266static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1267 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001268{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001269 GLOBAL_STATE_CODE();
Kevin Wolf73176be2016-03-07 13:02:15 +01001270 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1271
1272 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001273 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1274 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001275
Kevin Wolf3f486862019-04-04 17:04:43 +02001276 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001277 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001278 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001279
Kevin Wolf41869042016-06-16 12:59:30 +02001280 /* aio=native doesn't work for cache.direct=off, so disable it for the
1281 * temporary snapshot */
1282 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001283}
1284
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001285static void bdrv_backing_attach(BdrvChild *c)
1286{
1287 BlockDriverState *parent = c->opaque;
1288 BlockDriverState *backing_hd = c->bs;
1289
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001290 GLOBAL_STATE_CODE();
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001291 assert(!parent->backing_blocker);
1292 error_setg(&parent->backing_blocker,
1293 "node is used as backing hd of '%s'",
1294 bdrv_get_device_or_node_name(parent));
1295
Max Reitzf30c66b2019-02-01 20:29:05 +01001296 bdrv_refresh_filename(backing_hd);
1297
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001298 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001299
1300 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1301 /* Otherwise we won't be able to commit or stream */
1302 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1303 parent->backing_blocker);
1304 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1305 parent->backing_blocker);
1306 /*
1307 * We do backup in 3 ways:
1308 * 1. drive backup
1309 * The target bs is new opened, and the source is top BDS
1310 * 2. blockdev backup
1311 * Both the source and the target are top BDSes.
1312 * 3. internal backup(used for block replication)
1313 * Both the source and the target are backing file
1314 *
1315 * In case 1 and 2, neither the source nor the target is the backing file.
1316 * In case 3, we will block the top BDS, so there is only one block job
1317 * for the top BDS and its backing chain.
1318 */
1319 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1320 parent->backing_blocker);
1321 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1322 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001323}
Kevin Wolfd736f112017-12-18 16:05:48 +01001324
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001325static void bdrv_backing_detach(BdrvChild *c)
1326{
1327 BlockDriverState *parent = c->opaque;
1328
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001329 GLOBAL_STATE_CODE();
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001330 assert(parent->backing_blocker);
1331 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1332 error_free(parent->backing_blocker);
1333 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001334}
Kevin Wolfd736f112017-12-18 16:05:48 +01001335
Kevin Wolf6858eba2017-06-29 19:32:21 +02001336static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1337 const char *filename, Error **errp)
1338{
1339 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001340 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001341 int ret;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001342 GLOBAL_STATE_CODE();
Kevin Wolf6858eba2017-06-29 19:32:21 +02001343
Alberto Garciae94d3db2018-11-12 16:00:34 +02001344 if (read_only) {
1345 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001346 if (ret < 0) {
1347 return ret;
1348 }
1349 }
1350
Kevin Wolf6858eba2017-06-29 19:32:21 +02001351 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001352 base->drv ? base->drv->format_name : "",
1353 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001354 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001355 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001356 }
1357
Alberto Garciae94d3db2018-11-12 16:00:34 +02001358 if (read_only) {
1359 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001360 }
1361
Kevin Wolf6858eba2017-06-29 19:32:21 +02001362 return ret;
1363}
1364
Max Reitzfae8bd32020-05-13 13:05:20 +02001365/*
1366 * Returns the options and flags that a generic child of a BDS should
1367 * get, based on the given options and flags for the parent BDS.
1368 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001369static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1370 int *child_flags, QDict *child_options,
1371 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001372{
1373 int flags = parent_flags;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001374 GLOBAL_STATE_CODE();
Max Reitzfae8bd32020-05-13 13:05:20 +02001375
1376 /*
1377 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1378 * Generally, the question to answer is: Should this child be
1379 * format-probed by default?
1380 */
1381
1382 /*
1383 * Pure and non-filtered data children of non-format nodes should
1384 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1385 * set). This only affects a very limited set of drivers (namely
1386 * quorum and blkverify when this comment was written).
1387 * Force-clear BDRV_O_PROTOCOL then.
1388 */
1389 if (!parent_is_format &&
1390 (role & BDRV_CHILD_DATA) &&
1391 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1392 {
1393 flags &= ~BDRV_O_PROTOCOL;
1394 }
1395
1396 /*
1397 * All children of format nodes (except for COW children) and all
1398 * metadata children in general should never be format-probed.
1399 * Force-set BDRV_O_PROTOCOL then.
1400 */
1401 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1402 (role & BDRV_CHILD_METADATA))
1403 {
1404 flags |= BDRV_O_PROTOCOL;
1405 }
1406
1407 /*
1408 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1409 * the parent.
1410 */
1411 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1412 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1413 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1414
1415 if (role & BDRV_CHILD_COW) {
1416 /* backing files are opened read-only by default */
1417 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1418 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1419 } else {
1420 /* Inherit the read-only option from the parent if it's not set */
1421 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1422 qdict_copy_default(child_options, parent_options,
1423 BDRV_OPT_AUTO_READ_ONLY);
1424 }
1425
1426 /*
1427 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1428 * can default to enable it on lower layers regardless of the
1429 * parent option.
1430 */
1431 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1432
1433 /* Clear flags that only apply to the top layer */
1434 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1435
1436 if (role & BDRV_CHILD_METADATA) {
1437 flags &= ~BDRV_O_NO_IO;
1438 }
1439 if (role & BDRV_CHILD_COW) {
1440 flags &= ~BDRV_O_TEMPORARY;
1441 }
1442
1443 *child_flags = flags;
1444}
1445
Max Reitzca2f1232020-05-13 13:05:22 +02001446static void bdrv_child_cb_attach(BdrvChild *child)
1447{
1448 BlockDriverState *bs = child->opaque;
1449
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05001450 assert_bdrv_graph_writable(bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001451 QLIST_INSERT_HEAD(&bs->children, child, next);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001452 if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1453 /*
1454 * Here we handle filters and block/raw-format.c when it behave like
1455 * filter. They generally have a single PRIMARY child, which is also the
1456 * FILTERED child, and that they may have multiple more children, which
1457 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1458 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1459 * into bs->backing on exceptional cases; and bs->backing will be
1460 * nothing else.
1461 */
1462 assert(!(child->role & BDRV_CHILD_COW));
1463 if (child->role & BDRV_CHILD_PRIMARY) {
1464 assert(child->role & BDRV_CHILD_FILTERED);
1465 assert(!bs->backing);
1466 assert(!bs->file);
Hanna Reitza2253692021-11-15 15:53:58 +01001467
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001468 if (bs->drv->filtered_child_is_backing) {
1469 bs->backing = child;
1470 } else {
1471 bs->file = child;
1472 }
1473 } else {
1474 assert(!(child->role & BDRV_CHILD_FILTERED));
1475 }
1476 } else if (child->role & BDRV_CHILD_COW) {
1477 assert(bs->drv->supports_backing);
1478 assert(!(child->role & BDRV_CHILD_PRIMARY));
1479 assert(!bs->backing);
1480 bs->backing = child;
Max Reitzca2f1232020-05-13 13:05:22 +02001481 bdrv_backing_attach(child);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001482 } else if (child->role & BDRV_CHILD_PRIMARY) {
1483 assert(!bs->file);
1484 bs->file = child;
Max Reitzca2f1232020-05-13 13:05:22 +02001485 }
1486
1487 bdrv_apply_subtree_drain(child, bs);
1488}
1489
Max Reitz48e08282020-05-13 13:05:23 +02001490static void bdrv_child_cb_detach(BdrvChild *child)
1491{
1492 BlockDriverState *bs = child->opaque;
1493
1494 if (child->role & BDRV_CHILD_COW) {
1495 bdrv_backing_detach(child);
1496 }
1497
1498 bdrv_unapply_subtree_drain(child, bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001499
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05001500 assert_bdrv_graph_writable(bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001501 QLIST_REMOVE(child, next);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001502 if (child == bs->backing) {
1503 assert(child != bs->file);
1504 bs->backing = NULL;
1505 } else if (child == bs->file) {
1506 bs->file = NULL;
1507 }
Max Reitz48e08282020-05-13 13:05:23 +02001508}
1509
Max Reitz43483552020-05-13 13:05:24 +02001510static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1511 const char *filename, Error **errp)
1512{
1513 if (c->role & BDRV_CHILD_COW) {
1514 return bdrv_backing_update_filename(c, base, filename, errp);
1515 }
1516 return 0;
1517}
1518
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001519AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001520{
1521 BlockDriverState *bs = c->opaque;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05001522 IO_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001523
1524 return bdrv_get_aio_context(bs);
1525}
1526
Max Reitz43483552020-05-13 13:05:24 +02001527const BdrvChildClass child_of_bds = {
1528 .parent_is_bds = true,
1529 .get_parent_desc = bdrv_child_get_parent_desc,
1530 .inherit_options = bdrv_inherited_options,
1531 .drained_begin = bdrv_child_cb_drained_begin,
1532 .drained_poll = bdrv_child_cb_drained_poll,
1533 .drained_end = bdrv_child_cb_drained_end,
1534 .attach = bdrv_child_cb_attach,
1535 .detach = bdrv_child_cb_detach,
1536 .inactivate = bdrv_child_cb_inactivate,
Emanuele Giuseppe Esposito27633e72022-10-25 04:49:47 -04001537 .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
Max Reitz43483552020-05-13 13:05:24 +02001538 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001539 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001540};
1541
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001542AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1543{
Hanna Reitzd5f8d792022-11-07 16:13:19 +01001544 IO_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001545 return c->klass->get_parent_aio_context(c);
1546}
1547
Kevin Wolf7b272452012-11-12 17:05:39 +01001548static int bdrv_open_flags(BlockDriverState *bs, int flags)
1549{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001550 int open_flags = flags;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001551 GLOBAL_STATE_CODE();
Kevin Wolf7b272452012-11-12 17:05:39 +01001552
1553 /*
1554 * Clear flags that are internal to the block layer before opening the
1555 * image.
1556 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001557 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001558
Kevin Wolf7b272452012-11-12 17:05:39 +01001559 return open_flags;
1560}
1561
Kevin Wolf91a097e2015-05-08 17:49:53 +02001562static void update_flags_from_options(int *flags, QemuOpts *opts)
1563{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001564 GLOBAL_STATE_CODE();
1565
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001566 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001567
Alberto Garcia57f9db92018-09-06 12:37:06 +03001568 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001569 *flags |= BDRV_O_NO_FLUSH;
1570 }
1571
Alberto Garcia57f9db92018-09-06 12:37:06 +03001572 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001573 *flags |= BDRV_O_NOCACHE;
1574 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001575
Alberto Garcia57f9db92018-09-06 12:37:06 +03001576 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001577 *flags |= BDRV_O_RDWR;
1578 }
1579
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001580 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1581 *flags |= BDRV_O_AUTO_RDONLY;
1582 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001583}
1584
1585static void update_options_from_flags(QDict *options, int flags)
1586{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001587 GLOBAL_STATE_CODE();
Kevin Wolf91a097e2015-05-08 17:49:53 +02001588 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001589 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001590 }
1591 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001592 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1593 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001594 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001595 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001596 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001597 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001598 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1599 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1600 flags & BDRV_O_AUTO_RDONLY);
1601 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001602}
1603
Kevin Wolf636ea372014-01-24 14:11:52 +01001604static void bdrv_assign_node_name(BlockDriverState *bs,
1605 const char *node_name,
1606 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001607{
Jeff Cody15489c72015-10-12 19:36:50 -04001608 char *gen_node_name = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001609 GLOBAL_STATE_CODE();
Benoît Canet6913c0c2014-01-23 21:31:33 +01001610
Jeff Cody15489c72015-10-12 19:36:50 -04001611 if (!node_name) {
1612 node_name = gen_node_name = id_generate(ID_BLOCK);
1613 } else if (!id_wellformed(node_name)) {
1614 /*
1615 * Check for empty string or invalid characters, but not if it is
1616 * generated (generated names use characters not available to the user)
1617 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001618 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001619 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001620 }
1621
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001622 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001623 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001624 error_setg(errp, "node-name=%s is conflicting with a device id",
1625 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001626 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001627 }
1628
Benoît Canet6913c0c2014-01-23 21:31:33 +01001629 /* takes care of avoiding duplicates node names */
1630 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001631 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001632 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001633 }
1634
Kevin Wolf824808d2018-07-04 13:28:29 +02001635 /* Make sure that the node name isn't truncated */
1636 if (strlen(node_name) >= sizeof(bs->node_name)) {
1637 error_setg(errp, "Node name too long");
1638 goto out;
1639 }
1640
Benoît Canet6913c0c2014-01-23 21:31:33 +01001641 /* copy node name into the bs and insert it into the graph list */
1642 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1643 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001644out:
1645 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001646}
1647
Kevin Wolf01a56502017-01-18 15:51:56 +01001648static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1649 const char *node_name, QDict *options,
1650 int open_flags, Error **errp)
1651{
1652 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001653 int i, ret;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001654 GLOBAL_STATE_CODE();
Kevin Wolf01a56502017-01-18 15:51:56 +01001655
1656 bdrv_assign_node_name(bs, node_name, &local_err);
1657 if (local_err) {
1658 error_propagate(errp, local_err);
1659 return -EINVAL;
1660 }
1661
1662 bs->drv = drv;
1663 bs->opaque = g_malloc0(drv->instance_size);
1664
1665 if (drv->bdrv_file_open) {
1666 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1667 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001668 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001669 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001670 } else {
1671 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001672 }
1673
1674 if (ret < 0) {
1675 if (local_err) {
1676 error_propagate(errp, local_err);
1677 } else if (bs->filename[0]) {
1678 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1679 } else {
1680 error_setg_errno(errp, -ret, "Could not open image");
1681 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001682 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001683 }
1684
Stefan Hajnoczie8b65352022-10-13 14:59:01 -04001685 assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1686 assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1687
1688 /*
1689 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1690 * drivers that pass read/write requests through to a child the trouble of
1691 * declaring support explicitly.
1692 *
1693 * Drivers must not propagate this flag accidentally when they initiate I/O
1694 * to a bounce buffer. That case should be rare though.
1695 */
1696 bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1697 bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1698
Kevin Wolf01a56502017-01-18 15:51:56 +01001699 ret = refresh_total_sectors(bs, bs->total_sectors);
1700 if (ret < 0) {
1701 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001702 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001703 }
1704
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001705 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001706 if (local_err) {
1707 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001708 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001709 }
1710
1711 assert(bdrv_opt_mem_align(bs) != 0);
1712 assert(bdrv_min_mem_align(bs) != 0);
1713 assert(is_power_of_2(bs->bl.request_alignment));
1714
Kevin Wolf0f122642018-03-28 18:29:18 +02001715 for (i = 0; i < bs->quiesce_counter; i++) {
1716 if (drv->bdrv_co_drain_begin) {
1717 drv->bdrv_co_drain_begin(bs);
1718 }
1719 }
1720
Kevin Wolf01a56502017-01-18 15:51:56 +01001721 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001722open_failed:
1723 bs->drv = NULL;
1724 if (bs->file != NULL) {
1725 bdrv_unref_child(bs, bs->file);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03001726 assert(!bs->file);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001727 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001728 g_free(bs->opaque);
1729 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001730 return ret;
1731}
1732
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001733/*
1734 * Create and open a block node.
1735 *
1736 * @options is a QDict of options to pass to the block drivers, or NULL for an
1737 * empty set of options. The reference to the QDict belongs to the block layer
1738 * after the call (even on failure), so if the caller intends to reuse the
1739 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1740 */
1741BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1742 const char *node_name,
1743 QDict *options, int flags,
1744 Error **errp)
Kevin Wolf680c7f92017-01-18 17:16:41 +01001745{
1746 BlockDriverState *bs;
1747 int ret;
1748
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001749 GLOBAL_STATE_CODE();
1750
Kevin Wolf680c7f92017-01-18 17:16:41 +01001751 bs = bdrv_new();
1752 bs->open_flags = flags;
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001753 bs->options = options ?: qdict_new();
1754 bs->explicit_options = qdict_clone_shallow(bs->options);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001755 bs->opaque = NULL;
1756
1757 update_options_from_flags(bs->options, flags);
1758
1759 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1760 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001761 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001762 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001763 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001764 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001765 bdrv_unref(bs);
1766 return NULL;
1767 }
1768
1769 return bs;
1770}
1771
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001772/* Create and open a block node. */
1773BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1774 int flags, Error **errp)
1775{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001776 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001777 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1778}
1779
Kevin Wolfc5f30142016-10-06 11:33:17 +02001780QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001781 .name = "bdrv_common",
1782 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1783 .desc = {
1784 {
1785 .name = "node-name",
1786 .type = QEMU_OPT_STRING,
1787 .help = "Node name of the block device node",
1788 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001789 {
1790 .name = "driver",
1791 .type = QEMU_OPT_STRING,
1792 .help = "Block driver to use for the node",
1793 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001794 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001795 .name = BDRV_OPT_CACHE_DIRECT,
1796 .type = QEMU_OPT_BOOL,
1797 .help = "Bypass software writeback cache on the host",
1798 },
1799 {
1800 .name = BDRV_OPT_CACHE_NO_FLUSH,
1801 .type = QEMU_OPT_BOOL,
1802 .help = "Ignore flush requests",
1803 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001804 {
1805 .name = BDRV_OPT_READ_ONLY,
1806 .type = QEMU_OPT_BOOL,
1807 .help = "Node is opened in read-only mode",
1808 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001809 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001810 .name = BDRV_OPT_AUTO_READ_ONLY,
1811 .type = QEMU_OPT_BOOL,
1812 .help = "Node can become read-only if opening read-write fails",
1813 },
1814 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001815 .name = "detect-zeroes",
1816 .type = QEMU_OPT_STRING,
1817 .help = "try to optimize zero writes (off, on, unmap)",
1818 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001819 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001820 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001821 .type = QEMU_OPT_STRING,
1822 .help = "discard operation (ignore/off, unmap/on)",
1823 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001824 {
1825 .name = BDRV_OPT_FORCE_SHARE,
1826 .type = QEMU_OPT_BOOL,
1827 .help = "always accept other writers (default: off)",
1828 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001829 { /* end of list */ }
1830 },
1831};
1832
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001833QemuOptsList bdrv_create_opts_simple = {
1834 .name = "simple-create-opts",
1835 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001836 .desc = {
1837 {
1838 .name = BLOCK_OPT_SIZE,
1839 .type = QEMU_OPT_SIZE,
1840 .help = "Virtual disk size"
1841 },
1842 {
1843 .name = BLOCK_OPT_PREALLOC,
1844 .type = QEMU_OPT_STRING,
1845 .help = "Preallocation mode (allowed values: off)"
1846 },
1847 { /* end of list */ }
1848 }
1849};
1850
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001851/*
Kevin Wolf57915332010-04-14 15:24:50 +02001852 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001853 *
1854 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001855 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001856static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001857 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001858{
1859 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001860 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001861 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001862 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001863 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001864 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001865 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001866 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001867 bool ro;
Kevin Wolf57915332010-04-14 15:24:50 +02001868
Paolo Bonzini64058752012-05-08 16:51:49 +02001869 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001870 assert(options != NULL && bs->options != options);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001871 GLOBAL_STATE_CODE();
Kevin Wolf57915332010-04-14 15:24:50 +02001872
Kevin Wolf62392eb2015-04-24 16:38:02 +02001873 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001874 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001875 ret = -EINVAL;
1876 goto fail_opts;
1877 }
1878
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001879 update_flags_from_options(&bs->open_flags, opts);
1880
Kevin Wolf62392eb2015-04-24 16:38:02 +02001881 driver_name = qemu_opt_get(opts, "driver");
1882 drv = bdrv_find_format(driver_name);
1883 assert(drv != NULL);
1884
Fam Zheng5a9347c2017-05-03 00:35:37 +08001885 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1886
1887 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1888 error_setg(errp,
1889 BDRV_OPT_FORCE_SHARE
1890 "=on can only be used with read-only images");
1891 ret = -EINVAL;
1892 goto fail_opts;
1893 }
1894
Kevin Wolf45673672013-04-22 17:48:40 +02001895 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001896 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001897 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001898 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001899 /*
1900 * Caution: while qdict_get_try_str() is fine, getting
1901 * non-string types would require more care. When @options
1902 * come from -blockdev or blockdev_add, its members are typed
1903 * according to the QAPI schema, but when they come from
1904 * -drive, they're all QString.
1905 */
Kevin Wolf45673672013-04-22 17:48:40 +02001906 filename = qdict_get_try_str(options, "filename");
1907 }
1908
Max Reitz4a008242017-04-13 18:06:24 +02001909 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001910 error_setg(errp, "The '%s' block driver requires a file name",
1911 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001912 ret = -EINVAL;
1913 goto fail_opts;
1914 }
1915
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001916 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1917 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001918
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001919 ro = bdrv_is_read_only(bs);
1920
1921 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1922 if (!ro && bdrv_is_whitelisted(drv, true)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001923 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1924 } else {
1925 ret = -ENOTSUP;
1926 }
1927 if (ret < 0) {
1928 error_setg(errp,
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001929 !ro && bdrv_is_whitelisted(drv, true)
Kevin Wolf8be25de2019-01-22 13:15:31 +01001930 ? "Driver '%s' can only be used for read-only devices"
1931 : "Driver '%s' is not whitelisted",
1932 drv->format_name);
1933 goto fail_opts;
1934 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001935 }
Kevin Wolf57915332010-04-14 15:24:50 +02001936
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001937 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001938 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001939
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001940 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001941 if (!ro) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001942 bdrv_enable_copy_on_read(bs);
1943 } else {
1944 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001945 ret = -EINVAL;
1946 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001947 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001948 }
1949
Alberto Garcia415bbca2018-10-03 13:23:13 +03001950 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001951 if (discard != NULL) {
1952 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1953 error_setg(errp, "Invalid discard option");
1954 ret = -EINVAL;
1955 goto fail_opts;
1956 }
1957 }
1958
Alberto Garcia543770b2018-09-06 12:37:09 +03001959 bs->detect_zeroes =
1960 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1961 if (local_err) {
1962 error_propagate(errp, local_err);
1963 ret = -EINVAL;
1964 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001965 }
1966
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001967 if (filename != NULL) {
1968 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1969 } else {
1970 bs->filename[0] = '\0';
1971 }
Max Reitz91af7012014-07-18 20:24:56 +02001972 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001973
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001974 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001975 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001976 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001977
Kevin Wolf01a56502017-01-18 15:51:56 +01001978 assert(!drv->bdrv_file_open || file == NULL);
1979 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001980 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001981 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001982 }
1983
Kevin Wolf18edf282015-04-07 17:12:56 +02001984 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001985 return 0;
1986
Kevin Wolf18edf282015-04-07 17:12:56 +02001987fail_opts:
1988 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001989 return ret;
1990}
1991
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001992static QDict *parse_json_filename(const char *filename, Error **errp)
1993{
1994 QObject *options_obj;
1995 QDict *options;
1996 int ret;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001997 GLOBAL_STATE_CODE();
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001998
1999 ret = strstart(filename, "json:", &filename);
2000 assert(ret);
2001
Markus Armbruster5577fff2017-02-28 22:26:59 +01002002 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02002003 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01002004 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02002005 return NULL;
2006 }
2007
Max Reitz7dc847e2018-02-24 16:40:29 +01002008 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01002009 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002010 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02002011 error_setg(errp, "Invalid JSON object given");
2012 return NULL;
2013 }
2014
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02002015 qdict_flatten(options);
2016
2017 return options;
2018}
2019
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002020static void parse_json_protocol(QDict *options, const char **pfilename,
2021 Error **errp)
2022{
2023 QDict *json_options;
2024 Error *local_err = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002025 GLOBAL_STATE_CODE();
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002026
2027 /* Parse json: pseudo-protocol */
2028 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2029 return;
2030 }
2031
2032 json_options = parse_json_filename(*pfilename, &local_err);
2033 if (local_err) {
2034 error_propagate(errp, local_err);
2035 return;
2036 }
2037
2038 /* Options given in the filename have lower priority than options
2039 * specified directly */
2040 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002041 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002042 *pfilename = NULL;
2043}
2044
Kevin Wolf57915332010-04-14 15:24:50 +02002045/*
Kevin Wolff54120f2014-05-26 11:09:59 +02002046 * Fills in default options for opening images and converts the legacy
2047 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04002048 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2049 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02002050 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002051static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02002052 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02002053{
2054 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04002055 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002056 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02002057 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002058 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002059
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002060 GLOBAL_STATE_CODE();
2061
Markus Armbruster129c7d12017-03-30 19:43:12 +02002062 /*
2063 * Caution: while qdict_get_try_str() is fine, getting non-string
2064 * types would require more care. When @options come from
2065 * -blockdev or blockdev_add, its members are typed according to
2066 * the QAPI schema, but when they come from -drive, they're all
2067 * QString.
2068 */
Max Reitz53a29512015-03-19 14:53:16 -04002069 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02002070 if (drvname) {
2071 drv = bdrv_find_format(drvname);
2072 if (!drv) {
2073 error_setg(errp, "Unknown driver '%s'", drvname);
2074 return -ENOENT;
2075 }
2076 /* If the user has explicitly specified the driver, this choice should
2077 * override the BDRV_O_PROTOCOL flag */
2078 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04002079 }
2080
2081 if (protocol) {
2082 *flags |= BDRV_O_PROTOCOL;
2083 } else {
2084 *flags &= ~BDRV_O_PROTOCOL;
2085 }
2086
Kevin Wolf91a097e2015-05-08 17:49:53 +02002087 /* Translate cache options from flags into options */
2088 update_options_from_flags(*options, *flags);
2089
Kevin Wolff54120f2014-05-26 11:09:59 +02002090 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002091 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002092 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002093 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02002094 parse_filename = true;
2095 } else {
2096 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2097 "the same time");
2098 return -EINVAL;
2099 }
2100 }
2101
2102 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02002103 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02002104 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02002105
Max Reitz053e1572015-08-26 19:47:51 +02002106 if (!drvname && protocol) {
2107 if (filename) {
2108 drv = bdrv_find_protocol(filename, parse_filename, errp);
2109 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002110 return -EINVAL;
2111 }
Max Reitz053e1572015-08-26 19:47:51 +02002112
2113 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05002114 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02002115 } else {
2116 error_setg(errp, "Must specify either driver or file");
2117 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002118 }
2119 }
2120
Kevin Wolf17b005f2014-05-27 10:50:29 +02002121 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02002122
2123 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002124 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002125 drv->bdrv_parse_filename(filename, *options, &local_err);
2126 if (local_err) {
2127 error_propagate(errp, local_err);
2128 return -EINVAL;
2129 }
2130
2131 if (!drv->bdrv_needs_filename) {
2132 qdict_del(*options, "filename");
2133 }
2134 }
2135
2136 return 0;
2137}
2138
Kevin Wolf148eb132017-09-14 14:32:04 +02002139typedef struct BlockReopenQueueEntry {
2140 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01002141 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02002142 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002143 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02002144} BlockReopenQueueEntry;
2145
2146/*
2147 * Return the flags that @bs will have after the reopens in @q have
2148 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2149 * return the current flags.
2150 */
2151static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2152{
2153 BlockReopenQueueEntry *entry;
2154
2155 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002156 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002157 if (entry->state.bs == bs) {
2158 return entry->state.flags;
2159 }
2160 }
2161 }
2162
2163 return bs->open_flags;
2164}
2165
2166/* Returns whether the image file can be written to after the reopen queue @q
2167 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002168static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2169 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002170{
2171 int flags = bdrv_reopen_get_flags(q, bs);
2172
2173 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2174}
2175
Max Reitzcc022142018-06-06 21:37:00 +02002176/*
2177 * Return whether the BDS can be written to. This is not necessarily
2178 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2179 * be written to but do not count as read-only images.
2180 */
2181bool bdrv_is_writable(BlockDriverState *bs)
2182{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05002183 IO_CODE();
Max Reitzcc022142018-06-06 21:37:00 +02002184 return bdrv_is_writable_after_reopen(bs, NULL);
2185}
2186
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002187static char *bdrv_child_user_desc(BdrvChild *c)
2188{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002189 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002190 return c->klass->get_parent_desc(c);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002191}
2192
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002193/*
2194 * Check that @a allows everything that @b needs. @a and @b must reference same
2195 * child node.
2196 */
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002197static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2198{
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002199 const char *child_bs_name;
2200 g_autofree char *a_user = NULL;
2201 g_autofree char *b_user = NULL;
2202 g_autofree char *perms = NULL;
2203
2204 assert(a->bs);
2205 assert(a->bs == b->bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002206 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002207
2208 if ((b->perm & a->shared_perm) == b->perm) {
2209 return true;
2210 }
2211
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002212 child_bs_name = bdrv_get_node_name(b->bs);
2213 a_user = bdrv_child_user_desc(a);
2214 b_user = bdrv_child_user_desc(b);
2215 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2216
2217 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2218 "both required by %s (uses node '%s' as '%s' child) and "
2219 "unshared by %s (uses node '%s' as '%s' child).",
2220 child_bs_name, perms,
2221 b_user, child_bs_name, b->name,
2222 a_user, child_bs_name, a->name);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002223
2224 return false;
2225}
2226
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002227static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002228{
2229 BdrvChild *a, *b;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002230 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002231
2232 /*
2233 * During the loop we'll look at each pair twice. That's correct because
2234 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2235 * directions.
2236 */
2237 QLIST_FOREACH(a, &bs->parents, next_parent) {
2238 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002239 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002240 continue;
2241 }
2242
2243 if (!bdrv_a_allow_b(a, b, errp)) {
2244 return true;
2245 }
2246 }
2247 }
2248
2249 return false;
2250}
2251
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002252static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002253 BdrvChild *c, BdrvChildRole role,
2254 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002255 uint64_t parent_perm, uint64_t parent_shared,
2256 uint64_t *nperm, uint64_t *nshared)
2257{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002258 assert(bs->drv && bs->drv->bdrv_child_perm);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002259 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002260 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002261 parent_perm, parent_shared,
2262 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002263 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002264 if (child_bs && child_bs->force_share) {
2265 *nshared = BLK_PERM_ALL;
2266 }
2267}
2268
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002269/*
2270 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2271 * nodes that are already in the @list, of course) so that final list is
2272 * topologically sorted. Return the result (GSList @list object is updated, so
2273 * don't use old reference after function call).
2274 *
2275 * On function start @list must be already topologically sorted and for any node
2276 * in the @list the whole subtree of the node must be in the @list as well. The
2277 * simplest way to satisfy this criteria: use only result of
2278 * bdrv_topological_dfs() or NULL as @list parameter.
2279 */
2280static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2281 BlockDriverState *bs)
2282{
2283 BdrvChild *child;
2284 g_autoptr(GHashTable) local_found = NULL;
2285
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002286 GLOBAL_STATE_CODE();
2287
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002288 if (!found) {
2289 assert(!list);
2290 found = local_found = g_hash_table_new(NULL, NULL);
2291 }
2292
2293 if (g_hash_table_contains(found, bs)) {
2294 return list;
2295 }
2296 g_hash_table_add(found, bs);
2297
2298 QLIST_FOREACH(child, &bs->children, next) {
2299 list = bdrv_topological_dfs(list, found, child->bs);
2300 }
2301
2302 return g_slist_prepend(list, bs);
2303}
2304
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002305typedef struct BdrvChildSetPermState {
2306 BdrvChild *child;
2307 uint64_t old_perm;
2308 uint64_t old_shared_perm;
2309} BdrvChildSetPermState;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002310
2311static void bdrv_child_set_perm_abort(void *opaque)
2312{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002313 BdrvChildSetPermState *s = opaque;
2314
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002315 GLOBAL_STATE_CODE();
2316
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002317 s->child->perm = s->old_perm;
2318 s->child->shared_perm = s->old_shared_perm;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002319}
2320
2321static TransactionActionDrv bdrv_child_set_pem_drv = {
2322 .abort = bdrv_child_set_perm_abort,
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002323 .clean = g_free,
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002324};
2325
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002326static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2327 uint64_t shared, Transaction *tran)
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002328{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002329 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002330 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002331
2332 *s = (BdrvChildSetPermState) {
2333 .child = c,
2334 .old_perm = c->perm,
2335 .old_shared_perm = c->shared_perm,
2336 };
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002337
2338 c->perm = perm;
2339 c->shared_perm = shared;
2340
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002341 tran_add(tran, &bdrv_child_set_pem_drv, s);
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002342}
2343
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002344static void bdrv_drv_set_perm_commit(void *opaque)
2345{
2346 BlockDriverState *bs = opaque;
2347 uint64_t cumulative_perms, cumulative_shared_perms;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002348 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002349
2350 if (bs->drv->bdrv_set_perm) {
2351 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2352 &cumulative_shared_perms);
2353 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2354 }
2355}
2356
2357static void bdrv_drv_set_perm_abort(void *opaque)
2358{
2359 BlockDriverState *bs = opaque;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002360 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002361
2362 if (bs->drv->bdrv_abort_perm_update) {
2363 bs->drv->bdrv_abort_perm_update(bs);
2364 }
2365}
2366
2367TransactionActionDrv bdrv_drv_set_perm_drv = {
2368 .abort = bdrv_drv_set_perm_abort,
2369 .commit = bdrv_drv_set_perm_commit,
2370};
2371
2372static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2373 uint64_t shared_perm, Transaction *tran,
2374 Error **errp)
2375{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002376 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002377 if (!bs->drv) {
2378 return 0;
2379 }
2380
2381 if (bs->drv->bdrv_check_perm) {
2382 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2383 if (ret < 0) {
2384 return ret;
2385 }
2386 }
2387
2388 if (tran) {
2389 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2390 }
2391
2392 return 0;
2393}
2394
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002395typedef struct BdrvReplaceChildState {
2396 BdrvChild *child;
2397 BlockDriverState *old_bs;
2398} BdrvReplaceChildState;
2399
2400static void bdrv_replace_child_commit(void *opaque)
2401{
2402 BdrvReplaceChildState *s = opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002403 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002404
2405 bdrv_unref(s->old_bs);
2406}
2407
2408static void bdrv_replace_child_abort(void *opaque)
2409{
2410 BdrvReplaceChildState *s = opaque;
2411 BlockDriverState *new_bs = s->child->bs;
2412
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002413 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002414 /* old_bs reference is transparently moved from @s to @s->child */
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03002415 bdrv_replace_child_noperm(s->child, s->old_bs);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002416 bdrv_unref(new_bs);
2417}
2418
2419static TransactionActionDrv bdrv_replace_child_drv = {
2420 .commit = bdrv_replace_child_commit,
2421 .abort = bdrv_replace_child_abort,
2422 .clean = g_free,
2423};
2424
2425/*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002426 * bdrv_replace_child_tran
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002427 *
2428 * Note: real unref of old_bs is done only on commit.
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002429 *
2430 * The function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002431 */
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002432static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002433 Transaction *tran)
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002434{
2435 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2436 *s = (BdrvReplaceChildState) {
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002437 .child = child,
2438 .old_bs = child->bs,
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002439 };
2440 tran_add(tran, &bdrv_replace_child_drv, s);
2441
2442 if (new_bs) {
2443 bdrv_ref(new_bs);
2444 }
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03002445 bdrv_replace_child_noperm(child, new_bs);
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03002446 /* old_bs reference is transparently moved from @child to @s */
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002447}
2448
Kevin Wolf33a610c2016-12-15 13:04:20 +01002449/*
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002450 * Refresh permissions in @bs subtree. The function is intended to be called
2451 * after some graph modification that was done without permission update.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002452 */
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002453static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2454 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002455{
2456 BlockDriver *drv = bs->drv;
2457 BdrvChild *c;
2458 int ret;
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002459 uint64_t cumulative_perms, cumulative_shared_perms;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002460 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002461
2462 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002463
2464 /* Write permissions never work with read-only images */
2465 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002466 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002467 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002468 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2469 error_setg(errp, "Block node is read-only");
2470 } else {
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002471 error_setg(errp, "Read-only block node '%s' cannot support "
2472 "read-write users", bdrv_get_node_name(bs));
Max Reitz481e0ee2019-05-15 22:15:00 +02002473 }
2474
Kevin Wolf33a610c2016-12-15 13:04:20 +01002475 return -EPERM;
2476 }
2477
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002478 /*
2479 * Unaligned requests will automatically be aligned to bl.request_alignment
2480 * and without RESIZE we can't extend requests to write to space beyond the
2481 * end of the image, so it's required that the image size is aligned.
2482 */
2483 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2484 !(cumulative_perms & BLK_PERM_RESIZE))
2485 {
2486 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2487 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2488 "Image size is not a multiple of request "
2489 "alignment");
2490 return -EPERM;
2491 }
2492 }
2493
Kevin Wolf33a610c2016-12-15 13:04:20 +01002494 /* Check this node */
2495 if (!drv) {
2496 return 0;
2497 }
2498
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002499 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002500 errp);
2501 if (ret < 0) {
2502 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002503 }
2504
Kevin Wolf78e421c2016-12-20 23:25:12 +01002505 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002506 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002507 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002508 return 0;
2509 }
2510
2511 /* Check all children */
2512 QLIST_FOREACH(c, &bs->children, next) {
2513 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002514
Max Reitze5d8a402020-05-13 13:05:44 +02002515 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002516 cumulative_perms, cumulative_shared_perms,
2517 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002518 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002519 }
2520
2521 return 0;
2522}
2523
Vladimir Sementsov-Ogievskiy25409802021-04-28 18:18:00 +03002524static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2525 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002526{
2527 int ret;
2528 BlockDriverState *bs;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002529 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002530
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002531 for ( ; list; list = list->next) {
2532 bs = list->data;
2533
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002534 if (bdrv_parent_perms_conflict(bs, errp)) {
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002535 return -EINVAL;
2536 }
2537
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002538 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002539 if (ret < 0) {
2540 return ret;
2541 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002542 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002543
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002544 return 0;
2545}
2546
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002547void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2548 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002549{
2550 BdrvChild *c;
2551 uint64_t cumulative_perms = 0;
2552 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2553
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002554 GLOBAL_STATE_CODE();
2555
Kevin Wolf33a610c2016-12-15 13:04:20 +01002556 QLIST_FOREACH(c, &bs->parents, next_parent) {
2557 cumulative_perms |= c->perm;
2558 cumulative_shared_perms &= c->shared_perm;
2559 }
2560
2561 *perm = cumulative_perms;
2562 *shared_perm = cumulative_shared_perms;
2563}
2564
Fam Zheng51761962017-05-03 00:35:36 +08002565char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002566{
2567 struct perm_name {
2568 uint64_t perm;
2569 const char *name;
2570 } permissions[] = {
2571 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2572 { BLK_PERM_WRITE, "write" },
2573 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2574 { BLK_PERM_RESIZE, "resize" },
Kevin Wolfd0833192017-01-16 18:26:20 +01002575 { 0, NULL }
2576 };
2577
Alberto Garciae2a74232020-01-10 18:15:18 +01002578 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002579 struct perm_name *p;
2580
2581 for (p = permissions; p->name; p++) {
2582 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002583 if (result->len > 0) {
2584 g_string_append(result, ", ");
2585 }
2586 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002587 }
2588 }
2589
Alberto Garciae2a74232020-01-10 18:15:18 +01002590 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002591}
2592
Kevin Wolf33a610c2016-12-15 13:04:20 +01002593
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002594/* @tran is allowed to be NULL. In this case no rollback is possible */
2595static int bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran,
2596 Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002597{
2598 int ret;
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002599 Transaction *local_tran = NULL;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002600 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002601 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002602
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002603 if (!tran) {
2604 tran = local_tran = tran_new();
2605 }
2606
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002607 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002608
2609 if (local_tran) {
2610 tran_finalize(local_tran, ret);
2611 }
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002612
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002613 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002614}
2615
Kevin Wolf33a610c2016-12-15 13:04:20 +01002616int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2617 Error **errp)
2618{
Max Reitz10467792019-05-22 19:03:51 +02002619 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002620 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002621 int ret;
2622
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002623 GLOBAL_STATE_CODE();
2624
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002625 bdrv_child_set_perm(c, perm, shared, tran);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002626
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03002627 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002628
2629 tran_finalize(tran, ret);
2630
Kevin Wolf33a610c2016-12-15 13:04:20 +01002631 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002632 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2633 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002634 error_propagate(errp, local_err);
2635 } else {
2636 /*
2637 * Our caller may intend to only loosen restrictions and
2638 * does not expect this function to fail. Errors are not
2639 * fatal in such a case, so we can just hide them from our
2640 * caller.
2641 */
2642 error_free(local_err);
2643 ret = 0;
2644 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002645 }
2646
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002647 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002648}
2649
Max Reitzc1087f12019-05-22 19:03:46 +02002650int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2651{
2652 uint64_t parent_perms, parent_shared;
2653 uint64_t perms, shared;
2654
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002655 GLOBAL_STATE_CODE();
2656
Max Reitzc1087f12019-05-22 19:03:46 +02002657 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002658 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002659 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002660
2661 return bdrv_child_try_set_perm(c, perms, shared, errp);
2662}
2663
Max Reitz87278af2020-05-13 13:05:40 +02002664/*
2665 * Default implementation for .bdrv_child_perm() for block filters:
2666 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2667 * filtered child.
2668 */
2669static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002670 BdrvChildRole role,
2671 BlockReopenQueue *reopen_queue,
2672 uint64_t perm, uint64_t shared,
2673 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002674{
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002675 GLOBAL_STATE_CODE();
Kevin Wolfe444fa82019-08-02 15:59:41 +02002676 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2677 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002678}
2679
Max Reitz70082db2020-05-13 13:05:26 +02002680static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002681 BdrvChildRole role,
2682 BlockReopenQueue *reopen_queue,
2683 uint64_t perm, uint64_t shared,
2684 uint64_t *nperm, uint64_t *nshared)
2685{
Max Reitze5d8a402020-05-13 13:05:44 +02002686 assert(role & BDRV_CHILD_COW);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002687 GLOBAL_STATE_CODE();
Max Reitz70082db2020-05-13 13:05:26 +02002688
2689 /*
2690 * We want consistent read from backing files if the parent needs it.
2691 * No other operations are performed on backing files.
2692 */
2693 perm &= BLK_PERM_CONSISTENT_READ;
2694
2695 /*
2696 * If the parent can deal with changing data, we're okay with a
2697 * writable and resizable backing file.
2698 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2699 */
2700 if (shared & BLK_PERM_WRITE) {
2701 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2702 } else {
2703 shared = 0;
2704 }
2705
Vladimir Sementsov-Ogievskiy64631f32021-09-02 12:37:54 +03002706 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
Max Reitz70082db2020-05-13 13:05:26 +02002707
2708 if (bs->open_flags & BDRV_O_INACTIVE) {
2709 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2710 }
2711
2712 *nperm = perm;
2713 *nshared = shared;
2714}
2715
Max Reitz6f838a42020-05-13 13:05:27 +02002716static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002717 BdrvChildRole role,
2718 BlockReopenQueue *reopen_queue,
2719 uint64_t perm, uint64_t shared,
2720 uint64_t *nperm, uint64_t *nshared)
2721{
2722 int flags;
2723
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002724 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002725 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002726
2727 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2728
2729 /*
2730 * Apart from the modifications below, the same permissions are
2731 * forwarded and left alone as for filters
2732 */
Max Reitze5d8a402020-05-13 13:05:44 +02002733 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002734 perm, shared, &perm, &shared);
2735
Max Reitzf8890542020-05-13 13:05:28 +02002736 if (role & BDRV_CHILD_METADATA) {
2737 /* Format drivers may touch metadata even if the guest doesn't write */
2738 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2739 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2740 }
2741
2742 /*
2743 * bs->file always needs to be consistent because of the
2744 * metadata. We can never allow other users to resize or write
2745 * to it.
2746 */
2747 if (!(flags & BDRV_O_NO_IO)) {
2748 perm |= BLK_PERM_CONSISTENT_READ;
2749 }
2750 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002751 }
2752
Max Reitzf8890542020-05-13 13:05:28 +02002753 if (role & BDRV_CHILD_DATA) {
2754 /*
2755 * Technically, everything in this block is a subset of the
2756 * BDRV_CHILD_METADATA path taken above, and so this could
2757 * be an "else if" branch. However, that is not obvious, and
2758 * this function is not performance critical, therefore we let
2759 * this be an independent "if".
2760 */
2761
2762 /*
2763 * We cannot allow other users to resize the file because the
2764 * format driver might have some assumptions about the size
2765 * (e.g. because it is stored in metadata, or because the file
2766 * is split into fixed-size data files).
2767 */
2768 shared &= ~BLK_PERM_RESIZE;
2769
2770 /*
2771 * WRITE_UNCHANGED often cannot be performed as such on the
2772 * data file. For example, the qcow2 driver may still need to
2773 * write copied clusters on copy-on-read.
2774 */
2775 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2776 perm |= BLK_PERM_WRITE;
2777 }
2778
2779 /*
2780 * If the data file is written to, the format driver may
2781 * expect to be able to resize it by writing beyond the EOF.
2782 */
2783 if (perm & BLK_PERM_WRITE) {
2784 perm |= BLK_PERM_RESIZE;
2785 }
Max Reitz6f838a42020-05-13 13:05:27 +02002786 }
Max Reitz6f838a42020-05-13 13:05:27 +02002787
2788 if (bs->open_flags & BDRV_O_INACTIVE) {
2789 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2790 }
2791
2792 *nperm = perm;
2793 *nshared = shared;
2794}
2795
Max Reitz2519f542020-05-13 13:05:29 +02002796void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002797 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002798 uint64_t perm, uint64_t shared,
2799 uint64_t *nperm, uint64_t *nshared)
2800{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002801 GLOBAL_STATE_CODE();
Max Reitz2519f542020-05-13 13:05:29 +02002802 if (role & BDRV_CHILD_FILTERED) {
2803 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2804 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002805 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002806 perm, shared, nperm, nshared);
2807 } else if (role & BDRV_CHILD_COW) {
2808 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002809 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002810 perm, shared, nperm, nshared);
2811 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002812 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002813 perm, shared, nperm, nshared);
2814 } else {
2815 g_assert_not_reached();
2816 }
2817}
2818
Max Reitz7b1d9c42019-11-08 13:34:51 +01002819uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2820{
2821 static const uint64_t permissions[] = {
2822 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2823 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2824 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2825 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
Max Reitz7b1d9c42019-11-08 13:34:51 +01002826 };
2827
2828 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2829 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2830
2831 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2832
2833 return permissions[qapi_perm];
2834}
2835
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03002836static void bdrv_replace_child_noperm(BdrvChild *child,
Vladimir Sementsov-Ogievskiy4eba8252022-07-26 23:11:28 +03002837 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002838{
2839 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002840 int new_bs_quiesce_counter;
2841 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002842
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002843 assert(!child->frozen);
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02002844 assert(old_bs != new_bs);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002845 GLOBAL_STATE_CODE();
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002846
Fam Zhengbb2614e2017-04-07 14:54:10 +08002847 if (old_bs && new_bs) {
2848 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2849 }
Max Reitzdebc2922019-07-22 15:33:44 +02002850
2851 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2852 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2853
2854 /*
2855 * If the new child node is drained but the old one was not, flush
2856 * all outstanding requests to the old child node.
2857 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002858 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002859 bdrv_parent_drained_begin_single(child, true);
2860 drain_saldo--;
2861 }
2862
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002863 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002864 /* Detach first so that the recursive drain sections coming from @child
2865 * are already gone and we only end the drain sections that came from
2866 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002867 if (child->klass->detach) {
2868 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002869 }
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002870 assert_bdrv_graph_writable(old_bs);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002871 QLIST_REMOVE(child, next_parent);
2872 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002873
2874 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002875
2876 if (new_bs) {
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002877 assert_bdrv_graph_writable(new_bs);
Kevin Wolf36fe1332016-05-17 14:51:55 +02002878 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002879
2880 /*
2881 * Detaching the old node may have led to the new node's
2882 * quiesce_counter having been decreased. Not a problem, we
2883 * just need to recognize this here and then invoke
2884 * drained_end appropriately more often.
2885 */
2886 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2887 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002888
Kevin Wolfd736f112017-12-18 16:05:48 +01002889 /* Attach only after starting new drained sections, so that recursive
2890 * drain sections coming from @child don't get an extra .drained_begin
2891 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002892 if (child->klass->attach) {
2893 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002894 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002895 }
Max Reitzdebc2922019-07-22 15:33:44 +02002896
2897 /*
2898 * If the old child node was drained but the new one is not, allow
2899 * requests to come in only after the new node has been attached.
2900 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002901 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002902 bdrv_parent_drained_end_single(child);
2903 drain_saldo++;
2904 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002905}
2906
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002907/**
2908 * Free the given @child.
2909 *
2910 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2911 * unused (i.e. not in a children list).
2912 */
2913static void bdrv_child_free(BdrvChild *child)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002914{
2915 assert(!child->bs);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002916 GLOBAL_STATE_CODE();
Hanna Reitza2253692021-11-15 15:53:58 +01002917 assert(!child->next.le_prev); /* not in children list */
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002918
2919 g_free(child->name);
2920 g_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002921}
2922
2923typedef struct BdrvAttachChildCommonState {
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002924 BdrvChild *child;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002925 AioContext *old_parent_ctx;
2926 AioContext *old_child_ctx;
2927} BdrvAttachChildCommonState;
2928
2929static void bdrv_attach_child_common_abort(void *opaque)
2930{
2931 BdrvAttachChildCommonState *s = opaque;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002932 BlockDriverState *bs = s->child->bs;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002933
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002934 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002935 bdrv_replace_child_noperm(s->child, NULL);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002936
2937 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
Emanuele Giuseppe Esposito142e6902022-10-25 04:49:52 -04002938 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002939 }
2940
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002941 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04002942 Transaction *tran;
2943 GHashTable *visited;
2944 bool ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002945
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04002946 tran = tran_new();
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002947
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04002948 /* No need to visit `child`, because it has been detached already */
2949 visited = g_hash_table_new(NULL, NULL);
2950 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2951 visited, tran, &error_abort);
2952 g_hash_table_destroy(visited);
2953
2954 /* transaction is supposed to always succeed */
2955 assert(ret == true);
2956 tran_commit(tran);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002957 }
2958
2959 bdrv_unref(bs);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002960 bdrv_child_free(s->child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002961}
2962
2963static TransactionActionDrv bdrv_attach_child_common_drv = {
2964 .abort = bdrv_attach_child_common_abort,
2965 .clean = g_free,
2966};
2967
2968/*
2969 * Common part of attaching bdrv child to bs or to blk or to job
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002970 *
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002971 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002972 *
2973 * Returns new created child.
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002974 */
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03002975static BdrvChild *bdrv_attach_child_common(BlockDriverState *child_bs,
2976 const char *child_name,
2977 const BdrvChildClass *child_class,
2978 BdrvChildRole child_role,
2979 uint64_t perm, uint64_t shared_perm,
2980 void *opaque,
2981 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002982{
2983 BdrvChild *new_child;
2984 AioContext *parent_ctx;
2985 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2986
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002987 assert(child_class->get_parent_desc);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002988 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002989
2990 new_child = g_new(BdrvChild, 1);
2991 *new_child = (BdrvChild) {
2992 .bs = NULL,
2993 .name = g_strdup(child_name),
2994 .klass = child_class,
2995 .role = child_role,
2996 .perm = perm,
2997 .shared_perm = shared_perm,
2998 .opaque = opaque,
2999 };
3000
3001 /*
3002 * If the AioContexts don't match, first try to move the subtree of
3003 * child_bs into the AioContext of the new parent. If this doesn't work,
3004 * try moving the parent into the AioContext of child_bs instead.
3005 */
3006 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3007 if (child_ctx != parent_ctx) {
3008 Error *local_err = NULL;
Emanuele Giuseppe Esposito142e6902022-10-25 04:49:52 -04003009 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3010 &local_err);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003011
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04003012 if (ret < 0 && child_class->change_aio_ctx) {
3013 Transaction *tran = tran_new();
3014 GHashTable *visited = g_hash_table_new(NULL, NULL);
3015 bool ret_child;
3016
3017 g_hash_table_add(visited, new_child);
3018 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3019 visited, tran, NULL);
3020 if (ret_child == true) {
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003021 error_free(local_err);
3022 ret = 0;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003023 }
Emanuele Giuseppe Espositof8be48a2022-10-25 04:49:49 -04003024 tran_finalize(tran, ret_child == true ? 0 : -1);
3025 g_hash_table_destroy(visited);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003026 }
3027
3028 if (ret < 0) {
3029 error_propagate(errp, local_err);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01003030 bdrv_child_free(new_child);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003031 return NULL;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003032 }
3033 }
3034
3035 bdrv_ref(child_bs);
Vladimir Sementsov-Ogievskiy544acc72022-07-26 23:11:31 +03003036 bdrv_replace_child_noperm(new_child, child_bs);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003037
3038 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3039 *s = (BdrvAttachChildCommonState) {
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003040 .child = new_child,
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003041 .old_parent_ctx = parent_ctx,
3042 .old_child_ctx = child_ctx,
3043 };
3044 tran_add(tran, &bdrv_attach_child_common_drv, s);
3045
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003046 return new_child;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003047}
3048
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003049/*
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003050 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003051 */
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003052static BdrvChild *bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3053 BlockDriverState *child_bs,
3054 const char *child_name,
3055 const BdrvChildClass *child_class,
3056 BdrvChildRole child_role,
3057 Transaction *tran,
3058 Error **errp)
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003059{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003060 uint64_t perm, shared_perm;
3061
3062 assert(parent_bs->drv);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003063 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003064
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02003065 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3066 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3067 child_bs->node_name, child_name, parent_bs->node_name);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003068 return NULL;
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02003069 }
3070
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003071 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3072 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3073 perm, shared_perm, &perm, &shared_perm);
3074
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003075 return bdrv_attach_child_common(child_bs, child_name, child_class,
3076 child_role, perm, shared_perm, parent_bs,
3077 tran, errp);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003078}
3079
Alberto Garciab441dc72019-05-13 16:46:18 +03003080/*
3081 * This function steals the reference to child_bs from the caller.
3082 * That reference is later dropped by bdrv_root_unref_child().
3083 *
3084 * On failure NULL is returned, errp is set and the reference to
3085 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003086 *
3087 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3088 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003089 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003090BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3091 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003092 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003093 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003094 uint64_t perm, uint64_t shared_perm,
3095 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003096{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003097 int ret;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003098 BdrvChild *child;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003099 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003100
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05003101 GLOBAL_STATE_CODE();
3102
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003103 child = bdrv_attach_child_common(child_bs, child_name, child_class,
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003104 child_role, perm, shared_perm, opaque,
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003105 tran, errp);
3106 if (!child) {
3107 ret = -EINVAL;
Kevin Wolfe878bb12021-05-03 13:05:54 +02003108 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003109 }
3110
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003111 ret = bdrv_refresh_perms(child_bs, tran, errp);
Kevin Wolfdf581792015-06-15 11:53:47 +02003112
Kevin Wolfe878bb12021-05-03 13:05:54 +02003113out:
3114 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003115
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003116 bdrv_unref(child_bs);
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003117
3118 return ret < 0 ? NULL : child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003119}
3120
Alberto Garciab441dc72019-05-13 16:46:18 +03003121/*
3122 * This function transfers the reference to child_bs from the caller
3123 * to parent_bs. That reference is later dropped by parent_bs on
3124 * bdrv_close() or if someone calls bdrv_unref_child().
3125 *
3126 * On failure NULL is returned, errp is set and the reference to
3127 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003128 *
3129 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3130 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003131 */
Wen Congyang98292c62016-05-10 15:36:38 +08003132BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3133 BlockDriverState *child_bs,
3134 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003135 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003136 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003137 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003138{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003139 int ret;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003140 BdrvChild *child;
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003141 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003142
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003143 GLOBAL_STATE_CODE();
3144
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003145 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3146 child_class, child_role, tran, errp);
3147 if (!child) {
3148 ret = -EINVAL;
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003149 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003150 }
3151
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003152 ret = bdrv_refresh_perms(parent_bs, tran, errp);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003153 if (ret < 0) {
3154 goto out;
3155 }
3156
3157out:
3158 tran_finalize(tran, ret);
3159
3160 bdrv_unref(child_bs);
3161
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003162 return ret < 0 ? NULL : child;
Kevin Wolff21d96d2016-03-08 13:47:46 +01003163}
3164
Max Reitz7b99a262019-06-12 16:07:11 +02003165/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003166void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003167{
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003168 BlockDriverState *child_bs = child->bs;
Kevin Wolf779020c2015-10-13 14:09:44 +02003169
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003170 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003171 bdrv_replace_child_noperm(child, NULL);
3172 bdrv_child_free(child);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003173
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003174 if (child_bs) {
3175 /*
3176 * Update permissions for old node. We're just taking a parent away, so
3177 * we're loosening restrictions. Errors of permission update are not
3178 * fatal in this case, ignore them.
3179 */
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003180 bdrv_refresh_perms(child_bs, NULL, NULL);
Vladimir Sementsov-Ogievskiy00eb93b2022-11-07 19:35:55 +03003181
3182 /*
3183 * When the parent requiring a non-default AioContext is removed, the
3184 * node moves back to the main AioContext
3185 */
3186 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3187 NULL);
3188 }
3189
Kevin Wolff21d96d2016-03-08 13:47:46 +01003190 bdrv_unref(child_bs);
3191}
3192
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003193typedef struct BdrvSetInheritsFrom {
3194 BlockDriverState *bs;
3195 BlockDriverState *old_inherits_from;
3196} BdrvSetInheritsFrom;
3197
3198static void bdrv_set_inherits_from_abort(void *opaque)
3199{
3200 BdrvSetInheritsFrom *s = opaque;
3201
3202 s->bs->inherits_from = s->old_inherits_from;
3203}
3204
3205static TransactionActionDrv bdrv_set_inherits_from_drv = {
3206 .abort = bdrv_set_inherits_from_abort,
3207 .clean = g_free,
3208};
3209
3210/* @tran is allowed to be NULL. In this case no rollback is possible */
3211static void bdrv_set_inherits_from(BlockDriverState *bs,
3212 BlockDriverState *new_inherits_from,
3213 Transaction *tran)
3214{
3215 if (tran) {
3216 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3217
3218 *s = (BdrvSetInheritsFrom) {
3219 .bs = bs,
3220 .old_inherits_from = bs->inherits_from,
3221 };
3222
3223 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3224 }
3225
3226 bs->inherits_from = new_inherits_from;
3227}
3228
Max Reitz3cf746b2019-07-03 19:28:07 +02003229/**
3230 * Clear all inherits_from pointers from children and grandchildren of
3231 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003232 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003233 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003234static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3235 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003236{
Max Reitz3cf746b2019-07-03 19:28:07 +02003237 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003238
Max Reitz3cf746b2019-07-03 19:28:07 +02003239 if (child->bs->inherits_from == root) {
3240 /*
3241 * Remove inherits_from only when the last reference between root and
3242 * child->bs goes away.
3243 */
3244 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003245 if (c != child && c->bs == child->bs) {
3246 break;
3247 }
3248 }
3249 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003250 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003251 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003252 }
3253
Max Reitz3cf746b2019-07-03 19:28:07 +02003254 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003255 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003256 }
3257}
3258
Max Reitz7b99a262019-06-12 16:07:11 +02003259/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003260void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3261{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003262 GLOBAL_STATE_CODE();
Max Reitz3cf746b2019-07-03 19:28:07 +02003263 if (child == NULL) {
3264 return;
3265 }
3266
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003267 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003268 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003269}
3270
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003271
3272static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3273{
3274 BdrvChild *c;
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003275 GLOBAL_STATE_CODE();
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003276 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003277 if (c->klass->change_media) {
3278 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003279 }
3280 }
3281}
3282
Alberto Garcia0065c452018-10-31 18:16:37 +02003283/* Return true if you can reach parent going through child->inherits_from
3284 * recursively. If parent or child are NULL, return false */
3285static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3286 BlockDriverState *parent)
3287{
3288 while (child && child != parent) {
3289 child = child->inherits_from;
3290 }
3291
3292 return child != NULL;
3293}
3294
Kevin Wolf5db15a52015-09-14 15:33:33 +02003295/*
Max Reitz25191e52020-05-13 13:05:33 +02003296 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3297 * mostly used for COW backing children (role = COW), but also for
3298 * filtered children (role = FILTERED | PRIMARY).
3299 */
3300static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3301{
3302 if (bs->drv && bs->drv->is_filter) {
3303 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3304 } else {
3305 return BDRV_CHILD_COW;
3306 }
3307}
3308
3309/*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003310 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3311 * callers which don't need their own reference any more must call bdrv_unref().
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003312 *
3313 * Function doesn't update permissions, caller is responsible for this.
Kevin Wolf5db15a52015-09-14 15:33:33 +02003314 */
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003315static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3316 BlockDriverState *child_bs,
3317 bool is_backing,
3318 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003319{
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003320 bool update_inherits_from =
3321 bdrv_inherits_from_recursive(child_bs, parent_bs);
3322 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3323 BdrvChildRole role;
Alberto Garcia0065c452018-10-31 18:16:37 +02003324
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003325 GLOBAL_STATE_CODE();
3326
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003327 if (!parent_bs->drv) {
3328 /*
3329 * Node without drv is an object without a class :/. TODO: finally fix
3330 * qcow2 driver to never clear bs->drv and implement format corruption
3331 * handling in other way.
3332 */
3333 error_setg(errp, "Node corrupted");
3334 return -EINVAL;
3335 }
3336
3337 if (child && child->frozen) {
3338 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3339 child->name, parent_bs->node_name, child->bs->node_name);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003340 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003341 }
3342
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03003343 if (is_backing && !parent_bs->drv->is_filter &&
3344 !parent_bs->drv->supports_backing)
3345 {
3346 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3347 "files", parent_bs->drv->format_name, parent_bs->node_name);
3348 return -EINVAL;
3349 }
3350
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003351 if (parent_bs->drv->is_filter) {
3352 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3353 } else if (is_backing) {
3354 role = BDRV_CHILD_COW;
3355 } else {
3356 /*
3357 * We only can use same role as it is in existing child. We don't have
3358 * infrastructure to determine role of file child in generic way
3359 */
3360 if (!child) {
3361 error_setg(errp, "Cannot set file child to format node without "
3362 "file child");
3363 return -EINVAL;
3364 }
3365 role = child->role;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003366 }
3367
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003368 if (child) {
3369 bdrv_unset_inherits_from(parent_bs, child, tran);
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03003370 bdrv_remove_child(child, tran);
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003371 }
3372
3373 if (!child_bs) {
Fam Zheng8d24cce2014-05-23 21:29:45 +08003374 goto out;
3375 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003376
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003377 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3378 is_backing ? "backing" : "file",
3379 &child_of_bds, role,
3380 tran, errp);
3381 if (!child) {
3382 return -EINVAL;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003383 }
3384
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003385
3386 /*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003387 * If inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003388 * point directly to bs (else it will become NULL).
3389 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003390 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003391 bdrv_set_inherits_from(child_bs, parent_bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003392 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003393
Fam Zheng8d24cce2014-05-23 21:29:45 +08003394out:
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003395 bdrv_refresh_limits(parent_bs, tran, NULL);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003396
3397 return 0;
3398}
3399
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003400static int bdrv_set_backing_noperm(BlockDriverState *bs,
3401 BlockDriverState *backing_hd,
3402 Transaction *tran, Error **errp)
3403{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003404 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003405 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3406}
3407
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003408int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3409 Error **errp)
3410{
3411 int ret;
3412 Transaction *tran = tran_new();
3413
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003414 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003415 bdrv_drained_begin(bs);
3416
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003417 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3418 if (ret < 0) {
3419 goto out;
3420 }
3421
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03003422 ret = bdrv_refresh_perms(bs, tran, errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003423out:
3424 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003425
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003426 bdrv_drained_end(bs);
3427
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003428 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003429}
3430
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003431/*
3432 * Opens the backing file for a BlockDriverState if not yet open
3433 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003434 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3435 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3436 * itself, all options starting with "${bdref_key}." are considered part of the
3437 * BlockdevRef.
3438 *
3439 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003440 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003441int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3442 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003443{
Max Reitz6b6833c2019-02-01 20:29:15 +01003444 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003445 char *bdref_key_dot;
3446 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003447 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003448 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003449 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003450 QDict *options;
3451 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003452 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003453
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003454 GLOBAL_STATE_CODE();
3455
Kevin Wolf760e0062015-06-17 14:55:21 +02003456 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003457 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003458 }
3459
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003460 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003461 if (parent_options == NULL) {
3462 tmp_parent_options = qdict_new();
3463 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003464 }
3465
Paolo Bonzini9156df12012-10-18 16:49:17 +02003466 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003467
3468 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3469 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3470 g_free(bdref_key_dot);
3471
Markus Armbruster129c7d12017-03-30 19:43:12 +02003472 /*
3473 * Caution: while qdict_get_try_str() is fine, getting non-string
3474 * types would require more care. When @parent_options come from
3475 * -blockdev or blockdev_add, its members are typed according to
3476 * the QAPI schema, but when they come from -drive, they're all
3477 * QString.
3478 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003479 reference = qdict_get_try_str(parent_options, bdref_key);
3480 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003481 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003482 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003483 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003484 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003485 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003486 if (qdict_size(options) == 0) {
3487 /* If the user specifies options that do not modify the
3488 * backing file's behavior, we might still consider it the
3489 * implicit backing file. But it's easier this way, and
3490 * just specifying some of the backing BDS's options is
3491 * only possible with -drive anyway (otherwise the QAPI
3492 * schema forces the user to specify everything). */
3493 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3494 }
3495
Max Reitz6b6833c2019-02-01 20:29:15 +01003496 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003497 if (local_err) {
3498 ret = -EINVAL;
3499 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003500 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003501 goto free_exit;
3502 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003503 }
3504
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003505 if (!bs->drv || !bs->drv->supports_backing) {
3506 ret = -EINVAL;
3507 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003508 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003509 goto free_exit;
3510 }
3511
Peter Krempa6bff5972017-10-12 16:14:10 +02003512 if (!reference &&
3513 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003514 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003515 }
3516
Max Reitz6b6833c2019-02-01 20:29:15 +01003517 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003518 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003519 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003520 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003521 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003522 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003523 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003524 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003525
Max Reitz998c2012019-02-01 20:29:08 +01003526 if (implicit_backing) {
3527 bdrv_refresh_filename(backing_hd);
3528 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3529 backing_hd->filename);
3530 }
3531
Kevin Wolf5db15a52015-09-14 15:33:33 +02003532 /* Hook up the backing file link; drop our reference, bs owns the
3533 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003534 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003535 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003536 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003537 goto free_exit;
3538 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003539
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003540 qdict_del(parent_options, bdref_key);
3541
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003542free_exit:
3543 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003544 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003545 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003546}
3547
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003548static BlockDriverState *
3549bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003550 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003551 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003552{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003553 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003554 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003555 char *bdref_key_dot;
3556 const char *reference;
3557
Max Reitzbd86fb92020-05-13 13:05:13 +02003558 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003559
Max Reitzda557aa2013-12-20 19:28:11 +01003560 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3561 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3562 g_free(bdref_key_dot);
3563
Markus Armbruster129c7d12017-03-30 19:43:12 +02003564 /*
3565 * Caution: while qdict_get_try_str() is fine, getting non-string
3566 * types would require more care. When @options come from
3567 * -blockdev or blockdev_add, its members are typed according to
3568 * the QAPI schema, but when they come from -drive, they're all
3569 * QString.
3570 */
Max Reitzda557aa2013-12-20 19:28:11 +01003571 reference = qdict_get_try_str(options, bdref_key);
3572 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003573 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003574 error_setg(errp, "A block device must be specified for \"%s\"",
3575 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003576 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003577 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003578 goto done;
3579 }
3580
Max Reitz5b363932016-05-17 16:41:31 +02003581 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003582 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003583 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003584 goto done;
3585 }
3586
Max Reitzda557aa2013-12-20 19:28:11 +01003587done:
3588 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003589 return bs;
3590}
3591
3592/*
3593 * Opens a disk image whose options are given as BlockdevRef in another block
3594 * device's options.
3595 *
3596 * If allow_none is true, no image will be opened if filename is false and no
3597 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3598 *
3599 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3600 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3601 * itself, all options starting with "${bdref_key}." are considered part of the
3602 * BlockdevRef.
3603 *
3604 * The BlockdevRef will be removed from the options QDict.
3605 */
3606BdrvChild *bdrv_open_child(const char *filename,
3607 QDict *options, const char *bdref_key,
3608 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003609 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003610 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003611 bool allow_none, Error **errp)
3612{
3613 BlockDriverState *bs;
3614
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003615 GLOBAL_STATE_CODE();
3616
Max Reitzbd86fb92020-05-13 13:05:13 +02003617 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003618 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003619 if (bs == NULL) {
3620 return NULL;
3621 }
3622
Max Reitz258b7762020-05-13 13:05:15 +02003623 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3624 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003625}
3626
Max Reitzbd86fb92020-05-13 13:05:13 +02003627/*
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003628 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3629 */
3630int bdrv_open_file_child(const char *filename,
3631 QDict *options, const char *bdref_key,
3632 BlockDriverState *parent, Error **errp)
3633{
3634 BdrvChildRole role;
3635
3636 /* commit_top and mirror_top don't use this function */
3637 assert(!parent->drv->filtered_child_is_backing);
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003638 role = parent->drv->is_filter ?
3639 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3640
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003641 if (!bdrv_open_child(filename, options, bdref_key, parent,
3642 &child_of_bds, role, false, errp))
3643 {
3644 return -EINVAL;
3645 }
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003646
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03003647 return 0;
Vladimir Sementsov-Ogievskiy83930782022-07-26 23:11:21 +03003648}
3649
3650/*
Max Reitzbd86fb92020-05-13 13:05:13 +02003651 * TODO Future callers may need to specify parent/child_class in order for
3652 * option inheritance to work. Existing callers use it for the root node.
3653 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003654BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3655{
3656 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003657 QObject *obj = NULL;
3658 QDict *qdict = NULL;
3659 const char *reference = NULL;
3660 Visitor *v = NULL;
3661
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003662 GLOBAL_STATE_CODE();
3663
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003664 if (ref->type == QTYPE_QSTRING) {
3665 reference = ref->u.reference;
3666 } else {
3667 BlockdevOptions *options = &ref->u.definition;
3668 assert(ref->type == QTYPE_QDICT);
3669
3670 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003671 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003672 visit_complete(v, &obj);
3673
Max Reitz7dc847e2018-02-24 16:40:29 +01003674 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003675 qdict_flatten(qdict);
3676
3677 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3678 * compatibility with other callers) rather than what we want as the
3679 * real defaults. Apply the defaults here instead. */
3680 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3681 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3682 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003683 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3684
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003685 }
3686
Max Reitz272c02e2020-05-13 13:05:17 +02003687 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003688 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003689 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003690 visit_free(v);
3691 return bs;
3692}
3693
Max Reitz66836182016-05-17 16:41:27 +02003694static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3695 int flags,
3696 QDict *snapshot_options,
3697 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003698{
Bin Meng69fbfff2022-10-10 12:04:31 +08003699 g_autofree char *tmp_filename = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003700 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003701 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003702 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003703 int ret;
3704
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003705 GLOBAL_STATE_CODE();
3706
Kevin Wolfb9988752014-04-03 12:09:34 +02003707 /* if snapshot, we create a temporary backing file and open it
3708 instead of opening 'filename' directly */
3709
3710 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003711 total_size = bdrv_getlength(bs);
3712 if (total_size < 0) {
3713 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003714 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003715 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003716
3717 /* Create the temporary image */
Bin Meng69fbfff2022-10-10 12:04:31 +08003718 tmp_filename = create_tmp_file(errp);
3719 if (!tmp_filename) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003720 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003721 }
3722
Max Reitzef810432014-12-02 18:32:42 +01003723 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003724 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003725 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003726 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003727 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003728 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003729 error_prepend(errp, "Could not create temporary overlay '%s': ",
3730 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003731 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003732 }
3733
Kevin Wolf73176be2016-03-07 13:02:15 +01003734 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003735 qdict_put_str(snapshot_options, "file.driver", "file");
3736 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3737 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003738
Max Reitz5b363932016-05-17 16:41:31 +02003739 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003740 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003741 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003742 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003743 }
3744
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003745 ret = bdrv_append(bs_snapshot, bs, errp);
3746 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003747 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003748 goto out;
3749 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003750
3751out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003752 qobject_unref(snapshot_options);
Eric Blakeff6ed712017-04-27 16:58:18 -05003753 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003754}
3755
Max Reitzda557aa2013-12-20 19:28:11 +01003756/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003757 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003758 *
3759 * options is a QDict of options to pass to the block drivers, or NULL for an
3760 * empty set of options. The reference to the QDict belongs to the block layer
3761 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003762 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003763 *
3764 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3765 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003766 *
3767 * The reference parameter may be used to specify an existing block device which
3768 * should be opened. If specified, neither options nor a filename may be given,
3769 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003770 */
Max Reitz5b363932016-05-17 16:41:31 +02003771static BlockDriverState *bdrv_open_inherit(const char *filename,
3772 const char *reference,
3773 QDict *options, int flags,
3774 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003775 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003776 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003777 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003778{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003779 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003780 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003781 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003782 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003783 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003784 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003785 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003786 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003787 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003788 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003789
Max Reitzbd86fb92020-05-13 13:05:13 +02003790 assert(!child_class || !flags);
3791 assert(!child_class == !parent);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003792 GLOBAL_STATE_CODE();
Max Reitzf67503e2014-02-18 18:33:05 +01003793
Max Reitzddf56362014-02-18 18:33:06 +01003794 if (reference) {
3795 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003796 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003797
Max Reitzddf56362014-02-18 18:33:06 +01003798 if (filename || options_non_empty) {
3799 error_setg(errp, "Cannot reference an existing block device with "
3800 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003801 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003802 }
3803
3804 bs = bdrv_lookup_bs(reference, reference, errp);
3805 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003806 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003807 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003808
Max Reitzddf56362014-02-18 18:33:06 +01003809 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003810 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003811 }
3812
Max Reitz5b363932016-05-17 16:41:31 +02003813 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003814
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003815 /* NULL means an empty set of options */
3816 if (options == NULL) {
3817 options = qdict_new();
3818 }
3819
Kevin Wolf145f5982015-05-08 16:15:03 +02003820 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003821 parse_json_protocol(options, &filename, &local_err);
3822 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003823 goto fail;
3824 }
3825
Kevin Wolf145f5982015-05-08 16:15:03 +02003826 bs->explicit_options = qdict_clone_shallow(options);
3827
Max Reitzbd86fb92020-05-13 13:05:13 +02003828 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003829 bool parent_is_format;
3830
3831 if (parent->drv) {
3832 parent_is_format = parent->drv->is_format;
3833 } else {
3834 /*
3835 * parent->drv is not set yet because this node is opened for
3836 * (potential) format probing. That means that @parent is going
3837 * to be a format node.
3838 */
3839 parent_is_format = true;
3840 }
3841
Kevin Wolfbddcec32015-04-09 18:47:50 +02003842 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003843 child_class->inherit_options(child_role, parent_is_format,
3844 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003845 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003846 }
3847
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003848 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003849 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003850 goto fail;
3851 }
3852
Markus Armbruster129c7d12017-03-30 19:43:12 +02003853 /*
3854 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3855 * Caution: getting a boolean member of @options requires care.
3856 * When @options come from -blockdev or blockdev_add, members are
3857 * typed according to the QAPI schema, but when they come from
3858 * -drive, they're all QString.
3859 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003860 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3861 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3862 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3863 } else {
3864 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003865 }
3866
3867 if (flags & BDRV_O_SNAPSHOT) {
3868 snapshot_options = qdict_new();
3869 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3870 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003871 /* Let bdrv_backing_options() override "read-only" */
3872 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003873 bdrv_inherited_options(BDRV_CHILD_COW, true,
3874 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003875 }
3876
Kevin Wolf62392eb2015-04-24 16:38:02 +02003877 bs->open_flags = flags;
3878 bs->options = options;
3879 options = qdict_clone_shallow(options);
3880
Kevin Wolf76c591b2014-06-04 14:19:44 +02003881 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003882 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003883 drvname = qdict_get_try_str(options, "driver");
3884 if (drvname) {
3885 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003886 if (!drv) {
3887 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003888 goto fail;
3889 }
3890 }
3891
3892 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003893
Markus Armbruster129c7d12017-03-30 19:43:12 +02003894 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003895 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003896 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3897 (backing && *backing == '\0'))
3898 {
Max Reitz4f7be282018-02-24 16:40:33 +01003899 if (backing) {
3900 warn_report("Use of \"backing\": \"\" is deprecated; "
3901 "use \"backing\": null instead");
3902 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003903 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003904 qdict_del(bs->explicit_options, "backing");
3905 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003906 qdict_del(options, "backing");
3907 }
3908
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003909 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003910 * probing, the block drivers will do their own bdrv_open_child() for the
3911 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003912 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003913 BlockDriverState *file_bs;
3914
3915 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003916 &child_of_bds, BDRV_CHILD_IMAGE,
3917 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003918 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003919 goto fail;
3920 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003921 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003922 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3923 * looking at the header to guess the image format. This works even
3924 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003925 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003926 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003927 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003928 if (local_err) {
3929 goto fail;
3930 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003931
Eric Blake46f5ac22017-04-27 16:58:17 -05003932 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003933 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003934 }
3935
Kevin Wolf76c591b2014-06-04 14:19:44 +02003936 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003937 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003938 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003939 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003940 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003941 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003942 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003943 /*
3944 * This option update would logically belong in bdrv_fill_options(),
3945 * but we first need to open bs->file for the probing to work, while
3946 * opening bs->file already requires the (mostly) final set of options
3947 * so that cache mode etc. can be inherited.
3948 *
3949 * Adding the driver later is somewhat ugly, but it's not an option
3950 * that would ever be inherited, so it's correct. We just need to make
3951 * sure to update both bs->options (which has the full effective
3952 * options for bs) and options (which has file.* already removed).
3953 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003954 qdict_put_str(bs->options, "driver", drv->format_name);
3955 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003956 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003957 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003958 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003959 }
3960
Max Reitz53a29512015-03-19 14:53:16 -04003961 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3962 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3963 /* file must be NULL if a protocol BDS is about to be created
3964 * (the inverse results in an error message from bdrv_open_common()) */
3965 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3966
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003967 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003968 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003969 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003970 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003971 }
3972
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003973 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003974 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003975 file = NULL;
3976 }
3977
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003978 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003979 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003980 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003981 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003982 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003983 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003984 }
3985
Alberto Garcia50196d72018-09-06 12:37:03 +03003986 /* Remove all children options and references
3987 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003988 QLIST_FOREACH(child, &bs->children, next) {
3989 char *child_key_dot;
3990 child_key_dot = g_strdup_printf("%s.", child->name);
3991 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3992 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003993 qdict_del(bs->explicit_options, child->name);
3994 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003995 g_free(child_key_dot);
3996 }
3997
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003998 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003999 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004000 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01004001 if (flags & BDRV_O_PROTOCOL) {
4002 error_setg(errp, "Block protocol '%s' doesn't support the option "
4003 "'%s'", drv->format_name, entry->key);
4004 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01004005 error_setg(errp,
4006 "Block format '%s' does not support the option '%s'",
4007 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01004008 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004009
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004010 goto close_and_fail;
4011 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004012
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01004013 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004014
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004015 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03004016 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004017
4018 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4019 * temporary snapshot afterwards. */
4020 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02004021 BlockDriverState *snapshot_bs;
4022 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4023 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01004024 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004025 if (local_err) {
4026 goto close_and_fail;
4027 }
Max Reitz5b363932016-05-17 16:41:31 +02004028 /* We are not going to return bs but the overlay on top of it
4029 * (snapshot_bs); thus, we have to drop the strong reference to bs
4030 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4031 * though, because the overlay still has a reference to it. */
4032 bdrv_unref(bs);
4033 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02004034 }
4035
Max Reitz5b363932016-05-17 16:41:31 +02004036 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004037
Kevin Wolf8bfea152014-04-11 19:16:36 +02004038fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01004039 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004040 qobject_unref(snapshot_options);
4041 qobject_unref(bs->explicit_options);
4042 qobject_unref(bs->options);
4043 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004044 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03004045 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02004046 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004047 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004048 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004049
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004050close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02004051 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004052 qobject_unref(snapshot_options);
4053 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004054 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004055 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004056}
4057
Max Reitz5b363932016-05-17 16:41:31 +02004058BlockDriverState *bdrv_open(const char *filename, const char *reference,
4059 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02004060{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004061 GLOBAL_STATE_CODE();
4062
Max Reitz5b363932016-05-17 16:41:31 +02004063 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02004064 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02004065}
4066
Alberto Garciafaf116b2019-03-12 18:48:49 +02004067/* Return true if the NULL-terminated @list contains @str */
4068static bool is_str_in_list(const char *str, const char *const *list)
4069{
4070 if (str && list) {
4071 int i;
4072 for (i = 0; list[i] != NULL; i++) {
4073 if (!strcmp(str, list[i])) {
4074 return true;
4075 }
4076 }
4077 }
4078 return false;
4079}
4080
4081/*
4082 * Check that every option set in @bs->options is also set in
4083 * @new_opts.
4084 *
4085 * Options listed in the common_options list and in
4086 * @bs->drv->mutable_opts are skipped.
4087 *
4088 * Return 0 on success, otherwise return -EINVAL and set @errp.
4089 */
4090static int bdrv_reset_options_allowed(BlockDriverState *bs,
4091 const QDict *new_opts, Error **errp)
4092{
4093 const QDictEntry *e;
4094 /* These options are common to all block drivers and are handled
4095 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4096 const char *const common_options[] = {
4097 "node-name", "discard", "cache.direct", "cache.no-flush",
4098 "read-only", "auto-read-only", "detect-zeroes", NULL
4099 };
4100
4101 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4102 if (!qdict_haskey(new_opts, e->key) &&
4103 !is_str_in_list(e->key, common_options) &&
4104 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4105 error_setg(errp, "Option '%s' cannot be reset "
4106 "to its default value", e->key);
4107 return -EINVAL;
4108 }
4109 }
4110
4111 return 0;
4112}
4113
Jeff Codye971aa12012-09-20 15:13:19 -04004114/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004115 * Returns true if @child can be reached recursively from @bs
4116 */
4117static bool bdrv_recurse_has_child(BlockDriverState *bs,
4118 BlockDriverState *child)
4119{
4120 BdrvChild *c;
4121
4122 if (bs == child) {
4123 return true;
4124 }
4125
4126 QLIST_FOREACH(c, &bs->children, next) {
4127 if (bdrv_recurse_has_child(c->bs, child)) {
4128 return true;
4129 }
4130 }
4131
4132 return false;
4133}
4134
4135/*
Jeff Codye971aa12012-09-20 15:13:19 -04004136 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4137 * reopen of multiple devices.
4138 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004139 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04004140 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4141 * be created and initialized. This newly created BlockReopenQueue should be
4142 * passed back in for subsequent calls that are intended to be of the same
4143 * atomic 'set'.
4144 *
4145 * bs is the BlockDriverState to add to the reopen queue.
4146 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004147 * options contains the changed options for the associated bs
4148 * (the BlockReopenQueue takes ownership)
4149 *
Jeff Codye971aa12012-09-20 15:13:19 -04004150 * flags contains the open flags for the associated bs
4151 *
4152 * returns a pointer to bs_queue, which is either the newly allocated
4153 * bs_queue, or the existing bs_queue being used.
4154 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004155 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004156 */
Kevin Wolf28518102015-05-08 17:07:31 +02004157static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4158 BlockDriverState *bs,
4159 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02004160 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02004161 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004162 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02004163 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004164 int parent_flags,
4165 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04004166{
4167 assert(bs != NULL);
4168
4169 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02004170 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004171 QDict *old_options, *explicit_options, *options_copy;
4172 int flags;
4173 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004174
Kevin Wolf1a63a902017-12-06 20:24:44 +01004175 /* Make sure that the caller remembered to use a drained section. This is
4176 * important to avoid graph changes between the recursive queuing here and
4177 * bdrv_reopen_multiple(). */
4178 assert(bs->quiesce_counter > 0);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05004179 GLOBAL_STATE_CODE();
Kevin Wolf1a63a902017-12-06 20:24:44 +01004180
Jeff Codye971aa12012-09-20 15:13:19 -04004181 if (bs_queue == NULL) {
4182 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004183 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04004184 }
4185
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004186 if (!options) {
4187 options = qdict_new();
4188 }
4189
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004190 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004191 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004192 if (bs == bs_entry->state.bs) {
4193 break;
4194 }
4195 }
4196
Kevin Wolf28518102015-05-08 17:07:31 +02004197 /*
4198 * Precedence of options:
4199 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004200 * 2. Retained from explicitly set options of bs
4201 * 3. Inherited from parent node
4202 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004203 */
4204
Kevin Wolf145f5982015-05-08 16:15:03 +02004205 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004206 if (bs_entry || keep_old_opts) {
4207 old_options = qdict_clone_shallow(bs_entry ?
4208 bs_entry->state.explicit_options :
4209 bs->explicit_options);
4210 bdrv_join_options(bs, options, old_options);
4211 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004212 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004213
4214 explicit_options = qdict_clone_shallow(options);
4215
Kevin Wolf28518102015-05-08 17:07:31 +02004216 /* Inherit from parent node */
4217 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004218 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004219 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004220 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004221 } else {
4222 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004223 }
4224
Alberto Garcia077e8e22019-03-12 18:48:44 +02004225 if (keep_old_opts) {
4226 /* Old values are used for options that aren't set yet */
4227 old_options = qdict_clone_shallow(bs->options);
4228 bdrv_join_options(bs, options, old_options);
4229 qobject_unref(old_options);
4230 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004231
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004232 /* We have the final set of options so let's update the flags */
4233 options_copy = qdict_clone_shallow(options);
4234 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4235 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4236 update_flags_from_options(&flags, opts);
4237 qemu_opts_del(opts);
4238 qobject_unref(options_copy);
4239
Kevin Wolffd452022017-08-03 17:02:59 +02004240 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004241 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004242 if (flags & BDRV_O_RDWR) {
4243 flags |= BDRV_O_ALLOW_RDWR;
4244 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004245
Kevin Wolf1857c972017-09-14 14:53:46 +02004246 if (!bs_entry) {
4247 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004248 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004249 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004250 qobject_unref(bs_entry->state.options);
4251 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004252 }
4253
4254 bs_entry->state.bs = bs;
4255 bs_entry->state.options = options;
4256 bs_entry->state.explicit_options = explicit_options;
4257 bs_entry->state.flags = flags;
4258
Alberto Garcia85466322019-03-12 18:48:45 +02004259 /*
4260 * If keep_old_opts is false then it means that unspecified
4261 * options must be reset to their original value. We don't allow
4262 * resetting 'backing' but we need to know if the option is
4263 * missing in order to decide if we have to return an error.
4264 */
4265 if (!keep_old_opts) {
4266 bs_entry->state.backing_missing =
4267 !qdict_haskey(options, "backing") &&
4268 !qdict_haskey(options, "backing.driver");
4269 }
4270
Kevin Wolf67251a32015-04-09 18:54:04 +02004271 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004272 QDict *new_child_options = NULL;
4273 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004274
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004275 /* reopen can only change the options of block devices that were
4276 * implicitly created and inherited options. For other (referenced)
4277 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004278 if (child->bs->inherits_from != bs) {
4279 continue;
4280 }
4281
Alberto Garcia85466322019-03-12 18:48:45 +02004282 /* Check if the options contain a child reference */
4283 if (qdict_haskey(options, child->name)) {
4284 const char *childref = qdict_get_try_str(options, child->name);
4285 /*
4286 * The current child must not be reopened if the child
4287 * reference is null or points to a different node.
4288 */
4289 if (g_strcmp0(childref, child->bs->node_name)) {
4290 continue;
4291 }
4292 /*
4293 * If the child reference points to the current child then
4294 * reopen it with its existing set of options (note that
4295 * it can still inherit new options from the parent).
4296 */
4297 child_keep_old = true;
4298 } else {
4299 /* Extract child options ("child-name.*") */
4300 char *child_key_dot = g_strdup_printf("%s.", child->name);
4301 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4302 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4303 g_free(child_key_dot);
4304 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004305
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004306 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004307 child->klass, child->role, bs->drv->is_format,
4308 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004309 }
4310
Jeff Codye971aa12012-09-20 15:13:19 -04004311 return bs_queue;
4312}
4313
Kevin Wolf28518102015-05-08 17:07:31 +02004314BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4315 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004316 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004317{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004318 GLOBAL_STATE_CODE();
4319
Max Reitz3cdc69d2020-05-13 13:05:18 +02004320 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4321 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004322}
4323
Alberto Garciaab5b52282021-07-08 13:47:05 +02004324void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4325{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004326 GLOBAL_STATE_CODE();
Alberto Garciaab5b52282021-07-08 13:47:05 +02004327 if (bs_queue) {
4328 BlockReopenQueueEntry *bs_entry, *next;
4329 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4330 qobject_unref(bs_entry->state.explicit_options);
4331 qobject_unref(bs_entry->state.options);
4332 g_free(bs_entry);
4333 }
4334 g_free(bs_queue);
4335 }
4336}
4337
Jeff Codye971aa12012-09-20 15:13:19 -04004338/*
4339 * Reopen multiple BlockDriverStates atomically & transactionally.
4340 *
4341 * The queue passed in (bs_queue) must have been built up previous
4342 * via bdrv_reopen_queue().
4343 *
4344 * Reopens all BDS specified in the queue, with the appropriate
4345 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004346 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004347 * data cleaned up.
4348 *
4349 * If all devices prepare successfully, then the changes are committed
4350 * to all devices.
4351 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004352 * All affected nodes must be drained between bdrv_reopen_queue() and
4353 * bdrv_reopen_multiple().
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004354 *
4355 * To be called from the main thread, with all other AioContexts unlocked.
Jeff Codye971aa12012-09-20 15:13:19 -04004356 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004357int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004358{
4359 int ret = -1;
4360 BlockReopenQueueEntry *bs_entry, *next;
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004361 AioContext *ctx;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004362 Transaction *tran = tran_new();
4363 g_autoptr(GHashTable) found = NULL;
4364 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004365
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004366 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Jeff Codye971aa12012-09-20 15:13:19 -04004367 assert(bs_queue != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004368 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004369
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004370 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004371 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4372 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004373 ret = bdrv_flush(bs_entry->state.bs);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004374 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004375 if (ret < 0) {
4376 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004377 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004378 }
4379 }
4380
4381 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004382 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004383 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4384 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004385 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004386 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004387 if (ret < 0) {
4388 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004389 }
4390 bs_entry->prepared = true;
4391 }
4392
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004393 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004394 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004395 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004396
4397 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4398 if (state->old_backing_bs) {
4399 refresh_list = bdrv_topological_dfs(refresh_list, found,
4400 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004401 }
Alberto Garciaecd30d22021-06-10 15:05:36 +03004402 if (state->old_file_bs) {
4403 refresh_list = bdrv_topological_dfs(refresh_list, found,
4404 state->old_file_bs);
4405 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004406 }
4407
4408 /*
4409 * Note that file-posix driver rely on permission update done during reopen
4410 * (even if no permission changed), because it wants "new" permissions for
4411 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4412 * in raw_reopen_prepare() which is called with "old" permissions.
4413 */
4414 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4415 if (ret < 0) {
4416 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004417 }
4418
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004419 /*
4420 * If we reach this point, we have success and just need to apply the
4421 * changes.
4422 *
4423 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4424 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4425 * children are usually goes after parents in reopen-queue, so go from last
4426 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004427 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004428 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004429 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4430 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004431 bdrv_reopen_commit(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004432 aio_context_release(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004433 }
4434
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004435 tran_commit(tran);
4436
4437 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4438 BlockDriverState *bs = bs_entry->state.bs;
4439
4440 if (bs->drv->bdrv_reopen_commit_post) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004441 ctx = bdrv_get_aio_context(bs);
4442 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004443 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004444 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004445 }
4446 }
4447
Jeff Codye971aa12012-09-20 15:13:19 -04004448 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004449 goto cleanup;
4450
4451abort:
4452 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004453 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004454 if (bs_entry->prepared) {
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 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004458 aio_context_release(ctx);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004459 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004460 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004461
Jeff Codye971aa12012-09-20 15:13:19 -04004462cleanup:
Alberto Garciaab5b52282021-07-08 13:47:05 +02004463 bdrv_reopen_queue_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004464
Jeff Codye971aa12012-09-20 15:13:19 -04004465 return ret;
4466}
4467
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004468int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4469 Error **errp)
4470{
4471 AioContext *ctx = bdrv_get_aio_context(bs);
4472 BlockReopenQueue *queue;
4473 int ret;
4474
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004475 GLOBAL_STATE_CODE();
4476
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004477 bdrv_subtree_drained_begin(bs);
4478 if (ctx != qemu_get_aio_context()) {
4479 aio_context_release(ctx);
4480 }
4481
4482 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4483 ret = bdrv_reopen_multiple(queue, errp);
4484
4485 if (ctx != qemu_get_aio_context()) {
4486 aio_context_acquire(ctx);
4487 }
4488 bdrv_subtree_drained_end(bs);
4489
4490 return ret;
4491}
4492
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004493int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4494 Error **errp)
4495{
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004496 QDict *opts = qdict_new();
4497
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004498 GLOBAL_STATE_CODE();
4499
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004500 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4501
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004502 return bdrv_reopen(bs, opts, true, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004503}
4504
Jeff Codye971aa12012-09-20 15:13:19 -04004505/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004506 * Take a BDRVReopenState and check if the value of 'backing' in the
4507 * reopen_state->options QDict is valid or not.
4508 *
4509 * If 'backing' is missing from the QDict then return 0.
4510 *
4511 * If 'backing' contains the node name of the backing file of
4512 * reopen_state->bs then return 0.
4513 *
4514 * If 'backing' contains a different node name (or is null) then check
4515 * whether the current backing file can be replaced with the new one.
4516 * If that's the case then reopen_state->replace_backing_bs is set to
4517 * true and reopen_state->new_backing_bs contains a pointer to the new
4518 * backing BlockDriverState (or NULL).
4519 *
4520 * Return 0 on success, otherwise return < 0 and set @errp.
4521 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004522static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4523 bool is_backing, Transaction *tran,
4524 Error **errp)
Alberto Garciacb828c32019-03-12 18:48:47 +02004525{
4526 BlockDriverState *bs = reopen_state->bs;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004527 BlockDriverState *new_child_bs;
4528 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4529 child_bs(bs->file);
4530 const char *child_name = is_backing ? "backing" : "file";
Alberto Garciacb828c32019-03-12 18:48:47 +02004531 QObject *value;
4532 const char *str;
4533
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05004534 GLOBAL_STATE_CODE();
4535
Alberto Garciaecd30d22021-06-10 15:05:36 +03004536 value = qdict_get(reopen_state->options, child_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004537 if (value == NULL) {
4538 return 0;
4539 }
4540
4541 switch (qobject_type(value)) {
4542 case QTYPE_QNULL:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004543 assert(is_backing); /* The 'file' option does not allow a null value */
4544 new_child_bs = NULL;
Alberto Garciacb828c32019-03-12 18:48:47 +02004545 break;
4546 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004547 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciaecd30d22021-06-10 15:05:36 +03004548 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4549 if (new_child_bs == NULL) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004550 return -EINVAL;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004551 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4552 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4553 "cycle", str, child_name, bs->node_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004554 return -EINVAL;
4555 }
4556 break;
4557 default:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004558 /*
4559 * The options QDict has been flattened, so 'backing' and 'file'
4560 * do not allow any other data type here.
4561 */
Alberto Garciacb828c32019-03-12 18:48:47 +02004562 g_assert_not_reached();
4563 }
4564
Alberto Garciaecd30d22021-06-10 15:05:36 +03004565 if (old_child_bs == new_child_bs) {
4566 return 0;
4567 }
4568
4569 if (old_child_bs) {
4570 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004571 return 0;
4572 }
4573
Alberto Garciaecd30d22021-06-10 15:05:36 +03004574 if (old_child_bs->implicit) {
4575 error_setg(errp, "Cannot replace implicit %s child of %s",
4576 child_name, bs->node_name);
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004577 return -EPERM;
4578 }
4579 }
4580
Alberto Garciaecd30d22021-06-10 15:05:36 +03004581 if (bs->drv->is_filter && !old_child_bs) {
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004582 /*
4583 * Filters always have a file or a backing child, so we are trying to
4584 * change wrong child
4585 */
4586 error_setg(errp, "'%s' is a %s filter node that does not support a "
Alberto Garciaecd30d22021-06-10 15:05:36 +03004587 "%s child", bs->node_name, bs->drv->format_name, child_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004588 return -EINVAL;
4589 }
4590
Alberto Garciaecd30d22021-06-10 15:05:36 +03004591 if (is_backing) {
4592 reopen_state->old_backing_bs = old_child_bs;
4593 } else {
4594 reopen_state->old_file_bs = old_child_bs;
4595 }
4596
4597 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4598 tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004599}
4600
4601/*
Jeff Codye971aa12012-09-20 15:13:19 -04004602 * Prepares a BlockDriverState for reopen. All changes are staged in the
4603 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4604 * the block driver layer .bdrv_reopen_prepare()
4605 *
4606 * bs is the BlockDriverState to reopen
4607 * flags are the new open flags
4608 * queue is the reopen queue
4609 *
4610 * Returns 0 on success, non-zero on error. On error errp will be set
4611 * as well.
4612 *
4613 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4614 * It is the responsibility of the caller to then call the abort() or
4615 * commit() for any other BDS that have been left in a prepare() state
4616 *
4617 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004618static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004619 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +03004620 Transaction *change_child_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004621{
4622 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004623 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004624 Error *local_err = NULL;
4625 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004626 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004627 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004628 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004629 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004630 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004631
4632 assert(reopen_state != NULL);
4633 assert(reopen_state->bs->drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004634 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004635 drv = reopen_state->bs->drv;
4636
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004637 /* This function and each driver's bdrv_reopen_prepare() remove
4638 * entries from reopen_state->options as they are processed, so
4639 * we need to make a copy of the original QDict. */
4640 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4641
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004642 /* Process generic block layer options */
4643 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004644 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004645 ret = -EINVAL;
4646 goto error;
4647 }
4648
Alberto Garciae6d79c42018-11-12 16:00:47 +02004649 /* This was already called in bdrv_reopen_queue_child() so the flags
4650 * are up-to-date. This time we simply want to remove the options from
4651 * QemuOpts in order to indicate that they have been processed. */
4652 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004653 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004654 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004655
Alberto Garcia415bbca2018-10-03 13:23:13 +03004656 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004657 if (discard != NULL) {
4658 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4659 error_setg(errp, "Invalid discard option");
4660 ret = -EINVAL;
4661 goto error;
4662 }
4663 }
4664
Alberto Garcia543770b2018-09-06 12:37:09 +03004665 reopen_state->detect_zeroes =
4666 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4667 if (local_err) {
4668 error_propagate(errp, local_err);
4669 ret = -EINVAL;
4670 goto error;
4671 }
4672
Alberto Garcia57f9db92018-09-06 12:37:06 +03004673 /* All other options (including node-name and driver) must be unchanged.
4674 * Put them back into the QDict, so that they are checked at the end
4675 * of this function. */
4676 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004677
Jeff Cody3d8ce172017-04-07 16:55:30 -04004678 /* If we are to stay read-only, do not allow permission change
4679 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4680 * not set, or if the BDS still has copy_on_read enabled */
4681 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004682 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004683 if (local_err) {
4684 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004685 goto error;
4686 }
4687
Jeff Codye971aa12012-09-20 15:13:19 -04004688 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004689 /*
4690 * If a driver-specific option is missing, it means that we
4691 * should reset it to its default value.
4692 * But not all options allow that, so we need to check it first.
4693 */
4694 ret = bdrv_reset_options_allowed(reopen_state->bs,
4695 reopen_state->options, errp);
4696 if (ret) {
4697 goto error;
4698 }
4699
Jeff Codye971aa12012-09-20 15:13:19 -04004700 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4701 if (ret) {
4702 if (local_err != NULL) {
4703 error_propagate(errp, local_err);
4704 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004705 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004706 error_setg(errp, "failed while preparing to reopen image '%s'",
4707 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004708 }
4709 goto error;
4710 }
4711 } else {
4712 /* It is currently mandatory to have a bdrv_reopen_prepare()
4713 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004714 error_setg(errp, "Block format '%s' used by node '%s' "
4715 "does not support reopening files", drv->format_name,
4716 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004717 ret = -1;
4718 goto error;
4719 }
4720
Max Reitz9ad08c42018-11-16 17:45:24 +01004721 drv_prepared = true;
4722
Alberto Garciabacd9b82019-03-12 18:48:46 +02004723 /*
4724 * We must provide the 'backing' option if the BDS has a backing
4725 * file or if the image file has a backing file name as part of
4726 * its metadata. Otherwise the 'backing' option can be omitted.
4727 */
4728 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004729 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004730 error_setg(errp, "backing is missing for '%s'",
4731 reopen_state->bs->node_name);
4732 ret = -EINVAL;
4733 goto error;
4734 }
4735
Alberto Garciacb828c32019-03-12 18:48:47 +02004736 /*
4737 * Allow changing the 'backing' option. The new value can be
4738 * either a reference to an existing node (using its node name)
4739 * or NULL to simply detach the current backing file.
4740 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004741 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4742 change_child_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004743 if (ret < 0) {
4744 goto error;
4745 }
4746 qdict_del(reopen_state->options, "backing");
4747
Alberto Garciaecd30d22021-06-10 15:05:36 +03004748 /* Allow changing the 'file' option. In this case NULL is not allowed */
4749 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4750 change_child_tran, errp);
4751 if (ret < 0) {
4752 goto error;
4753 }
4754 qdict_del(reopen_state->options, "file");
4755
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004756 /* Options that are not handled are only okay if they are unchanged
4757 * compared to the old state. It is expected that some options are only
4758 * used for the initial open, but not reopen (e.g. filename) */
4759 if (qdict_size(reopen_state->options)) {
4760 const QDictEntry *entry = qdict_first(reopen_state->options);
4761
4762 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004763 QObject *new = entry->value;
4764 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004765
Alberto Garciadb905282018-09-06 12:37:05 +03004766 /* Allow child references (child_name=node_name) as long as they
4767 * point to the current child (i.e. everything stays the same). */
4768 if (qobject_type(new) == QTYPE_QSTRING) {
4769 BdrvChild *child;
4770 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4771 if (!strcmp(child->name, entry->key)) {
4772 break;
4773 }
4774 }
4775
4776 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004777 if (!strcmp(child->bs->node_name,
4778 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004779 continue; /* Found child with this name, skip option */
4780 }
4781 }
4782 }
4783
Max Reitz54fd1b02017-11-14 19:01:26 +01004784 /*
4785 * TODO: When using -drive to specify blockdev options, all values
4786 * will be strings; however, when using -blockdev, blockdev-add or
4787 * filenames using the json:{} pseudo-protocol, they will be
4788 * correctly typed.
4789 * In contrast, reopening options are (currently) always strings
4790 * (because you can only specify them through qemu-io; all other
4791 * callers do not specify any options).
4792 * Therefore, when using anything other than -drive to create a BDS,
4793 * this cannot detect non-string options as unchanged, because
4794 * qobject_is_equal() always returns false for objects of different
4795 * type. In the future, this should be remedied by correctly typing
4796 * all options. For now, this is not too big of an issue because
4797 * the user can simply omit options which cannot be changed anyway,
4798 * so they will stay unchanged.
4799 */
4800 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004801 error_setg(errp, "Cannot change the option '%s'", entry->key);
4802 ret = -EINVAL;
4803 goto error;
4804 }
4805 } while ((entry = qdict_next(reopen_state->options, entry)));
4806 }
4807
Jeff Codye971aa12012-09-20 15:13:19 -04004808 ret = 0;
4809
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004810 /* Restore the original reopen_state->options QDict */
4811 qobject_unref(reopen_state->options);
4812 reopen_state->options = qobject_ref(orig_reopen_opts);
4813
Jeff Codye971aa12012-09-20 15:13:19 -04004814error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004815 if (ret < 0 && drv_prepared) {
4816 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4817 * call drv->bdrv_reopen_abort() before signaling an error
4818 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4819 * when the respective bdrv_reopen_prepare() has failed) */
4820 if (drv->bdrv_reopen_abort) {
4821 drv->bdrv_reopen_abort(reopen_state);
4822 }
4823 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004824 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004825 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004826 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004827 return ret;
4828}
4829
4830/*
4831 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4832 * makes them final by swapping the staging BlockDriverState contents into
4833 * the active BlockDriverState contents.
4834 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004835static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004836{
4837 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004838 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004839 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004840
4841 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004842 bs = reopen_state->bs;
4843 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004844 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004845 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004846
4847 /* If there are any driver level actions to take */
4848 if (drv->bdrv_reopen_commit) {
4849 drv->bdrv_reopen_commit(reopen_state);
4850 }
4851
4852 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004853 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004854 qobject_unref(bs->options);
Alberto Garciaab5b52282021-07-08 13:47:05 +02004855 qobject_ref(reopen_state->explicit_options);
4856 qobject_ref(reopen_state->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004857
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004858 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004859 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004860 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004861 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004862
Alberto Garcia50196d72018-09-06 12:37:03 +03004863 /* Remove child references from bs->options and bs->explicit_options.
4864 * Child options were already removed in bdrv_reopen_queue_child() */
4865 QLIST_FOREACH(child, &bs->children, next) {
4866 qdict_del(bs->explicit_options, child->name);
4867 qdict_del(bs->options, child->name);
4868 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004869 /* backing is probably removed, so it's not handled by previous loop */
4870 qdict_del(bs->explicit_options, "backing");
4871 qdict_del(bs->options, "backing");
4872
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004873 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004874}
4875
4876/*
4877 * Abort the reopen, and delete and free the staged changes in
4878 * reopen_state
4879 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004880static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004881{
4882 BlockDriver *drv;
4883
4884 assert(reopen_state != NULL);
4885 drv = reopen_state->bs->drv;
4886 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004887 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004888
4889 if (drv->bdrv_reopen_abort) {
4890 drv->bdrv_reopen_abort(reopen_state);
4891 }
4892}
4893
4894
Max Reitz64dff522016-01-29 16:36:10 +01004895static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004896{
Max Reitz33384422014-06-20 21:57:33 +02004897 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004898 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004899
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004900 GLOBAL_STATE_CODE();
Max Reitz30f55fb2016-05-17 16:41:32 +02004901 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004902
Paolo Bonzinifc272912015-12-23 11:48:24 +01004903 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004904 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004905 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004906
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004907 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004908 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004909 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004910 bs->drv->bdrv_close(bs);
4911 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004912 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004913 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004914
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004915 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004916 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004917 }
4918
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03004919 assert(!bs->backing);
4920 assert(!bs->file);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004921 g_free(bs->opaque);
4922 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004923 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004924 bs->backing_file[0] = '\0';
4925 bs->backing_format[0] = '\0';
4926 bs->total_sectors = 0;
4927 bs->encrypted = false;
4928 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004929 qobject_unref(bs->options);
4930 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004931 bs->options = NULL;
4932 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004933 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004934 bs->full_open_options = NULL;
Hanna Reitz0bc329f2021-08-12 10:41:44 +02004935 g_free(bs->block_status_cache);
4936 bs->block_status_cache = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004937
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004938 bdrv_release_named_dirty_bitmaps(bs);
4939 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4940
Max Reitz33384422014-06-20 21:57:33 +02004941 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4942 g_free(ban);
4943 }
4944 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004945 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004946
4947 /*
4948 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4949 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4950 * gets called.
4951 */
4952 if (bs->quiesce_counter) {
4953 bdrv_drain_all_end_quiesce(bs);
4954 }
bellardb3380822004-03-14 21:38:54 +00004955}
4956
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004957void bdrv_close_all(void)
4958{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004959 GLOBAL_STATE_CODE();
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04004960 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004961
Max Reitzca9bd242016-01-29 16:36:14 +01004962 /* Drop references from requests still in flight, such as canceled block
4963 * jobs whose AIO context has not been polled yet */
4964 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004965
Max Reitzca9bd242016-01-29 16:36:14 +01004966 blk_remove_all_bs();
4967 blockdev_close_all_bdrv_states();
4968
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004969 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004970}
4971
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004972static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004973{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004974 GQueue *queue;
4975 GHashTable *found;
4976 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004977
Max Reitzbd86fb92020-05-13 13:05:13 +02004978 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004979 return false;
4980 }
4981
Max Reitzec9f10f2018-06-13 20:18:15 +02004982 /* If the child @c belongs to the BDS @to, replacing the current
4983 * c->bs by @to would mean to create a loop.
4984 *
4985 * Such a case occurs when appending a BDS to a backing chain.
4986 * For instance, imagine the following chain:
4987 *
4988 * guest device -> node A -> further backing chain...
4989 *
4990 * Now we create a new BDS B which we want to put on top of this
4991 * chain, so we first attach A as its backing node:
4992 *
4993 * node B
4994 * |
4995 * v
4996 * guest device -> node A -> further backing chain...
4997 *
4998 * Finally we want to replace A by B. When doing that, we want to
4999 * replace all pointers to A by pointers to B -- except for the
5000 * pointer from B because (1) that would create a loop, and (2)
5001 * that pointer should simply stay intact:
5002 *
5003 * guest device -> node B
5004 * |
5005 * v
5006 * node A -> further backing chain...
5007 *
5008 * In general, when replacing a node A (c->bs) by a node B (@to),
5009 * if A is a child of B, that means we cannot replace A by B there
5010 * because that would create a loop. Silently detaching A from B
5011 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005012 * place there is the most sensible choice.
5013 *
5014 * We would also create a loop in any cases where @c is only
5015 * indirectly referenced by @to. Prevent this by returning false
5016 * if @c is found (by breadth-first search) anywhere in the whole
5017 * subtree of @to.
5018 */
5019
5020 ret = true;
5021 found = g_hash_table_new(NULL, NULL);
5022 g_hash_table_add(found, to);
5023 queue = g_queue_new();
5024 g_queue_push_tail(queue, to);
5025
5026 while (!g_queue_is_empty(queue)) {
5027 BlockDriverState *v = g_queue_pop_head(queue);
5028 BdrvChild *c2;
5029
5030 QLIST_FOREACH(c2, &v->children, next) {
5031 if (c2 == c) {
5032 ret = false;
5033 break;
5034 }
5035
5036 if (g_hash_table_contains(found, c2->bs)) {
5037 continue;
5038 }
5039
5040 g_queue_push_tail(queue, c2->bs);
5041 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005042 }
5043 }
5044
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005045 g_queue_free(queue);
5046 g_hash_table_destroy(found);
5047
5048 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005049}
5050
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005051static void bdrv_remove_child_commit(void *opaque)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005052{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005053 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03005054 bdrv_child_free(opaque);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005055}
5056
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005057static TransactionActionDrv bdrv_remove_child_drv = {
5058 .commit = bdrv_remove_child_commit,
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005059};
5060
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005061/* Function doesn't update permissions, caller is responsible for this. */
5062static void bdrv_remove_child(BdrvChild *child, Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005063{
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005064 if (!child) {
5065 return;
5066 }
5067
5068 if (child->bs) {
Vladimir Sementsov-Ogievskiya2c37a32022-07-26 23:11:30 +03005069 bdrv_replace_child_tran(child, NULL, tran);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005070 }
5071
Vladimir Sementsov-Ogievskiy57f08942022-07-26 23:11:34 +03005072 tran_add(tran, &bdrv_remove_child_drv, child);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005073}
5074
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005075static int bdrv_replace_node_noperm(BlockDriverState *from,
5076 BlockDriverState *to,
5077 bool auto_skip, Transaction *tran,
5078 Error **errp)
5079{
5080 BdrvChild *c, *next;
5081
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005082 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005083
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005084 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5085 assert(c->bs == from);
5086 if (!should_update_child(c, to)) {
5087 if (auto_skip) {
5088 continue;
5089 }
5090 error_setg(errp, "Should not change '%s' link to '%s'",
5091 c->name, from->node_name);
5092 return -EINVAL;
5093 }
5094 if (c->frozen) {
5095 error_setg(errp, "Cannot change '%s' link to '%s'",
5096 c->name, from->node_name);
5097 return -EPERM;
5098 }
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03005099 bdrv_replace_child_tran(c, to, tran);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005100 }
5101
5102 return 0;
5103}
5104
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005105/*
5106 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5107 * if it creates a parent-child relation loop or if parent is block-job.
5108 *
5109 * With auto_skip=false the error is returned if from has a parent which should
5110 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005111 *
5112 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5113 * case backing link of the cow-parent of @to is removed.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005114 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005115static int bdrv_replace_node_common(BlockDriverState *from,
5116 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005117 bool auto_skip, bool detach_subchain,
5118 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005119{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005120 Transaction *tran = tran_new();
5121 g_autoptr(GHashTable) found = NULL;
5122 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04005123 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005124 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005125
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005126 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005127
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005128 if (detach_subchain) {
5129 assert(bdrv_chain_contains(from, to));
5130 assert(from != to);
5131 for (to_cow_parent = from;
5132 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5133 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5134 {
5135 ;
5136 }
5137 }
5138
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005139 /* Make sure that @from doesn't go away until we have successfully attached
5140 * all of its parents to @to. */
5141 bdrv_ref(from);
5142
Kevin Wolff871abd2019-05-21 19:00:25 +02005143 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01005144 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02005145 bdrv_drained_begin(from);
5146
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005147 /*
5148 * Do the replacement without permission update.
5149 * Replacement may influence the permissions, we should calculate new
5150 * permissions based on new graph. If we fail, we'll roll-back the
5151 * replacement.
5152 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005153 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5154 if (ret < 0) {
5155 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005156 }
5157
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005158 if (detach_subchain) {
Vladimir Sementsov-Ogievskiyf38eaec2022-11-07 19:35:56 +03005159 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005160 }
5161
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005162 found = g_hash_table_new(NULL, NULL);
5163
5164 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5165 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5166
5167 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005168 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005169 goto out;
5170 }
5171
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005172 ret = 0;
5173
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005174out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005175 tran_finalize(tran, ret);
5176
Kevin Wolff871abd2019-05-21 19:00:25 +02005177 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005178 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005179
5180 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005181}
5182
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005183int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5184 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005185{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005186 GLOBAL_STATE_CODE();
5187
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005188 return bdrv_replace_node_common(from, to, true, false, errp);
5189}
5190
5191int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5192{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005193 GLOBAL_STATE_CODE();
5194
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005195 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5196 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005197}
5198
Jeff Cody8802d1f2012-02-28 15:54:06 -05005199/*
5200 * Add new bs contents at the top of an image chain while the chain is
5201 * live, while keeping required fields on the top layer.
5202 *
5203 * This will modify the BlockDriverState fields, and swap contents
5204 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5205 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005206 * bs_new must not be attached to a BlockBackend and must not have backing
5207 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005208 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005209 * This function does not create any image files.
5210 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005211int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5212 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005213{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005214 int ret;
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03005215 BdrvChild *child;
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005216 Transaction *tran = tran_new();
5217
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005218 GLOBAL_STATE_CODE();
5219
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005220 assert(!bs_new->backing);
5221
Vladimir Sementsov-Ogievskiy5bb047472022-07-26 23:11:32 +03005222 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5223 &child_of_bds, bdrv_backing_role(bs_new),
5224 tran, errp);
5225 if (!child) {
5226 ret = -EINVAL;
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005227 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005228 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005229
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005230 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005231 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005232 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005233 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005234
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03005235 ret = bdrv_refresh_perms(bs_new, tran, errp);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005236out:
5237 tran_finalize(tran, ret);
5238
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005239 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005240
5241 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005242}
5243
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005244/* Not for empty child */
5245int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5246 Error **errp)
5247{
5248 int ret;
5249 Transaction *tran = tran_new();
5250 g_autoptr(GHashTable) found = NULL;
5251 g_autoptr(GSList) refresh_list = NULL;
5252 BlockDriverState *old_bs = child->bs;
5253
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005254 GLOBAL_STATE_CODE();
5255
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005256 bdrv_ref(old_bs);
5257 bdrv_drained_begin(old_bs);
5258 bdrv_drained_begin(new_bs);
5259
Vladimir Sementsov-Ogievskiy0f0b1e22022-07-26 23:11:29 +03005260 bdrv_replace_child_tran(child, new_bs, tran);
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005261
5262 found = g_hash_table_new(NULL, NULL);
5263 refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5264 refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5265
5266 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5267
5268 tran_finalize(tran, ret);
5269
5270 bdrv_drained_end(old_bs);
5271 bdrv_drained_end(new_bs);
5272 bdrv_unref(old_bs);
5273
5274 return ret;
5275}
5276
Fam Zheng4f6fd342013-08-23 09:14:47 +08005277static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005278{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005279 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005280 assert(!bs->refcnt);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005281 GLOBAL_STATE_CODE();
Markus Armbruster18846de2010-06-29 16:58:30 +02005282
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005283 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005284 if (bs->node_name[0] != '\0') {
5285 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5286 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005287 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5288
Anton Kuchin30c321f2019-05-07 11:12:56 +03005289 bdrv_close(bs);
5290
Anthony Liguori7267c092011-08-20 22:09:37 -05005291 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005292}
5293
Vladimir Sementsov-Ogievskiy96796fa2021-09-20 14:55:36 +03005294
5295/*
5296 * Replace @bs by newly created block node.
5297 *
5298 * @options is a QDict of options to pass to the block drivers, or NULL for an
5299 * empty set of options. The reference to the QDict belongs to the block layer
5300 * after the call (even on failure), so if the caller intends to reuse the
5301 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5302 */
5303BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005304 int flags, Error **errp)
5305{
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005306 ERRP_GUARD();
5307 int ret;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005308 BlockDriverState *new_node_bs = NULL;
5309 const char *drvname, *node_name;
5310 BlockDriver *drv;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005311
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005312 drvname = qdict_get_try_str(options, "driver");
5313 if (!drvname) {
5314 error_setg(errp, "driver is not specified");
5315 goto fail;
5316 }
5317
5318 drv = bdrv_find_format(drvname);
5319 if (!drv) {
5320 error_setg(errp, "Unknown driver: '%s'", drvname);
5321 goto fail;
5322 }
5323
5324 node_name = qdict_get_try_str(options, "node-name");
5325
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005326 GLOBAL_STATE_CODE();
5327
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005328 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5329 errp);
5330 options = NULL; /* bdrv_new_open_driver() eats options */
5331 if (!new_node_bs) {
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005332 error_prepend(errp, "Could not create node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005333 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005334 }
5335
5336 bdrv_drained_begin(bs);
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005337 ret = bdrv_replace_node(bs, new_node_bs, errp);
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005338 bdrv_drained_end(bs);
5339
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005340 if (ret < 0) {
5341 error_prepend(errp, "Could not replace node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005342 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005343 }
5344
5345 return new_node_bs;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005346
5347fail:
5348 qobject_unref(options);
5349 bdrv_unref(new_node_bs);
5350 return NULL;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005351}
5352
aliguorie97fc192009-04-21 23:11:50 +00005353/*
5354 * Run consistency checks on an image
5355 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005356 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005357 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005358 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005359 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005360int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5361 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005362{
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05005363 IO_CODE();
Max Reitz908bcd52014-08-07 22:47:55 +02005364 if (bs->drv == NULL) {
5365 return -ENOMEDIUM;
5366 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005367 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005368 return -ENOTSUP;
5369 }
5370
Kevin Wolfe076f332010-06-29 11:43:13 +02005371 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005372 return bs->drv->bdrv_co_check(bs, res, fix);
5373}
5374
Kevin Wolf756e6732010-01-12 12:55:17 +01005375/*
5376 * Return values:
5377 * 0 - success
5378 * -EINVAL - backing format specified, but no file
5379 * -ENOSPC - can't update the backing file because no space is left in the
5380 * image file header
5381 * -ENOTSUP - format driver doesn't support changing the backing file
5382 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005383int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
Eric Blake497a30d2021-05-03 14:36:00 -07005384 const char *backing_fmt, bool require)
Kevin Wolf756e6732010-01-12 12:55:17 +01005385{
5386 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005387 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005388
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005389 GLOBAL_STATE_CODE();
5390
Max Reitzd470ad42017-11-10 21:31:09 +01005391 if (!drv) {
5392 return -ENOMEDIUM;
5393 }
5394
Paolo Bonzini5f377792012-04-12 14:01:01 +02005395 /* Backing file format doesn't make sense without a backing file */
5396 if (backing_fmt && !backing_file) {
5397 return -EINVAL;
5398 }
5399
Eric Blake497a30d2021-05-03 14:36:00 -07005400 if (require && backing_file && !backing_fmt) {
5401 return -EINVAL;
Eric Blakee54ee1b2020-07-06 15:39:53 -05005402 }
5403
Kevin Wolf756e6732010-01-12 12:55:17 +01005404 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005405 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005406 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005407 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005408 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005409
5410 if (ret == 0) {
5411 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5412 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005413 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5414 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005415 }
5416 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005417}
5418
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005419/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005420 * Finds the first non-filter node above bs in the chain between
5421 * active and bs. The returned node is either an immediate parent of
5422 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005423 *
5424 * Returns NULL if bs is not found in active's image chain,
5425 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005426 *
5427 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005428 */
5429BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5430 BlockDriverState *bs)
5431{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005432
5433 GLOBAL_STATE_CODE();
5434
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005435 bs = bdrv_skip_filters(bs);
5436 active = bdrv_skip_filters(active);
5437
5438 while (active) {
5439 BlockDriverState *next = bdrv_backing_chain_next(active);
5440 if (bs == next) {
5441 return active;
5442 }
5443 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005444 }
5445
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005446 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005447}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005448
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005449/* Given a BDS, searches for the base layer. */
5450BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5451{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005452 GLOBAL_STATE_CODE();
5453
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005454 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005455}
5456
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005457/*
Max Reitz7b99a262019-06-12 16:07:11 +02005458 * Return true if at least one of the COW (backing) and filter links
5459 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005460 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005461 */
5462bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5463 Error **errp)
5464{
5465 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005466 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005467
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005468 GLOBAL_STATE_CODE();
5469
Max Reitz7b99a262019-06-12 16:07:11 +02005470 for (i = bs; i != base; i = child_bs(child)) {
5471 child = bdrv_filter_or_cow_child(i);
5472
5473 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005474 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005475 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005476 return true;
5477 }
5478 }
5479
5480 return false;
5481}
5482
5483/*
Max Reitz7b99a262019-06-12 16:07:11 +02005484 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005485 * If any of the links is already frozen the operation is aborted and
5486 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005487 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005488 * Returns 0 on success. On failure returns < 0 and sets @errp.
5489 */
5490int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5491 Error **errp)
5492{
5493 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005494 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005495
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005496 GLOBAL_STATE_CODE();
5497
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005498 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5499 return -EPERM;
5500 }
5501
Max Reitz7b99a262019-06-12 16:07:11 +02005502 for (i = bs; i != base; i = child_bs(child)) {
5503 child = bdrv_filter_or_cow_child(i);
5504 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005505 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005506 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005507 return -EPERM;
5508 }
5509 }
5510
Max Reitz7b99a262019-06-12 16:07:11 +02005511 for (i = bs; i != base; i = child_bs(child)) {
5512 child = bdrv_filter_or_cow_child(i);
5513 if (child) {
5514 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005515 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005516 }
5517
5518 return 0;
5519}
5520
5521/*
Max Reitz7b99a262019-06-12 16:07:11 +02005522 * Unfreeze all COW (backing) and filter links between @bs and @base.
5523 * The caller must ensure that all links are frozen before using this
5524 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005525 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005526 */
5527void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5528{
5529 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005530 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005531
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005532 GLOBAL_STATE_CODE();
5533
Max Reitz7b99a262019-06-12 16:07:11 +02005534 for (i = bs; i != base; i = child_bs(child)) {
5535 child = bdrv_filter_or_cow_child(i);
5536 if (child) {
5537 assert(child->frozen);
5538 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005539 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005540 }
5541}
5542
5543/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005544 * Drops images above 'base' up to and including 'top', and sets the image
5545 * above 'top' to have base as its backing file.
5546 *
5547 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5548 * information in 'bs' can be properly updated.
5549 *
5550 * E.g., this will convert the following chain:
5551 * bottom <- base <- intermediate <- top <- active
5552 *
5553 * to
5554 *
5555 * bottom <- base <- active
5556 *
5557 * It is allowed for bottom==base, in which case it converts:
5558 *
5559 * base <- intermediate <- top <- active
5560 *
5561 * to
5562 *
5563 * base <- active
5564 *
Jeff Cody54e26902014-06-25 15:40:10 -04005565 * If backing_file_str is non-NULL, it will be used when modifying top's
5566 * overlay image metadata.
5567 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005568 * Error conditions:
5569 * if active == top, that is considered an error
5570 *
5571 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005572int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5573 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005574{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005575 BlockDriverState *explicit_top = top;
5576 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005577 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005578 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005579 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005580 g_autoptr(GSList) updated_children = NULL;
5581 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005582
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005583 GLOBAL_STATE_CODE();
5584
Kevin Wolf6858eba2017-06-29 19:32:21 +02005585 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005586 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005587
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005588 if (!top->drv || !base->drv) {
5589 goto exit;
5590 }
5591
Kevin Wolf5db15a52015-09-14 15:33:33 +02005592 /* Make sure that base is in the backing chain of top */
5593 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005594 goto exit;
5595 }
5596
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005597 /* If 'base' recursively inherits from 'top' then we should set
5598 * base->inherits_from to top->inherits_from after 'top' and all
5599 * other intermediate nodes have been dropped.
5600 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5601 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005602 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005603 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5604
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005605 /* success - we can delete the intermediate states, and link top->base */
Max Reitzf30c66b2019-02-01 20:29:05 +01005606 if (!backing_file_str) {
5607 bdrv_refresh_filename(base);
5608 backing_file_str = base->filename;
5609 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005610
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005611 QLIST_FOREACH(c, &top->parents, next_parent) {
5612 updated_children = g_slist_prepend(updated_children, c);
5613 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005614
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005615 /*
5616 * It seems correct to pass detach_subchain=true here, but it triggers
5617 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5618 * another drained section, which modify the graph (for example, removing
5619 * the child, which we keep in updated_children list). So, it's a TODO.
5620 *
5621 * Note, bug triggered if pass detach_subchain=true here and run
5622 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5623 * That's a FIXME.
5624 */
5625 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005626 if (local_err) {
5627 error_report_err(local_err);
5628 goto exit;
5629 }
5630
5631 for (p = updated_children; p; p = p->next) {
5632 c = p->data;
5633
Max Reitzbd86fb92020-05-13 13:05:13 +02005634 if (c->klass->update_filename) {
5635 ret = c->klass->update_filename(c, base, backing_file_str,
5636 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005637 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005638 /*
5639 * TODO: Actually, we want to rollback all previous iterations
5640 * of this loop, and (which is almost impossible) previous
5641 * bdrv_replace_node()...
5642 *
5643 * Note, that c->klass->update_filename may lead to permission
5644 * update, so it's a bad idea to call it inside permission
5645 * update transaction of bdrv_replace_node.
5646 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005647 error_report_err(local_err);
5648 goto exit;
5649 }
5650 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005651 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005652
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005653 if (update_inherits_from) {
5654 base->inherits_from = explicit_top->inherits_from;
5655 }
5656
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005657 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005658exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005659 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005660 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005661 return ret;
5662}
5663
bellard83f64092006-08-01 16:21:11 +00005664/**
Max Reitz081e4652019-06-12 18:14:13 +02005665 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5666 * sums the size of all data-bearing children. (This excludes backing
5667 * children.)
5668 */
5669static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5670{
5671 BdrvChild *child;
5672 int64_t child_size, sum = 0;
5673
5674 QLIST_FOREACH(child, &bs->children, next) {
5675 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5676 BDRV_CHILD_FILTERED))
5677 {
5678 child_size = bdrv_get_allocated_file_size(child->bs);
5679 if (child_size < 0) {
5680 return child_size;
5681 }
5682 sum += child_size;
5683 }
5684 }
5685
5686 return sum;
5687}
5688
5689/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005690 * Length of a allocated file in bytes. Sparse files are counted by actual
5691 * allocated space. Return < 0 if error or unknown.
5692 */
5693int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5694{
5695 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005696 IO_CODE();
5697
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005698 if (!drv) {
5699 return -ENOMEDIUM;
5700 }
5701 if (drv->bdrv_get_allocated_file_size) {
5702 return drv->bdrv_get_allocated_file_size(bs);
5703 }
Max Reitz081e4652019-06-12 18:14:13 +02005704
5705 if (drv->bdrv_file_open) {
5706 /*
5707 * Protocol drivers default to -ENOTSUP (most of their data is
5708 * not stored in any of their children (if they even have any),
5709 * so there is no generic way to figure it out).
5710 */
5711 return -ENOTSUP;
5712 } else if (drv->is_filter) {
5713 /* Filter drivers default to the size of their filtered child */
5714 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5715 } else {
5716 /* Other drivers default to summing their children's sizes */
5717 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005718 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005719}
5720
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005721/*
5722 * bdrv_measure:
5723 * @drv: Format driver
5724 * @opts: Creation options for new image
5725 * @in_bs: Existing image containing data for new image (may be NULL)
5726 * @errp: Error object
5727 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5728 * or NULL on error
5729 *
5730 * Calculate file size required to create a new image.
5731 *
5732 * If @in_bs is given then space for allocated clusters and zero clusters
5733 * from that image are included in the calculation. If @opts contains a
5734 * backing file that is shared by @in_bs then backing clusters may be omitted
5735 * from the calculation.
5736 *
5737 * If @in_bs is NULL then the calculation includes no allocated clusters
5738 * unless a preallocation option is given in @opts.
5739 *
5740 * Note that @in_bs may use a different BlockDriver from @drv.
5741 *
5742 * If an error occurs the @errp pointer is set.
5743 */
5744BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5745 BlockDriverState *in_bs, Error **errp)
5746{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005747 IO_CODE();
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005748 if (!drv->bdrv_measure) {
5749 error_setg(errp, "Block driver '%s' does not support size measurement",
5750 drv->format_name);
5751 return NULL;
5752 }
5753
5754 return drv->bdrv_measure(opts, in_bs, errp);
5755}
5756
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005757/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005758 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005759 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005760int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005761{
5762 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005763 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005764
bellard83f64092006-08-01 16:21:11 +00005765 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005766 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005767
Kevin Wolfb94a2612013-10-29 12:18:58 +01005768 if (drv->has_variable_length) {
5769 int ret = refresh_total_sectors(bs, bs->total_sectors);
5770 if (ret < 0) {
5771 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005772 }
bellard83f64092006-08-01 16:21:11 +00005773 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005774 return bs->total_sectors;
5775}
5776
5777/**
5778 * Return length in bytes on success, -errno on error.
5779 * The length is always a multiple of BDRV_SECTOR_SIZE.
5780 */
5781int64_t bdrv_getlength(BlockDriverState *bs)
5782{
5783 int64_t ret = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005784 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005785
Eric Blake122860b2020-11-05 09:51:22 -06005786 if (ret < 0) {
5787 return ret;
5788 }
5789 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5790 return -EFBIG;
5791 }
5792 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005793}
5794
bellard19cb3732006-08-19 11:45:59 +00005795/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005796void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005797{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005798 int64_t nb_sectors = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005799 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005800
5801 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005802}
bellardcf989512004-02-16 21:56:36 +00005803
Eric Blake54115412016-06-23 16:37:26 -06005804bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005805{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005806 IO_CODE();
ths985a03b2007-12-24 16:10:43 +00005807 return bs->sg;
5808}
5809
Max Reitzae23f782019-06-12 22:57:15 +02005810/**
5811 * Return whether the given node supports compressed writes.
5812 */
5813bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5814{
5815 BlockDriverState *filtered;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005816 IO_CODE();
Max Reitzae23f782019-06-12 22:57:15 +02005817
5818 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5819 return false;
5820 }
5821
5822 filtered = bdrv_filter_bs(bs);
5823 if (filtered) {
5824 /*
5825 * Filters can only forward compressed writes, so we have to
5826 * check the child.
5827 */
5828 return bdrv_supports_compressed_writes(filtered);
5829 }
5830
5831 return true;
5832}
5833
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005834const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005835{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005836 IO_CODE();
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005837 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005838}
5839
Stefan Hajnocziada42402014-08-27 12:08:55 +01005840static int qsort_strcmp(const void *a, const void *b)
5841{
Max Reitzceff5bd2016-10-12 22:49:05 +02005842 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005843}
5844
ths5fafdf22007-09-16 21:08:06 +00005845void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005846 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005847{
5848 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005849 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005850 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005851 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005852
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005853 GLOBAL_STATE_CODE();
5854
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005855 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005856 if (drv->format_name) {
5857 bool found = false;
5858 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005859
5860 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5861 continue;
5862 }
5863
Jeff Codye855e4f2014-04-28 18:29:54 -04005864 while (formats && i && !found) {
5865 found = !strcmp(formats[--i], drv->format_name);
5866 }
5867
5868 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005869 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005870 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005871 }
5872 }
bellardea2384d2004-08-01 21:59:26 +00005873 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005874
Max Reitzeb0df692016-10-12 22:49:06 +02005875 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5876 const char *format_name = block_driver_modules[i].format_name;
5877
5878 if (format_name) {
5879 bool found = false;
5880 int j = count;
5881
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005882 if (use_bdrv_whitelist &&
5883 !bdrv_format_is_whitelisted(format_name, read_only)) {
5884 continue;
5885 }
5886
Max Reitzeb0df692016-10-12 22:49:06 +02005887 while (formats && j && !found) {
5888 found = !strcmp(formats[--j], format_name);
5889 }
5890
5891 if (!found) {
5892 formats = g_renew(const char *, formats, count + 1);
5893 formats[count++] = format_name;
5894 }
5895 }
5896 }
5897
Stefan Hajnocziada42402014-08-27 12:08:55 +01005898 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5899
5900 for (i = 0; i < count; i++) {
5901 it(opaque, formats[i]);
5902 }
5903
Jeff Codye855e4f2014-04-28 18:29:54 -04005904 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005905}
5906
Benoît Canetdc364f42014-01-23 21:31:32 +01005907/* This function is to find a node in the bs graph */
5908BlockDriverState *bdrv_find_node(const char *node_name)
5909{
5910 BlockDriverState *bs;
5911
5912 assert(node_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005913 GLOBAL_STATE_CODE();
Benoît Canetdc364f42014-01-23 21:31:32 +01005914
5915 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5916 if (!strcmp(node_name, bs->node_name)) {
5917 return bs;
5918 }
5919 }
5920 return NULL;
5921}
5922
Benoît Canetc13163f2014-01-23 21:31:34 +01005923/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005924BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5925 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005926{
Eric Blake9812e712020-10-27 00:05:47 -05005927 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005928 BlockDriverState *bs;
5929
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005930 GLOBAL_STATE_CODE();
5931
Benoît Canetc13163f2014-01-23 21:31:34 +01005932 list = NULL;
5933 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005934 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005935 if (!info) {
5936 qapi_free_BlockDeviceInfoList(list);
5937 return NULL;
5938 }
Eric Blake9812e712020-10-27 00:05:47 -05005939 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005940 }
5941
5942 return list;
5943}
5944
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005945typedef struct XDbgBlockGraphConstructor {
5946 XDbgBlockGraph *graph;
5947 GHashTable *graph_nodes;
5948} XDbgBlockGraphConstructor;
5949
5950static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5951{
5952 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5953
5954 gr->graph = g_new0(XDbgBlockGraph, 1);
5955 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5956
5957 return gr;
5958}
5959
5960static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5961{
5962 XDbgBlockGraph *graph = gr->graph;
5963
5964 g_hash_table_destroy(gr->graph_nodes);
5965 g_free(gr);
5966
5967 return graph;
5968}
5969
5970static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5971{
5972 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5973
5974 if (ret != 0) {
5975 return ret;
5976 }
5977
5978 /*
5979 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5980 * answer of g_hash_table_lookup.
5981 */
5982 ret = g_hash_table_size(gr->graph_nodes) + 1;
5983 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5984
5985 return ret;
5986}
5987
5988static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5989 XDbgBlockGraphNodeType type, const char *name)
5990{
5991 XDbgBlockGraphNode *n;
5992
5993 n = g_new0(XDbgBlockGraphNode, 1);
5994
5995 n->id = xdbg_graph_node_num(gr, node);
5996 n->type = type;
5997 n->name = g_strdup(name);
5998
Eric Blake9812e712020-10-27 00:05:47 -05005999 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006000}
6001
6002static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6003 const BdrvChild *child)
6004{
Max Reitzcdb1cec2019-11-08 13:34:52 +01006005 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006006 XDbgBlockGraphEdge *edge;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05006007 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006008
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006009 edge = g_new0(XDbgBlockGraphEdge, 1);
6010
6011 edge->parent = xdbg_graph_node_num(gr, parent);
6012 edge->child = xdbg_graph_node_num(gr, child->bs);
6013 edge->name = g_strdup(child->name);
6014
Max Reitzcdb1cec2019-11-08 13:34:52 +01006015 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6016 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6017
6018 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006019 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006020 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01006021 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006022 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006023 }
6024 }
6025
Eric Blake9812e712020-10-27 00:05:47 -05006026 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006027}
6028
6029
6030XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6031{
6032 BlockBackend *blk;
6033 BlockJob *job;
6034 BlockDriverState *bs;
6035 BdrvChild *child;
6036 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6037
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006038 GLOBAL_STATE_CODE();
6039
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006040 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6041 char *allocated_name = NULL;
6042 const char *name = blk_name(blk);
6043
6044 if (!*name) {
6045 name = allocated_name = blk_get_attached_dev_id(blk);
6046 }
6047 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6048 name);
6049 g_free(allocated_name);
6050 if (blk_root(blk)) {
6051 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6052 }
6053 }
6054
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04006055 WITH_JOB_LOCK_GUARD() {
6056 for (job = block_job_next_locked(NULL); job;
6057 job = block_job_next_locked(job)) {
6058 GSList *el;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006059
Emanuele Giuseppe Esposito880eeec2022-09-26 05:32:04 -04006060 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6061 job->job.id);
6062 for (el = job->nodes; el; el = el->next) {
6063 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6064 }
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006065 }
6066 }
6067
6068 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6069 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6070 bs->node_name);
6071 QLIST_FOREACH(child, &bs->children, next) {
6072 xdbg_graph_add_edge(gr, bs, child);
6073 }
6074 }
6075
6076 return xdbg_graph_finalize(gr);
6077}
6078
Benoît Canet12d3ba82014-01-23 21:31:35 +01006079BlockDriverState *bdrv_lookup_bs(const char *device,
6080 const char *node_name,
6081 Error **errp)
6082{
Markus Armbruster7f06d472014-10-07 13:59:12 +02006083 BlockBackend *blk;
6084 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006085
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006086 GLOBAL_STATE_CODE();
6087
Benoît Canet12d3ba82014-01-23 21:31:35 +01006088 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02006089 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006090
Markus Armbruster7f06d472014-10-07 13:59:12 +02006091 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006092 bs = blk_bs(blk);
6093 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02006094 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02006095 }
6096
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006097 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006098 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006099 }
6100
Benoît Canetdd67fa52014-02-12 17:15:06 +01006101 if (node_name) {
6102 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006103
Benoît Canetdd67fa52014-02-12 17:15:06 +01006104 if (bs) {
6105 return bs;
6106 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006107 }
6108
Connor Kuehl785ec4b2021-03-05 09:19:28 -06006109 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01006110 device ? device : "",
6111 node_name ? node_name : "");
6112 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006113}
6114
Jeff Cody5a6684d2014-06-25 15:40:09 -04006115/* If 'base' is in the same chain as 'top', return true. Otherwise,
6116 * return false. If either argument is NULL, return false. */
6117bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6118{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006119
6120 GLOBAL_STATE_CODE();
6121
Jeff Cody5a6684d2014-06-25 15:40:09 -04006122 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006123 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04006124 }
6125
6126 return top != NULL;
6127}
6128
Fam Zheng04df7652014-10-31 11:32:54 +08006129BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6130{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006131 GLOBAL_STATE_CODE();
Fam Zheng04df7652014-10-31 11:32:54 +08006132 if (!bs) {
6133 return QTAILQ_FIRST(&graph_bdrv_states);
6134 }
6135 return QTAILQ_NEXT(bs, node_list);
6136}
6137
Kevin Wolf0f122642018-03-28 18:29:18 +02006138BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6139{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006140 GLOBAL_STATE_CODE();
Kevin Wolf0f122642018-03-28 18:29:18 +02006141 if (!bs) {
6142 return QTAILQ_FIRST(&all_bdrv_states);
6143 }
6144 return QTAILQ_NEXT(bs, bs_list);
6145}
6146
Fam Zheng20a9e772014-10-31 11:32:55 +08006147const char *bdrv_get_node_name(const BlockDriverState *bs)
6148{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006149 IO_CODE();
Fam Zheng20a9e772014-10-31 11:32:55 +08006150 return bs->node_name;
6151}
6152
Kevin Wolf1f0c4612016-03-22 18:38:44 +01006153const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006154{
6155 BdrvChild *c;
6156 const char *name;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05006157 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006158
6159 /* If multiple parents have a name, just pick the first one. */
6160 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006161 if (c->klass->get_name) {
6162 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006163 if (name && *name) {
6164 return name;
6165 }
6166 }
6167 }
6168
6169 return NULL;
6170}
6171
Markus Armbruster7f06d472014-10-07 13:59:12 +02006172/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02006173const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00006174{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006175 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006176 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00006177}
6178
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006179/* This can be used to identify nodes that might not have a device
6180 * name associated. Since node and device names live in the same
6181 * namespace, the result is unambiguous. The exception is if both are
6182 * absent, then this returns an empty (non-null) string. */
6183const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6184{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006185 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006186 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006187}
6188
Markus Armbrusterc8433282012-06-05 16:49:24 +02006189int bdrv_get_flags(BlockDriverState *bs)
6190{
Hanna Reitz15aee7a2022-04-27 13:40:54 +02006191 IO_CODE();
Markus Armbrusterc8433282012-06-05 16:49:24 +02006192 return bs->open_flags;
6193}
6194
Peter Lieven3ac21622013-06-28 12:47:42 +02006195int bdrv_has_zero_init_1(BlockDriverState *bs)
6196{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006197 GLOBAL_STATE_CODE();
Peter Lieven3ac21622013-06-28 12:47:42 +02006198 return 1;
6199}
6200
Kevin Wolff2feebb2010-04-14 17:30:35 +02006201int bdrv_has_zero_init(BlockDriverState *bs)
6202{
Max Reitz93393e62019-06-12 17:03:38 +02006203 BlockDriverState *filtered;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006204 GLOBAL_STATE_CODE();
Max Reitz93393e62019-06-12 17:03:38 +02006205
Max Reitzd470ad42017-11-10 21:31:09 +01006206 if (!bs->drv) {
6207 return 0;
6208 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006209
Paolo Bonzini11212d82013-09-04 19:00:27 +02006210 /* If BS is a copy on write image, it is initialized to
6211 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02006212 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02006213 return 0;
6214 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02006215 if (bs->drv->bdrv_has_zero_init) {
6216 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02006217 }
Max Reitz93393e62019-06-12 17:03:38 +02006218
6219 filtered = bdrv_filter_bs(bs);
6220 if (filtered) {
6221 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006222 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006223
Peter Lieven3ac21622013-06-28 12:47:42 +02006224 /* safe default */
6225 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02006226}
6227
Peter Lieven4ce78692013-10-24 12:06:54 +02006228bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6229{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006230 IO_CODE();
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03006231 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02006232 return false;
6233 }
6234
Eric Blakee24d8132018-01-26 13:34:39 -06006235 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02006236}
6237
ths5fafdf22007-09-16 21:08:06 +00006238void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00006239 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00006240{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006241 IO_CODE();
Kevin Wolf3574c602011-10-26 11:02:11 +02006242 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00006243}
6244
bellardfaea38e2006-08-05 21:31:00 +00006245int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6246{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006247 int ret;
bellardfaea38e2006-08-05 21:31:00 +00006248 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006249 IO_CODE();
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006250 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6251 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00006252 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006253 }
6254 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02006255 BlockDriverState *filtered = bdrv_filter_bs(bs);
6256 if (filtered) {
6257 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006258 }
bellardfaea38e2006-08-05 21:31:00 +00006259 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006260 }
bellardfaea38e2006-08-05 21:31:00 +00006261 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006262 ret = drv->bdrv_get_info(bs, bdi);
6263 if (ret < 0) {
6264 return ret;
6265 }
6266
6267 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6268 return -EINVAL;
6269 }
6270
6271 return 0;
bellardfaea38e2006-08-05 21:31:00 +00006272}
6273
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006274ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6275 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02006276{
6277 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006278 IO_CODE();
Max Reitzeae041f2013-10-09 10:46:16 +02006279 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006280 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02006281 }
6282 return NULL;
6283}
6284
Anton Nefedovd9245592019-09-23 15:17:37 +03006285BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6286{
6287 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006288 IO_CODE();
Anton Nefedovd9245592019-09-23 15:17:37 +03006289 if (!drv || !drv->bdrv_get_specific_stats) {
6290 return NULL;
6291 }
6292 return drv->bdrv_get_specific_stats(bs);
6293}
6294
Eric Blakea31939e2015-11-18 01:52:54 -07006295void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006296{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006297 IO_CODE();
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006298 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006299 return;
6300 }
6301
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006302 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006303}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006304
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006305static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01006306{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006307 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006308 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02006309 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006310 }
6311
6312 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006313 assert(bs->drv->bdrv_debug_remove_breakpoint);
6314 return bs;
6315 }
6316
6317 return NULL;
6318}
6319
6320int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6321 const char *tag)
6322{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006323 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006324 bs = bdrv_find_debug_node(bs);
6325 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006326 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6327 }
6328
6329 return -ENOTSUP;
6330}
6331
Fam Zheng4cc70e92013-11-20 10:01:54 +08006332int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6333{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006334 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006335 bs = bdrv_find_debug_node(bs);
6336 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006337 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6338 }
6339
6340 return -ENOTSUP;
6341}
6342
Kevin Wolf41c695c2012-12-06 14:32:58 +01006343int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6344{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006345 GLOBAL_STATE_CODE();
Max Reitz938789e2014-03-10 23:44:08 +01006346 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006347 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006348 }
6349
6350 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6351 return bs->drv->bdrv_debug_resume(bs, tag);
6352 }
6353
6354 return -ENOTSUP;
6355}
6356
6357bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6358{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006359 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006360 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006361 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006362 }
6363
6364 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6365 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6366 }
6367
6368 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006369}
6370
Jeff Codyb1b1d782012-10-16 15:49:09 -04006371/* backing_file can either be relative, or absolute, or a protocol. If it is
6372 * relative, it must be relative to the chain. So, passing in bs->filename
6373 * from a BDS as backing_file should not be done, as that may be relative to
6374 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006375BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6376 const char *backing_file)
6377{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006378 char *filename_full = NULL;
6379 char *backing_file_full = NULL;
6380 char *filename_tmp = NULL;
6381 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006382 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006383 BlockDriverState *curr_bs = NULL;
6384 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006385 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006386
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006387 GLOBAL_STATE_CODE();
6388
Jeff Codyb1b1d782012-10-16 15:49:09 -04006389 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006390 return NULL;
6391 }
6392
Jeff Codyb1b1d782012-10-16 15:49:09 -04006393 filename_full = g_malloc(PATH_MAX);
6394 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006395
6396 is_protocol = path_has_protocol(backing_file);
6397
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006398 /*
6399 * Being largely a legacy function, skip any filters here
6400 * (because filters do not have normal filenames, so they cannot
6401 * match anyway; and allowing json:{} filenames is a bit out of
6402 * scope).
6403 */
6404 for (curr_bs = bdrv_skip_filters(bs);
6405 bdrv_cow_child(curr_bs) != NULL;
6406 curr_bs = bs_below)
6407 {
6408 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006409
Max Reitz0b877d02018-08-01 20:34:11 +02006410 if (bdrv_backing_overridden(curr_bs)) {
6411 /*
6412 * If the backing file was overridden, we can only compare
6413 * directly against the backing node's filename.
6414 */
6415
6416 if (!filenames_refreshed) {
6417 /*
6418 * This will automatically refresh all of the
6419 * filenames in the rest of the backing chain, so we
6420 * only need to do this once.
6421 */
6422 bdrv_refresh_filename(bs_below);
6423 filenames_refreshed = true;
6424 }
6425
6426 if (strcmp(backing_file, bs_below->filename) == 0) {
6427 retval = bs_below;
6428 break;
6429 }
6430 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6431 /*
6432 * If either of the filename paths is actually a protocol, then
6433 * compare unmodified paths; otherwise make paths relative.
6434 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006435 char *backing_file_full_ret;
6436
Jeff Codyb1b1d782012-10-16 15:49:09 -04006437 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006438 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006439 break;
6440 }
Jeff Cody418661e2017-01-25 20:08:20 -05006441 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006442 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6443 NULL);
6444 if (backing_file_full_ret) {
6445 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6446 g_free(backing_file_full_ret);
6447 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006448 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006449 break;
6450 }
Jeff Cody418661e2017-01-25 20:08:20 -05006451 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006452 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006453 /* If not an absolute filename path, make it relative to the current
6454 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006455 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6456 NULL);
6457 /* We are going to compare canonicalized absolute pathnames */
6458 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6459 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006460 continue;
6461 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006462 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006463
6464 /* We need to make sure the backing filename we are comparing against
6465 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006466 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6467 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6468 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006469 continue;
6470 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006471 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006472
6473 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006474 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006475 break;
6476 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006477 }
6478 }
6479
Jeff Codyb1b1d782012-10-16 15:49:09 -04006480 g_free(filename_full);
6481 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006482 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006483}
6484
bellardea2384d2004-08-01 21:59:26 +00006485void bdrv_init(void)
6486{
Kevin Wolfe5f05f82021-07-09 18:41:41 +02006487#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6488 use_bdrv_whitelist = 1;
6489#endif
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006490 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006491}
pbrookce1a14d2006-08-07 02:38:06 +00006492
Markus Armbrustereb852012009-10-27 18:41:44 +01006493void bdrv_init_with_whitelist(void)
6494{
6495 use_bdrv_whitelist = 1;
6496 bdrv_init();
6497}
6498
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006499int bdrv_activate(BlockDriverState *bs, Error **errp)
6500{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006501 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006502 Error *local_err = NULL;
6503 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006504 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006505
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006506 GLOBAL_STATE_CODE();
6507
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006508 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006509 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006510 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006511
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006512 QLIST_FOREACH(child, &bs->children, next) {
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006513 bdrv_activate(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006514 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006515 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006516 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006517 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006518 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006519
Kevin Wolfdafe0962017-11-16 13:00:01 +01006520 /*
6521 * Update permissions, they may differ for inactive nodes.
6522 *
6523 * Note that the required permissions of inactive images are always a
6524 * subset of the permissions required after activating the image. This
6525 * allows us to just get the permissions upfront without restricting
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006526 * bdrv_co_invalidate_cache().
Kevin Wolfdafe0962017-11-16 13:00:01 +01006527 *
6528 * It also means that in error cases, we don't have to try and revert to
6529 * the old permissions (which is an operation that could fail, too). We can
6530 * just keep the extended permissions for the next time that an activation
6531 * of the image is tried.
6532 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006533 if (bs->open_flags & BDRV_O_INACTIVE) {
6534 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03006535 ret = bdrv_refresh_perms(bs, NULL, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006536 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006537 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006538 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006539 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006540
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006541 ret = bdrv_invalidate_cache(bs, errp);
6542 if (ret < 0) {
6543 bs->open_flags |= BDRV_O_INACTIVE;
6544 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006545 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006546
Kevin Wolf7bb49412019-12-17 15:06:38 +01006547 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6548 bdrv_dirty_bitmap_skip_store(bm, false);
6549 }
6550
6551 ret = refresh_total_sectors(bs, bs->total_sectors);
6552 if (ret < 0) {
6553 bs->open_flags |= BDRV_O_INACTIVE;
6554 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006555 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006556 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006557 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006558
6559 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006560 if (parent->klass->activate) {
6561 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006562 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006563 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006564 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006565 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006566 }
6567 }
6568 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006569
6570 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006571}
6572
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006573int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6574{
6575 Error *local_err = NULL;
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05006576 IO_CODE();
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006577
6578 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6579
6580 if (bs->drv->bdrv_co_invalidate_cache) {
6581 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6582 if (local_err) {
6583 error_propagate(errp, local_err);
6584 return -EINVAL;
6585 }
6586 }
6587
6588 return 0;
6589}
6590
Emanuele Giuseppe Esposito3b717192022-02-09 05:54:51 -05006591void bdrv_activate_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006592{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006593 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006594 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006595
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006596 GLOBAL_STATE_CODE();
6597
Kevin Wolf88be7b42016-05-20 18:49:07 +02006598 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006599 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006600 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006601
6602 aio_context_acquire(aio_context);
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006603 ret = bdrv_activate(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006604 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006605 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006606 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006607 return;
6608 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006609 }
6610}
6611
Kevin Wolf9e372712018-11-23 15:11:14 +01006612static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6613{
6614 BdrvChild *parent;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006615 GLOBAL_STATE_CODE();
Kevin Wolf9e372712018-11-23 15:11:14 +01006616
6617 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006618 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006619 BlockDriverState *parent_bs = parent->opaque;
6620 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6621 return true;
6622 }
6623 }
6624 }
6625
6626 return false;
6627}
6628
6629static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006630{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006631 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006632 int ret;
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006633 uint64_t cumulative_perms, cumulative_shared_perms;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006634
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05006635 GLOBAL_STATE_CODE();
6636
Max Reitzd470ad42017-11-10 21:31:09 +01006637 if (!bs->drv) {
6638 return -ENOMEDIUM;
6639 }
6640
Kevin Wolf9e372712018-11-23 15:11:14 +01006641 /* Make sure that we don't inactivate a child before its parent.
6642 * It will be covered by recursion from the yet active parent. */
6643 if (bdrv_has_bds_parent(bs, true)) {
6644 return 0;
6645 }
6646
6647 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6648
6649 /* Inactivate this node */
6650 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006651 ret = bs->drv->bdrv_inactivate(bs);
6652 if (ret < 0) {
6653 return ret;
6654 }
6655 }
6656
Kevin Wolf9e372712018-11-23 15:11:14 +01006657 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006658 if (parent->klass->inactivate) {
6659 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006660 if (ret < 0) {
6661 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006662 }
6663 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006664 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006665
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006666 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6667 &cumulative_shared_perms);
6668 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6669 /* Our inactive parents still need write access. Inactivation failed. */
6670 return -EPERM;
6671 }
6672
Kevin Wolf9e372712018-11-23 15:11:14 +01006673 bs->open_flags |= BDRV_O_INACTIVE;
6674
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006675 /*
6676 * Update permissions, they may differ for inactive nodes.
6677 * We only tried to loosen restrictions, so errors are not fatal, ignore
6678 * them.
6679 */
Vladimir Sementsov-Ogievskiyf1316ed2022-11-07 19:35:57 +03006680 bdrv_refresh_perms(bs, NULL, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006681
6682 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006683 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006684 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006685 if (ret < 0) {
6686 return ret;
6687 }
6688 }
6689
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006690 return 0;
6691}
6692
6693int bdrv_inactivate_all(void)
6694{
Max Reitz79720af2016-03-16 19:54:44 +01006695 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006696 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006697 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006698 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006699
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006700 GLOBAL_STATE_CODE();
6701
Kevin Wolf88be7b42016-05-20 18:49:07 +02006702 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006703 AioContext *aio_context = bdrv_get_aio_context(bs);
6704
6705 if (!g_slist_find(aio_ctxs, aio_context)) {
6706 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6707 aio_context_acquire(aio_context);
6708 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006709 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006710
Kevin Wolf9e372712018-11-23 15:11:14 +01006711 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6712 /* Nodes with BDS parents are covered by recursion from the last
6713 * parent that gets inactivated. Don't inactivate them a second
6714 * time if that has already happened. */
6715 if (bdrv_has_bds_parent(bs, false)) {
6716 continue;
6717 }
6718 ret = bdrv_inactivate_recurse(bs);
6719 if (ret < 0) {
6720 bdrv_next_cleanup(&it);
6721 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006722 }
6723 }
6724
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006725out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006726 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6727 AioContext *aio_context = ctx->data;
6728 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006729 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006730 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006731
6732 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006733}
6734
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006735/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006736/* removable device support */
6737
6738/**
6739 * Return TRUE if the media is present
6740 */
Max Reitze031f752015-10-19 17:53:11 +02006741bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006742{
6743 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006744 BdrvChild *child;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006745 IO_CODE();
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006746
Max Reitze031f752015-10-19 17:53:11 +02006747 if (!drv) {
6748 return false;
6749 }
Max Reitz28d7a782015-10-19 17:53:13 +02006750 if (drv->bdrv_is_inserted) {
6751 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006752 }
Max Reitz28d7a782015-10-19 17:53:13 +02006753 QLIST_FOREACH(child, &bs->children, next) {
6754 if (!bdrv_is_inserted(child->bs)) {
6755 return false;
6756 }
6757 }
6758 return true;
bellard19cb3732006-08-19 11:45:59 +00006759}
6760
6761/**
bellard19cb3732006-08-19 11:45:59 +00006762 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6763 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006764void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006765{
6766 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006767 IO_CODE();
bellard19cb3732006-08-19 11:45:59 +00006768
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006769 if (drv && drv->bdrv_eject) {
6770 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006771 }
bellard19cb3732006-08-19 11:45:59 +00006772}
6773
bellard19cb3732006-08-19 11:45:59 +00006774/**
6775 * Lock or unlock the media (if it is locked, the user won't be able
6776 * to eject it manually).
6777 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006778void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006779{
6780 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006781 IO_CODE();
Markus Armbruster025e8492011-09-06 18:58:47 +02006782 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006783
Markus Armbruster025e8492011-09-06 18:58:47 +02006784 if (drv && drv->bdrv_lock_medium) {
6785 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006786 }
6787}
ths985a03b2007-12-24 16:10:43 +00006788
Fam Zheng9fcb0252013-08-23 09:14:46 +08006789/* Get a reference to bs */
6790void bdrv_ref(BlockDriverState *bs)
6791{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006792 GLOBAL_STATE_CODE();
Fam Zheng9fcb0252013-08-23 09:14:46 +08006793 bs->refcnt++;
6794}
6795
6796/* Release a previously grabbed reference to bs.
6797 * If after releasing, reference count is zero, the BlockDriverState is
6798 * deleted. */
6799void bdrv_unref(BlockDriverState *bs)
6800{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006801 GLOBAL_STATE_CODE();
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006802 if (!bs) {
6803 return;
6804 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006805 assert(bs->refcnt > 0);
6806 if (--bs->refcnt == 0) {
6807 bdrv_delete(bs);
6808 }
6809}
6810
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006811struct BdrvOpBlocker {
6812 Error *reason;
6813 QLIST_ENTRY(BdrvOpBlocker) list;
6814};
6815
6816bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6817{
6818 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006819 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006820 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6821 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6822 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006823 error_propagate_prepend(errp, error_copy(blocker->reason),
6824 "Node '%s' is busy: ",
6825 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006826 return true;
6827 }
6828 return false;
6829}
6830
6831void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6832{
6833 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006834 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006835 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6836
Markus Armbruster5839e532014-08-19 10:31:08 +02006837 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006838 blocker->reason = reason;
6839 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6840}
6841
6842void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6843{
6844 BdrvOpBlocker *blocker, *next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006845 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006846 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6847 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6848 if (blocker->reason == reason) {
6849 QLIST_REMOVE(blocker, list);
6850 g_free(blocker);
6851 }
6852 }
6853}
6854
6855void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6856{
6857 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006858 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006859 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6860 bdrv_op_block(bs, i, reason);
6861 }
6862}
6863
6864void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6865{
6866 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006867 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006868 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6869 bdrv_op_unblock(bs, i, reason);
6870 }
6871}
6872
6873bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6874{
6875 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006876 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006877 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6878 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6879 return false;
6880 }
6881 }
6882 return true;
6883}
6884
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006885void bdrv_img_create(const char *filename, const char *fmt,
6886 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006887 char *options, uint64_t img_size, int flags, bool quiet,
6888 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006889{
Chunyan Liu83d05212014-06-05 17:20:51 +08006890 QemuOptsList *create_opts = NULL;
6891 QemuOpts *opts = NULL;
6892 const char *backing_fmt, *backing_file;
6893 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006894 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006895 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006896 int ret = 0;
6897
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006898 GLOBAL_STATE_CODE();
6899
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006900 /* Find driver and parse its options */
6901 drv = bdrv_find_format(fmt);
6902 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006903 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006904 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006905 }
6906
Max Reitzb65a5e12015-02-05 13:58:12 -05006907 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006908 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006909 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006910 }
6911
Max Reitzc6149722014-12-02 18:32:45 +01006912 if (!drv->create_opts) {
6913 error_setg(errp, "Format driver '%s' does not support image creation",
6914 drv->format_name);
6915 return;
6916 }
6917
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006918 if (!proto_drv->create_opts) {
6919 error_setg(errp, "Protocol driver '%s' does not support image creation",
6920 proto_drv->format_name);
6921 return;
6922 }
6923
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006924 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006925 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006926 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006927
Chunyan Liu83d05212014-06-05 17:20:51 +08006928 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006929
6930 /* Parse -o options */
6931 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006932 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006933 goto out;
6934 }
6935 }
6936
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006937 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6938 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6939 } else if (img_size != UINT64_C(-1)) {
6940 error_setg(errp, "The image size must be specified only once");
6941 goto out;
6942 }
6943
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006944 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006945 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006946 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006947 error_setg(errp, "Backing file not supported for file format '%s'",
6948 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006949 goto out;
6950 }
6951 }
6952
6953 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006954 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006955 error_setg(errp, "Backing file format not supported for file "
6956 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006957 goto out;
6958 }
6959 }
6960
Chunyan Liu83d05212014-06-05 17:20:51 +08006961 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6962 if (backing_file) {
6963 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006964 error_setg(errp, "Error: Trying to create an image with the "
6965 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006966 goto out;
6967 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006968 if (backing_file[0] == '\0') {
6969 error_setg(errp, "Expected backing file name, got empty string");
6970 goto out;
6971 }
Jes Sorensen792da932010-12-16 13:52:17 +01006972 }
6973
Chunyan Liu83d05212014-06-05 17:20:51 +08006974 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006975
John Snow6e6e55f2017-07-17 20:34:22 -04006976 /* The size for the image must always be specified, unless we have a backing
6977 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006978 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006979 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6980 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006981 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006982 int back_flags;
6983 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006984
Max Reitz645ae7d2019-02-01 20:29:14 +01006985 full_backing =
6986 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6987 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006988 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006989 goto out;
6990 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006991 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006992
Max Reitzd5b23992021-06-22 16:00:30 +02006993 /*
6994 * No need to do I/O here, which allows us to open encrypted
6995 * backing images without needing the secret
6996 */
John Snow6e6e55f2017-07-17 20:34:22 -04006997 back_flags = flags;
6998 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02006999 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04007000
Fam Zhengcc954f02017-12-15 16:04:45 +08007001 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04007002 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04007003 qdict_put_str(backing_options, "driver", backing_fmt);
7004 }
Fam Zhengcc954f02017-12-15 16:04:45 +08007005 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04007006
7007 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7008 &local_err);
7009 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05007010 if (!bs) {
7011 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04007012 goto out;
7013 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05007014 if (!backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007015 error_setg(&local_err,
7016 "Backing file specified without backing format");
7017 error_append_hint(&local_err, "Detected format of %s.",
7018 bs->drv->format_name);
7019 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007020 }
John Snow6e6e55f2017-07-17 20:34:22 -04007021 if (size == -1) {
7022 /* Opened BS, have no size */
7023 size = bdrv_getlength(bs);
7024 if (size < 0) {
7025 error_setg_errno(errp, -size, "Could not get size of '%s'",
7026 backing_file);
7027 bdrv_unref(bs);
7028 goto out;
7029 }
7030 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7031 }
7032 bdrv_unref(bs);
7033 }
Eric Blaked9f059a2020-07-06 15:39:54 -05007034 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7035 } else if (backing_file && !backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007036 error_setg(&local_err,
7037 "Backing file specified without backing format");
7038 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007039 }
John Snow6e6e55f2017-07-17 20:34:22 -04007040
7041 if (size == -1) {
7042 error_setg(errp, "Image creation needs a size parameter");
7043 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007044 }
7045
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007046 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02007047 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08007048 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007049 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05007050 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007051 }
Chunyan Liu83d05212014-06-05 17:20:51 +08007052
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007053 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08007054
Max Reitzcc84d902013-09-06 17:14:26 +02007055 if (ret == -EFBIG) {
7056 /* This is generally a better message than whatever the driver would
7057 * deliver (especially because of the cluster_size_hint), since that
7058 * is most probably not much different from "image too large". */
7059 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08007060 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02007061 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007062 }
Max Reitzcc84d902013-09-06 17:14:26 +02007063 error_setg(errp, "The image size is too large for file format '%s'"
7064 "%s", fmt, cluster_size_hint);
7065 error_free(local_err);
7066 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007067 }
7068
7069out:
Chunyan Liu83d05212014-06-05 17:20:51 +08007070 qemu_opts_del(opts);
7071 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03007072 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007073}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007074
7075AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7076{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007077 IO_CODE();
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00007078 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007079}
7080
Kevin Wolfe336fd42020-10-05 17:58:53 +02007081AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7082{
7083 Coroutine *self = qemu_coroutine_self();
7084 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7085 AioContext *new_ctx;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007086 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007087
7088 /*
7089 * Increase bs->in_flight to ensure that this operation is completed before
7090 * moving the node to a different AioContext. Read new_ctx only afterwards.
7091 */
7092 bdrv_inc_in_flight(bs);
7093
7094 new_ctx = bdrv_get_aio_context(bs);
7095 aio_co_reschedule_self(new_ctx);
7096 return old_ctx;
7097}
7098
7099void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7100{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007101 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007102 aio_co_reschedule_self(old_ctx);
7103 bdrv_dec_in_flight(bs);
7104}
7105
Kevin Wolf18c6ac12020-10-05 17:58:54 +02007106void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7107{
7108 AioContext *ctx = bdrv_get_aio_context(bs);
7109
7110 /* In the main thread, bs->aio_context won't change concurrently */
7111 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7112
7113 /*
7114 * We're in coroutine context, so we already hold the lock of the main
7115 * loop AioContext. Don't lock it twice to avoid deadlocks.
7116 */
7117 assert(qemu_in_coroutine());
7118 if (ctx != qemu_get_aio_context()) {
7119 aio_context_acquire(ctx);
7120 }
7121}
7122
7123void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7124{
7125 AioContext *ctx = bdrv_get_aio_context(bs);
7126
7127 assert(qemu_in_coroutine());
7128 if (ctx != qemu_get_aio_context()) {
7129 aio_context_release(ctx);
7130 }
7131}
7132
Fam Zheng052a7572017-04-10 20:09:25 +08007133void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7134{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007135 IO_CODE();
Fam Zheng052a7572017-04-10 20:09:25 +08007136 aio_co_enter(bdrv_get_aio_context(bs), co);
7137}
7138
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007139static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7140{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05007141 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007142 QLIST_REMOVE(ban, list);
7143 g_free(ban);
7144}
7145
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007146static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007147{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007148 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007149
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007150 assert(!bs->walking_aio_notifiers);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007151 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007152 bs->walking_aio_notifiers = true;
7153 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7154 if (baf->deleted) {
7155 bdrv_do_remove_aio_context_notifier(baf);
7156 } else {
7157 baf->detach_aio_context(baf->opaque);
7158 }
Max Reitz33384422014-06-20 21:57:33 +02007159 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007160 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7161 * remove remaining aio notifiers if we aren't called again.
7162 */
7163 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02007164
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007165 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007166 bs->drv->bdrv_detach_aio_context(bs);
7167 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007168
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007169 if (bs->quiesce_counter) {
7170 aio_enable_external(bs->aio_context);
7171 }
Emanuele Giuseppe Esposito7f898612022-10-25 04:49:43 -04007172 assert_bdrv_graph_writable(bs);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007173 bs->aio_context = NULL;
7174}
7175
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007176static void bdrv_attach_aio_context(BlockDriverState *bs,
7177 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007178{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007179 BdrvAioNotifier *ban, *ban_tmp;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007180 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007181
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007182 if (bs->quiesce_counter) {
7183 aio_disable_external(new_context);
7184 }
7185
Emanuele Giuseppe Esposito7f898612022-10-25 04:49:43 -04007186 assert_bdrv_graph_writable(bs);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007187 bs->aio_context = new_context;
7188
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007189 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007190 bs->drv->bdrv_attach_aio_context(bs, new_context);
7191 }
Max Reitz33384422014-06-20 21:57:33 +02007192
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007193 assert(!bs->walking_aio_notifiers);
7194 bs->walking_aio_notifiers = true;
7195 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7196 if (ban->deleted) {
7197 bdrv_do_remove_aio_context_notifier(ban);
7198 } else {
7199 ban->attached_aio_context(new_context, ban->opaque);
7200 }
Max Reitz33384422014-06-20 21:57:33 +02007201 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007202 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007203}
7204
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007205typedef struct BdrvStateSetAioContext {
7206 AioContext *new_ctx;
7207 BlockDriverState *bs;
7208} BdrvStateSetAioContext;
7209
7210static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007211 GHashTable *visited,
7212 Transaction *tran,
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007213 Error **errp)
7214{
7215 GLOBAL_STATE_CODE();
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007216 if (g_hash_table_contains(visited, c)) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007217 return true;
7218 }
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007219 g_hash_table_add(visited, c);
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007220
7221 /*
7222 * A BdrvChildClass that doesn't handle AioContext changes cannot
7223 * tolerate any AioContext changes
7224 */
7225 if (!c->klass->change_aio_ctx) {
7226 char *user = bdrv_child_user_desc(c);
7227 error_setg(errp, "Changing iothreads is not supported by %s", user);
7228 g_free(user);
7229 return false;
7230 }
7231 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7232 assert(!errp || *errp);
7233 return false;
7234 }
7235 return true;
7236}
7237
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007238bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007239 GHashTable *visited, Transaction *tran,
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007240 Error **errp)
7241{
7242 GLOBAL_STATE_CODE();
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007243 if (g_hash_table_contains(visited, c)) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007244 return true;
7245 }
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007246 g_hash_table_add(visited, c);
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007247 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7248}
7249
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007250static void bdrv_set_aio_context_clean(void *opaque)
7251{
7252 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7253 BlockDriverState *bs = (BlockDriverState *) state->bs;
7254
7255 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7256 bdrv_drained_end(bs);
7257
7258 g_free(state);
7259}
7260
7261static void bdrv_set_aio_context_commit(void *opaque)
7262{
7263 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7264 BlockDriverState *bs = (BlockDriverState *) state->bs;
7265 AioContext *new_context = state->new_ctx;
7266 AioContext *old_context = bdrv_get_aio_context(bs);
7267 assert_bdrv_graph_writable(bs);
7268
7269 /*
7270 * Take the old AioContex when detaching it from bs.
7271 * At this point, new_context lock is already acquired, and we are now
7272 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7273 * does not call AIO_POLL_WHILE().
7274 */
7275 if (old_context != qemu_get_aio_context()) {
7276 aio_context_acquire(old_context);
7277 }
7278 bdrv_detach_aio_context(bs);
7279 if (old_context != qemu_get_aio_context()) {
7280 aio_context_release(old_context);
7281 }
7282 bdrv_attach_aio_context(bs, new_context);
7283}
7284
7285static TransactionActionDrv set_aio_context = {
7286 .commit = bdrv_set_aio_context_commit,
7287 .clean = bdrv_set_aio_context_clean,
7288};
7289
Kevin Wolf42a65f02019-05-07 18:31:38 +02007290/*
7291 * Changes the AioContext used for fd handlers, timers, and BHs by this
7292 * BlockDriverState and all its children and parents.
7293 *
Max Reitz43eaaae2019-07-22 15:30:54 +02007294 * Must be called from the main AioContext.
7295 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02007296 * The caller must own the AioContext lock for the old AioContext of bs, but it
7297 * must not own the AioContext lock for new_context (unless new_context is the
7298 * same as the current context of bs).
7299 *
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007300 * @visited will accumulate all visited BdrvChild objects. The caller is
Kevin Wolf42a65f02019-05-07 18:31:38 +02007301 * responsible for freeing the list afterwards.
7302 */
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007303static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007304 GHashTable *visited, Transaction *tran,
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007305 Error **errp)
Kevin Wolf5d231842019-05-06 19:17:56 +02007306{
7307 BdrvChild *c;
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007308 BdrvStateSetAioContext *state;
7309
7310 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007311
7312 if (bdrv_get_aio_context(bs) == ctx) {
7313 return true;
7314 }
7315
7316 QLIST_FOREACH(c, &bs->parents, next_parent) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007317 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007318 return false;
7319 }
7320 }
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007321
Kevin Wolf5d231842019-05-06 19:17:56 +02007322 QLIST_FOREACH(c, &bs->children, next) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007323 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007324 return false;
7325 }
7326 }
7327
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007328 state = g_new(BdrvStateSetAioContext, 1);
7329 *state = (BdrvStateSetAioContext) {
7330 .new_ctx = ctx,
7331 .bs = bs,
7332 };
7333
7334 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7335 bdrv_drained_begin(bs);
7336
7337 tran_add(tran, &set_aio_context, state);
7338
Kevin Wolf5d231842019-05-06 19:17:56 +02007339 return true;
7340}
7341
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007342/*
7343 * Change bs's and recursively all of its parents' and children's AioContext
7344 * to the given new context, returning an error if that isn't possible.
7345 *
7346 * If ignore_child is not NULL, that child (and its subgraph) will not
7347 * be touched.
7348 *
7349 * This function still requires the caller to take the bs current
7350 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7351 * assumes the lock is always held if bs is in another AioContext.
7352 * For the same reason, it temporarily also holds the new AioContext, since
7353 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7354 * Therefore the new AioContext lock must not be taken by the caller.
7355 */
Emanuele Giuseppe Espositoa41cfda2022-10-25 04:49:51 -04007356int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7357 BdrvChild *ignore_child, Error **errp)
Kevin Wolf5d231842019-05-06 19:17:56 +02007358{
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007359 Transaction *tran;
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007360 GHashTable *visited;
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007361 int ret;
7362 AioContext *old_context = bdrv_get_aio_context(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007363 GLOBAL_STATE_CODE();
7364
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007365 /*
7366 * Recursion phase: go through all nodes of the graph.
7367 * Take care of checking that all nodes support changing AioContext
7368 * and drain them, builing a linear list of callbacks to run if everything
7369 * is successful (the transaction itself).
7370 */
7371 tran = tran_new();
Emanuele Giuseppe Espositoe08cc002022-10-25 04:49:45 -04007372 visited = g_hash_table_new(NULL, NULL);
7373 if (ignore_child) {
7374 g_hash_table_add(visited, ignore_child);
7375 }
7376 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7377 g_hash_table_destroy(visited);
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007378
7379 /*
7380 * Linear phase: go through all callbacks collected in the transaction.
7381 * Run all callbacks collected in the recursion to switch all nodes
7382 * AioContext lock (transaction commit), or undo all changes done in the
7383 * recursion (transaction abort).
7384 */
Kevin Wolf5d231842019-05-06 19:17:56 +02007385
7386 if (!ret) {
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007387 /* Just run clean() callbacks. No AioContext changed. */
7388 tran_abort(tran);
Kevin Wolf5d231842019-05-06 19:17:56 +02007389 return -EPERM;
7390 }
7391
Emanuele Giuseppe Esposito7e8c1822022-10-25 04:49:44 -04007392 /*
7393 * Release old AioContext, it won't be needed anymore, as all
7394 * bdrv_drained_begin() have been called already.
7395 */
7396 if (qemu_get_aio_context() != old_context) {
7397 aio_context_release(old_context);
7398 }
7399
7400 /*
7401 * Acquire new AioContext since bdrv_drained_end() is going to be called
7402 * after we switched all nodes in the new AioContext, and the function
7403 * assumes that the lock of the bs is always taken.
7404 */
7405 if (qemu_get_aio_context() != ctx) {
7406 aio_context_acquire(ctx);
7407 }
7408
7409 tran_commit(tran);
7410
7411 if (qemu_get_aio_context() != ctx) {
7412 aio_context_release(ctx);
7413 }
7414
7415 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7416 if (qemu_get_aio_context() != old_context) {
7417 aio_context_acquire(old_context);
7418 }
Kevin Wolf53a7d042019-05-06 19:17:59 +02007419
Kevin Wolf5d231842019-05-06 19:17:56 +02007420 return 0;
7421}
7422
Max Reitz33384422014-06-20 21:57:33 +02007423void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7424 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7425 void (*detach_aio_context)(void *opaque), void *opaque)
7426{
7427 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7428 *ban = (BdrvAioNotifier){
7429 .attached_aio_context = attached_aio_context,
7430 .detach_aio_context = detach_aio_context,
7431 .opaque = opaque
7432 };
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007433 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007434
7435 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7436}
7437
7438void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7439 void (*attached_aio_context)(AioContext *,
7440 void *),
7441 void (*detach_aio_context)(void *),
7442 void *opaque)
7443{
7444 BdrvAioNotifier *ban, *ban_next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007445 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007446
7447 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7448 if (ban->attached_aio_context == attached_aio_context &&
7449 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007450 ban->opaque == opaque &&
7451 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007452 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007453 if (bs->walking_aio_notifiers) {
7454 ban->deleted = true;
7455 } else {
7456 bdrv_do_remove_aio_context_notifier(ban);
7457 }
Max Reitz33384422014-06-20 21:57:33 +02007458 return;
7459 }
7460 }
7461
7462 abort();
7463}
7464
Max Reitz77485432014-10-27 11:12:50 +01007465int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007466 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007467 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007468 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007469{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007470 GLOBAL_STATE_CODE();
Max Reitzd470ad42017-11-10 21:31:09 +01007471 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007472 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007473 return -ENOMEDIUM;
7474 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007475 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007476 error_setg(errp, "Block driver '%s' does not support option amendment",
7477 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007478 return -ENOTSUP;
7479 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007480 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7481 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007482}
Benoît Canetf6186f42013-10-02 14:33:48 +02007483
Max Reitz5d69b5a2020-02-18 11:34:41 +01007484/*
7485 * This function checks whether the given @to_replace is allowed to be
7486 * replaced by a node that always shows the same data as @bs. This is
7487 * used for example to verify whether the mirror job can replace
7488 * @to_replace by the target mirrored from @bs.
7489 * To be replaceable, @bs and @to_replace may either be guaranteed to
7490 * always show the same data (because they are only connected through
7491 * filters), or some driver may allow replacing one of its children
7492 * because it can guarantee that this child's data is not visible at
7493 * all (for example, for dissenting quorum children that have no other
7494 * parents).
7495 */
7496bool bdrv_recurse_can_replace(BlockDriverState *bs,
7497 BlockDriverState *to_replace)
7498{
Max Reitz93393e62019-06-12 17:03:38 +02007499 BlockDriverState *filtered;
7500
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007501 GLOBAL_STATE_CODE();
7502
Max Reitz5d69b5a2020-02-18 11:34:41 +01007503 if (!bs || !bs->drv) {
7504 return false;
7505 }
7506
7507 if (bs == to_replace) {
7508 return true;
7509 }
7510
7511 /* See what the driver can do */
7512 if (bs->drv->bdrv_recurse_can_replace) {
7513 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7514 }
7515
7516 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007517 filtered = bdrv_filter_bs(bs);
7518 if (filtered) {
7519 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007520 }
7521
7522 /* Safe default */
7523 return false;
7524}
7525
Max Reitz810803a2020-02-18 11:34:44 +01007526/*
7527 * Check whether the given @node_name can be replaced by a node that
7528 * has the same data as @parent_bs. If so, return @node_name's BDS;
7529 * NULL otherwise.
7530 *
7531 * @node_name must be a (recursive) *child of @parent_bs (or this
7532 * function will return NULL).
7533 *
7534 * The result (whether the node can be replaced or not) is only valid
7535 * for as long as no graph or permission changes occur.
7536 */
Wen Congyange12f3782015-07-17 10:12:22 +08007537BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7538 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007539{
7540 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007541 AioContext *aio_context;
7542
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007543 GLOBAL_STATE_CODE();
7544
Benoît Canet09158f02014-06-27 18:25:25 +02007545 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007546 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007547 return NULL;
7548 }
7549
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007550 aio_context = bdrv_get_aio_context(to_replace_bs);
7551 aio_context_acquire(aio_context);
7552
Benoît Canet09158f02014-06-27 18:25:25 +02007553 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007554 to_replace_bs = NULL;
7555 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007556 }
7557
7558 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7559 * most non filter in order to prevent data corruption.
7560 * Another benefit is that this tests exclude backing files which are
7561 * blocked by the backing blockers.
7562 */
Max Reitz810803a2020-02-18 11:34:44 +01007563 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7564 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7565 "because it cannot be guaranteed that doing so would not "
7566 "lead to an abrupt change of visible data",
7567 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007568 to_replace_bs = NULL;
7569 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007570 }
7571
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007572out:
7573 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007574 return to_replace_bs;
7575}
Ming Lei448ad912014-07-04 18:04:33 +08007576
Max Reitz97e2f022019-02-01 20:29:27 +01007577/**
7578 * Iterates through the list of runtime option keys that are said to
7579 * be "strong" for a BDS. An option is called "strong" if it changes
7580 * a BDS's data. For example, the null block driver's "size" and
7581 * "read-zeroes" options are strong, but its "latency-ns" option is
7582 * not.
7583 *
7584 * If a key returned by this function ends with a dot, all options
7585 * starting with that prefix are strong.
7586 */
7587static const char *const *strong_options(BlockDriverState *bs,
7588 const char *const *curopt)
7589{
7590 static const char *const global_options[] = {
7591 "driver", "filename", NULL
7592 };
7593
7594 if (!curopt) {
7595 return &global_options[0];
7596 }
7597
7598 curopt++;
7599 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7600 curopt = bs->drv->strong_runtime_opts;
7601 }
7602
7603 return (curopt && *curopt) ? curopt : NULL;
7604}
7605
7606/**
7607 * Copies all strong runtime options from bs->options to the given
7608 * QDict. The set of strong option keys is determined by invoking
7609 * strong_options().
7610 *
7611 * Returns true iff any strong option was present in bs->options (and
7612 * thus copied to the target QDict) with the exception of "filename"
7613 * and "driver". The caller is expected to use this value to decide
7614 * whether the existence of strong options prevents the generation of
7615 * a plain filename.
7616 */
7617static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7618{
7619 bool found_any = false;
7620 const char *const *option_name = NULL;
7621
7622 if (!bs->drv) {
7623 return false;
7624 }
7625
7626 while ((option_name = strong_options(bs, option_name))) {
7627 bool option_given = false;
7628
7629 assert(strlen(*option_name) > 0);
7630 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7631 QObject *entry = qdict_get(bs->options, *option_name);
7632 if (!entry) {
7633 continue;
7634 }
7635
7636 qdict_put_obj(d, *option_name, qobject_ref(entry));
7637 option_given = true;
7638 } else {
7639 const QDictEntry *entry;
7640 for (entry = qdict_first(bs->options); entry;
7641 entry = qdict_next(bs->options, entry))
7642 {
7643 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7644 qdict_put_obj(d, qdict_entry_key(entry),
7645 qobject_ref(qdict_entry_value(entry)));
7646 option_given = true;
7647 }
7648 }
7649 }
7650
7651 /* While "driver" and "filename" need to be included in a JSON filename,
7652 * their existence does not prohibit generation of a plain filename. */
7653 if (!found_any && option_given &&
7654 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7655 {
7656 found_any = true;
7657 }
7658 }
7659
Max Reitz62a01a272019-02-01 20:29:34 +01007660 if (!qdict_haskey(d, "driver")) {
7661 /* Drivers created with bdrv_new_open_driver() may not have a
7662 * @driver option. Add it here. */
7663 qdict_put_str(d, "driver", bs->drv->format_name);
7664 }
7665
Max Reitz97e2f022019-02-01 20:29:27 +01007666 return found_any;
7667}
7668
Max Reitz90993622019-02-01 20:29:09 +01007669/* Note: This function may return false positives; it may return true
7670 * even if opening the backing file specified by bs's image header
7671 * would result in exactly bs->backing. */
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -05007672static bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007673{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007674 GLOBAL_STATE_CODE();
Max Reitz90993622019-02-01 20:29:09 +01007675 if (bs->backing) {
7676 return strcmp(bs->auto_backing_file,
7677 bs->backing->bs->filename);
7678 } else {
7679 /* No backing BDS, so if the image header reports any backing
7680 * file, it must have been suppressed */
7681 return bs->auto_backing_file[0] != '\0';
7682 }
7683}
7684
Max Reitz91af7012014-07-18 20:24:56 +02007685/* Updates the following BDS fields:
7686 * - exact_filename: A filename which may be used for opening a block device
7687 * which (mostly) equals the given BDS (even without any
7688 * other options; so reading and writing must return the same
7689 * results, but caching etc. may be different)
7690 * - full_open_options: Options which, when given when opening a block device
7691 * (without a filename), result in a BDS (mostly)
7692 * equalling the given one
7693 * - filename: If exact_filename is set, it is copied here. Otherwise,
7694 * full_open_options is converted to a JSON object, prefixed with
7695 * "json:" (for use through the JSON pseudo protocol) and put here.
7696 */
7697void bdrv_refresh_filename(BlockDriverState *bs)
7698{
7699 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007700 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007701 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007702 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007703 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007704 bool generate_json_filename; /* Whether our default implementation should
7705 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007706
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007707 GLOBAL_STATE_CODE();
7708
Max Reitz91af7012014-07-18 20:24:56 +02007709 if (!drv) {
7710 return;
7711 }
7712
Max Reitze24518e2019-02-01 20:29:06 +01007713 /* This BDS's file name may depend on any of its children's file names, so
7714 * refresh those first */
7715 QLIST_FOREACH(child, &bs->children, next) {
7716 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007717 }
7718
Max Reitzbb808d52019-02-01 20:29:07 +01007719 if (bs->implicit) {
7720 /* For implicit nodes, just copy everything from the single child */
7721 child = QLIST_FIRST(&bs->children);
7722 assert(QLIST_NEXT(child, next) == NULL);
7723
7724 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7725 child->bs->exact_filename);
7726 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7727
Pan Nengyuancb895612020-01-16 16:56:00 +08007728 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007729 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7730
7731 return;
7732 }
7733
Max Reitz90993622019-02-01 20:29:09 +01007734 backing_overridden = bdrv_backing_overridden(bs);
7735
7736 if (bs->open_flags & BDRV_O_NO_IO) {
7737 /* Without I/O, the backing file does not change anything.
7738 * Therefore, in such a case (primarily qemu-img), we can
7739 * pretend the backing file has not been overridden even if
7740 * it technically has been. */
7741 backing_overridden = false;
7742 }
7743
Max Reitz97e2f022019-02-01 20:29:27 +01007744 /* Gather the options QDict */
7745 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007746 generate_json_filename = append_strong_runtime_options(opts, bs);
7747 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007748
7749 if (drv->bdrv_gather_child_options) {
7750 /* Some block drivers may not want to present all of their children's
7751 * options, or name them differently from BdrvChild.name */
7752 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7753 } else {
7754 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007755 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007756 /* We can skip the backing BDS if it has not been overridden */
7757 continue;
7758 }
7759
7760 qdict_put(opts, child->name,
7761 qobject_ref(child->bs->full_open_options));
7762 }
7763
7764 if (backing_overridden && !bs->backing) {
7765 /* Force no backing file */
7766 qdict_put_null(opts, "backing");
7767 }
7768 }
7769
7770 qobject_unref(bs->full_open_options);
7771 bs->full_open_options = opts;
7772
Max Reitz52f72d62019-06-12 17:43:03 +02007773 primary_child_bs = bdrv_primary_bs(bs);
7774
Max Reitz998b3a12019-02-01 20:29:28 +01007775 if (drv->bdrv_refresh_filename) {
7776 /* Obsolete information is of no use here, so drop the old file name
7777 * information before refreshing it */
7778 bs->exact_filename[0] = '\0';
7779
7780 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007781 } else if (primary_child_bs) {
7782 /*
7783 * Try to reconstruct valid information from the underlying
7784 * file -- this only works for format nodes (filter nodes
7785 * cannot be probed and as such must be selected by the user
7786 * either through an options dict, or through a special
7787 * filename which the filter driver must construct in its
7788 * .bdrv_refresh_filename() implementation).
7789 */
Max Reitz998b3a12019-02-01 20:29:28 +01007790
7791 bs->exact_filename[0] = '\0';
7792
Max Reitzfb695c72019-02-01 20:29:29 +01007793 /*
7794 * We can use the underlying file's filename if:
7795 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007796 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007797 * - the file is a protocol BDS, and
7798 * - opening that file (as this BDS's format) will automatically create
7799 * the BDS tree we have right now, that is:
7800 * - the user did not significantly change this BDS's behavior with
7801 * some explicit (strong) options
7802 * - no non-file child of this BDS has been overridden by the user
7803 * Both of these conditions are represented by generate_json_filename.
7804 */
Max Reitz52f72d62019-06-12 17:43:03 +02007805 if (primary_child_bs->exact_filename[0] &&
7806 primary_child_bs->drv->bdrv_file_open &&
7807 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007808 {
Max Reitz52f72d62019-06-12 17:43:03 +02007809 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007810 }
7811 }
7812
Max Reitz91af7012014-07-18 20:24:56 +02007813 if (bs->exact_filename[0]) {
7814 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007815 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007816 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007817 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007818 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007819 /* Give user a hint if we truncated things. */
7820 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7821 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007822 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007823 }
7824}
Wen Congyange06018a2016-05-10 15:36:37 +08007825
Max Reitz1e89d0f2019-02-01 20:29:18 +01007826char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7827{
7828 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007829 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007830
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007831 GLOBAL_STATE_CODE();
7832
Max Reitz1e89d0f2019-02-01 20:29:18 +01007833 if (!drv) {
7834 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7835 return NULL;
7836 }
7837
7838 if (drv->bdrv_dirname) {
7839 return drv->bdrv_dirname(bs, errp);
7840 }
7841
Max Reitz52f72d62019-06-12 17:43:03 +02007842 child_bs = bdrv_primary_bs(bs);
7843 if (child_bs) {
7844 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007845 }
7846
7847 bdrv_refresh_filename(bs);
7848 if (bs->exact_filename[0] != '\0') {
7849 return path_combine(bs->exact_filename, "");
7850 }
7851
7852 error_setg(errp, "Cannot generate a base directory for %s nodes",
7853 drv->format_name);
7854 return NULL;
7855}
7856
Wen Congyange06018a2016-05-10 15:36:37 +08007857/*
7858 * Hot add/remove a BDS's child. So the user can take a child offline when
7859 * it is broken and take a new child online
7860 */
7861void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7862 Error **errp)
7863{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007864 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007865 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7866 error_setg(errp, "The node %s does not support adding a child",
7867 bdrv_get_device_or_node_name(parent_bs));
7868 return;
7869 }
7870
7871 if (!QLIST_EMPTY(&child_bs->parents)) {
7872 error_setg(errp, "The node %s already has a parent",
7873 child_bs->node_name);
7874 return;
7875 }
7876
7877 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7878}
7879
7880void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7881{
7882 BdrvChild *tmp;
7883
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007884 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007885 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7886 error_setg(errp, "The node %s does not support removing a child",
7887 bdrv_get_device_or_node_name(parent_bs));
7888 return;
7889 }
7890
7891 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7892 if (tmp == child) {
7893 break;
7894 }
7895 }
7896
7897 if (!tmp) {
7898 error_setg(errp, "The node %s does not have a child named %s",
7899 bdrv_get_device_or_node_name(parent_bs),
7900 bdrv_get_device_or_node_name(child->bs));
7901 return;
7902 }
7903
7904 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7905}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007906
7907int bdrv_make_empty(BdrvChild *c, Error **errp)
7908{
7909 BlockDriver *drv = c->bs->drv;
7910 int ret;
7911
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007912 GLOBAL_STATE_CODE();
Max Reitz6f7a3b52020-04-29 16:11:23 +02007913 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7914
7915 if (!drv->bdrv_make_empty) {
7916 error_setg(errp, "%s does not support emptying nodes",
7917 drv->format_name);
7918 return -ENOTSUP;
7919 }
7920
7921 ret = drv->bdrv_make_empty(c->bs);
7922 if (ret < 0) {
7923 error_setg_errno(errp, -ret, "Failed to empty %s",
7924 c->bs->filename);
7925 return ret;
7926 }
7927
7928 return 0;
7929}
Max Reitz9a6fc882019-05-31 15:23:11 +02007930
7931/*
7932 * Return the child that @bs acts as an overlay for, and from which data may be
7933 * copied in COW or COR operations. Usually this is the backing file.
7934 */
7935BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7936{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05007937 IO_CODE();
7938
Max Reitz9a6fc882019-05-31 15:23:11 +02007939 if (!bs || !bs->drv) {
7940 return NULL;
7941 }
7942
7943 if (bs->drv->is_filter) {
7944 return NULL;
7945 }
7946
7947 if (!bs->backing) {
7948 return NULL;
7949 }
7950
7951 assert(bs->backing->role & BDRV_CHILD_COW);
7952 return bs->backing;
7953}
7954
7955/*
7956 * If @bs acts as a filter for exactly one of its children, return
7957 * that child.
7958 */
7959BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7960{
7961 BdrvChild *c;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05007962 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02007963
7964 if (!bs || !bs->drv) {
7965 return NULL;
7966 }
7967
7968 if (!bs->drv->is_filter) {
7969 return NULL;
7970 }
7971
7972 /* Only one of @backing or @file may be used */
7973 assert(!(bs->backing && bs->file));
7974
7975 c = bs->backing ?: bs->file;
7976 if (!c) {
7977 return NULL;
7978 }
7979
7980 assert(c->role & BDRV_CHILD_FILTERED);
7981 return c;
7982}
7983
7984/*
7985 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7986 * whichever is non-NULL.
7987 *
7988 * Return NULL if both are NULL.
7989 */
7990BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7991{
7992 BdrvChild *cow_child = bdrv_cow_child(bs);
7993 BdrvChild *filter_child = bdrv_filter_child(bs);
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05007994 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02007995
7996 /* Filter nodes cannot have COW backing files */
7997 assert(!(cow_child && filter_child));
7998
7999 return cow_child ?: filter_child;
8000}
8001
8002/*
8003 * Return the primary child of this node: For filters, that is the
8004 * filtered child. For other nodes, that is usually the child storing
8005 * metadata.
8006 * (A generally more helpful description is that this is (usually) the
8007 * child that has the same filename as @bs.)
8008 *
8009 * Drivers do not necessarily have a primary child; for example quorum
8010 * does not.
8011 */
8012BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8013{
8014 BdrvChild *c, *found = NULL;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008015 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008016
8017 QLIST_FOREACH(c, &bs->children, next) {
8018 if (c->role & BDRV_CHILD_PRIMARY) {
8019 assert(!found);
8020 found = c;
8021 }
8022 }
8023
8024 return found;
8025}
Max Reitzd38d7eb2019-06-12 15:06:37 +02008026
8027static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8028 bool stop_on_explicit_filter)
8029{
8030 BdrvChild *c;
8031
8032 if (!bs) {
8033 return NULL;
8034 }
8035
8036 while (!(stop_on_explicit_filter && !bs->implicit)) {
8037 c = bdrv_filter_child(bs);
8038 if (!c) {
8039 /*
8040 * A filter that is embedded in a working block graph must
8041 * have a child. Assert this here so this function does
8042 * not return a filter node that is not expected by the
8043 * caller.
8044 */
8045 assert(!bs->drv || !bs->drv->is_filter);
8046 break;
8047 }
8048 bs = c->bs;
8049 }
8050 /*
8051 * Note that this treats nodes with bs->drv == NULL as not being
8052 * filters (bs->drv == NULL should be replaced by something else
8053 * anyway).
8054 * The advantage of this behavior is that this function will thus
8055 * always return a non-NULL value (given a non-NULL @bs).
8056 */
8057
8058 return bs;
8059}
8060
8061/*
8062 * Return the first BDS that has not been added implicitly or that
8063 * does not have a filtered child down the chain starting from @bs
8064 * (including @bs itself).
8065 */
8066BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8067{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05008068 GLOBAL_STATE_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008069 return bdrv_do_skip_filters(bs, true);
8070}
8071
8072/*
8073 * Return the first BDS that does not have a filtered child down the
8074 * chain starting from @bs (including @bs itself).
8075 */
8076BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8077{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008078 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008079 return bdrv_do_skip_filters(bs, false);
8080}
8081
8082/*
8083 * For a backing chain, return the first non-filter backing image of
8084 * the first non-filter image.
8085 */
8086BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8087{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008088 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008089 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8090}
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008091
8092/**
8093 * Check whether [offset, offset + bytes) overlaps with the cached
8094 * block-status data region.
8095 *
8096 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8097 * which is what bdrv_bsc_is_data()'s interface needs.
8098 * Otherwise, *pnum is not touched.
8099 */
8100static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8101 int64_t offset, int64_t bytes,
8102 int64_t *pnum)
8103{
8104 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8105 bool overlaps;
8106
8107 overlaps =
8108 qatomic_read(&bsc->valid) &&
8109 ranges_overlap(offset, bytes, bsc->data_start,
8110 bsc->data_end - bsc->data_start);
8111
8112 if (overlaps && pnum) {
8113 *pnum = bsc->data_end - offset;
8114 }
8115
8116 return overlaps;
8117}
8118
8119/**
8120 * See block_int.h for this function's documentation.
8121 */
8122bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8123{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008124 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008125 RCU_READ_LOCK_GUARD();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008126 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8127}
8128
8129/**
8130 * See block_int.h for this function's documentation.
8131 */
8132void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8133 int64_t offset, int64_t bytes)
8134{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008135 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008136 RCU_READ_LOCK_GUARD();
8137
8138 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8139 qatomic_set(&bs->block_status_cache->valid, false);
8140 }
8141}
8142
8143/**
8144 * See block_int.h for this function's documentation.
8145 */
8146void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8147{
8148 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8149 BdrvBlockStatusCache *old_bsc;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008150 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008151
8152 *new_bsc = (BdrvBlockStatusCache) {
8153 .valid = true,
8154 .data_start = offset,
8155 .data_end = offset + bytes,
8156 };
8157
8158 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8159
8160 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8161 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8162 if (old_bsc) {
8163 g_free_rcu(old_bsc, rcu);
8164 }
8165}