blob: 9b0fae5c1e2c6fca263fad97c4fe58c18d6e02f9 [file] [log] [blame]
bellardfc01f7e2003-06-30 10:03:06 +00001/*
2 * QEMU System Emulator block driver
ths5fafdf22007-09-16 21:08:06 +00003 *
bellardfc01f7e2003-06-30 10:03:06 +00004 * Copyright (c) 2003 Fabrice Bellard
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03005 * Copyright (c) 2020 Virtuozzo International GmbH.
ths5fafdf22007-09-16 21:08:06 +00006 *
bellardfc01f7e2003-06-30 10:03:06 +00007 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
Markus Armbrustere688df62018-02-01 12:18:31 +010025
Peter Maydelld38ea872016-01-29 17:50:05 +000026#include "qemu/osdep.h"
Daniel P. Berrange0ab8ed12017-01-25 16:14:15 +000027#include "block/trace.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010028#include "block/block_int.h"
29#include "block/blockjob.h"
Max Reitz0c9b70d2020-10-27 20:05:42 +010030#include "block/fuse.h"
Kevin Wolfcd7fca92016-07-06 11:22:39 +020031#include "block/nbd.h"
Max Reitz609f45e2018-06-14 21:14:28 +020032#include "block/qdict.h"
Markus Armbrusterd49b6832015-03-17 18:29:20 +010033#include "qemu/error-report.h"
Marc-André Lureau5e5733e2019-08-29 22:34:43 +040034#include "block/module_block.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020035#include "qemu/main-loop.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010036#include "qemu/module.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010037#include "qapi/error.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010038#include "qapi/qmp/qdict.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010039#include "qapi/qmp/qjson.h"
Max Reitze59a0cf2018-02-24 16:40:32 +010040#include "qapi/qmp/qnull.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010041#include "qapi/qmp/qstring.h"
Kevin Wolfe1d74bc2018-01-10 15:52:33 +010042#include "qapi/qobject-output-visitor.h"
43#include "qapi/qapi-visit-block-core.h"
Markus Armbrusterbfb197e2014-10-07 13:59:11 +020044#include "sysemu/block-backend.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010045#include "qemu/notify.h"
Markus Armbruster922a01a2018-02-01 12:18:46 +010046#include "qemu/option.h"
Daniel P. Berrange10817bf2015-09-01 14:48:02 +010047#include "qemu/coroutine.h"
Benoît Canetc13163f2014-01-23 21:31:34 +010048#include "block/qapi.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010049#include "qemu/timer.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020050#include "qemu/cutils.h"
51#include "qemu/id.h"
Hanna Reitz0bc329f2021-08-12 10:41:44 +020052#include "qemu/range.h"
53#include "qemu/rcu.h"
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +030054#include "block/coroutines.h"
bellardfc01f7e2003-06-30 10:03:06 +000055
Juan Quintela71e72a12009-07-27 16:12:56 +020056#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000057#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000058#include <sys/queue.h>
Joelle van Dynefeccdce2021-03-15 11:03:39 -070059#if defined(HAVE_SYS_DISK_H)
bellard7674e7b2005-04-26 21:59:26 +000060#include <sys/disk.h>
61#endif
blueswir1c5e97232009-03-07 20:06:23 +000062#endif
bellard7674e7b2005-04-26 21:59:26 +000063
aliguori49dc7682009-03-08 16:26:59 +000064#ifdef _WIN32
65#include <windows.h>
66#endif
67
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010068#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
69
Emanuele Giuseppe Esposito3b491a92022-03-03 10:15:48 -050070/* Protected by BQL */
Benoît Canetdc364f42014-01-23 21:31:32 +010071static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
72 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
73
Emanuele Giuseppe Esposito3b491a92022-03-03 10:15:48 -050074/* Protected by BQL */
Max Reitz2c1d04e2016-01-29 16:36:11 +010075static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
76 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
77
Emanuele Giuseppe Esposito3b491a92022-03-03 10:15:48 -050078/* Protected by BQL */
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010079static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000081
Max Reitz5b363932016-05-17 16:41:31 +020082static BlockDriverState *bdrv_open_inherit(const char *filename,
83 const char *reference,
84 QDict *options, int flags,
85 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +020086 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +020087 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +020088 Error **errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +020089
Kevin Wolfbfb8aa62021-10-18 15:47:14 +020090static bool bdrv_recurse_has_child(BlockDriverState *bs,
91 BlockDriverState *child);
92
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +010093static void bdrv_child_free(BdrvChild *child);
Hanna Reitzbe64bbb2021-11-15 15:54:01 +010094static void bdrv_replace_child_noperm(BdrvChild **child,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +010095 BlockDriverState *new_bs,
96 bool free_empty_child);
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +030097static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
98 BdrvChild *child,
99 Transaction *tran);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +0300100static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
101 Transaction *tran);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +0300102
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +0300103static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
104 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +0300105 Transaction *change_child_tran, Error **errp);
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +0300106static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
107static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
108
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -0500109static bool bdrv_backing_overridden(BlockDriverState *bs);
110
Markus Armbrustereb852012009-10-27 18:41:44 +0100111/* If non-zero, use only whitelisted block drivers */
112static int use_bdrv_whitelist;
113
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000114#ifdef _WIN32
115static int is_windows_drive_prefix(const char *filename)
116{
117 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
118 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
119 filename[1] == ':');
120}
121
122int is_windows_drive(const char *filename)
123{
124 if (is_windows_drive_prefix(filename) &&
125 filename[2] == '\0')
126 return 1;
127 if (strstart(filename, "\\\\.\\", NULL) ||
128 strstart(filename, "//./", NULL))
129 return 1;
130 return 0;
131}
132#endif
133
Kevin Wolf339064d2013-11-28 10:23:32 +0100134size_t bdrv_opt_mem_align(BlockDriverState *bs)
135{
136 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300137 /* page size or 4k (hdd sector size) should be on the safe side */
Marc-André Lureau8e3b0cb2022-03-23 19:57:22 +0400138 return MAX(4096, qemu_real_host_page_size());
Kevin Wolf339064d2013-11-28 10:23:32 +0100139 }
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500140 IO_CODE();
Kevin Wolf339064d2013-11-28 10:23:32 +0100141
142 return bs->bl.opt_mem_alignment;
143}
144
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300145size_t bdrv_min_mem_align(BlockDriverState *bs)
146{
147 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300148 /* page size or 4k (hdd sector size) should be on the safe side */
Marc-André Lureau8e3b0cb2022-03-23 19:57:22 +0400149 return MAX(4096, qemu_real_host_page_size());
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300150 }
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500151 IO_CODE();
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300152
153 return bs->bl.min_mem_alignment;
154}
155
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000156/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100157int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000158{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200159 const char *p;
160
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000161#ifdef _WIN32
162 if (is_windows_drive(path) ||
163 is_windows_drive_prefix(path)) {
164 return 0;
165 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200166 p = path + strcspn(path, ":/\\");
167#else
168 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000169#endif
170
Paolo Bonzini947995c2012-05-08 16:51:48 +0200171 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000172}
173
bellard83f64092006-08-01 16:21:11 +0000174int path_is_absolute(const char *path)
175{
bellard21664422007-01-07 18:22:37 +0000176#ifdef _WIN32
177 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200178 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000179 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200180 }
181 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000182#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200183 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000184#endif
bellard83f64092006-08-01 16:21:11 +0000185}
186
Max Reitz009b03a2019-02-01 20:29:13 +0100187/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000188 path to it by considering it is relative to base_path. URL are
189 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100190char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000191{
Max Reitz009b03a2019-02-01 20:29:13 +0100192 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000193 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100194 char *result;
bellard83f64092006-08-01 16:21:11 +0000195 int len;
196
bellard83f64092006-08-01 16:21:11 +0000197 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100198 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000199 }
Max Reitz009b03a2019-02-01 20:29:13 +0100200
201 if (path_has_protocol(base_path)) {
202 protocol_stripped = strchr(base_path, ':');
203 if (protocol_stripped) {
204 protocol_stripped++;
205 }
206 }
207 p = protocol_stripped ?: base_path;
208
209 p1 = strrchr(base_path, '/');
210#ifdef _WIN32
211 {
212 const char *p2;
213 p2 = strrchr(base_path, '\\');
214 if (!p1 || p2 > p1) {
215 p1 = p2;
216 }
217 }
218#endif
219 if (p1) {
220 p1++;
221 } else {
222 p1 = base_path;
223 }
224 if (p1 > p) {
225 p = p1;
226 }
227 len = p - base_path;
228
229 result = g_malloc(len + strlen(filename) + 1);
230 memcpy(result, base_path, len);
231 strcpy(result + len, filename);
232
233 return result;
234}
235
Max Reitz03c320d2017-05-22 21:52:16 +0200236/*
237 * Helper function for bdrv_parse_filename() implementations to remove optional
238 * protocol prefixes (especially "file:") from a filename and for putting the
239 * stripped filename into the options QDict if there is such a prefix.
240 */
241void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
242 QDict *options)
243{
244 if (strstart(filename, prefix, &filename)) {
245 /* Stripping the explicit protocol prefix may result in a protocol
246 * prefix being (wrongly) detected (if the filename contains a colon) */
247 if (path_has_protocol(filename)) {
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100248 GString *fat_filename;
Max Reitz03c320d2017-05-22 21:52:16 +0200249
250 /* This means there is some colon before the first slash; therefore,
251 * this cannot be an absolute path */
252 assert(!path_is_absolute(filename));
253
254 /* And we can thus fix the protocol detection issue by prefixing it
255 * by "./" */
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100256 fat_filename = g_string_new("./");
257 g_string_append(fat_filename, filename);
Max Reitz03c320d2017-05-22 21:52:16 +0200258
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100259 assert(!path_has_protocol(fat_filename->str));
Max Reitz03c320d2017-05-22 21:52:16 +0200260
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100261 qdict_put(options, "filename",
262 qstring_from_gstring(fat_filename));
Max Reitz03c320d2017-05-22 21:52:16 +0200263 } else {
264 /* If no protocol prefix was detected, we can use the shortened
265 * filename as-is */
266 qdict_put_str(options, "filename", filename);
267 }
268 }
269}
270
271
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200272/* Returns whether the image file is opened as read-only. Note that this can
273 * return false and writing to the image file is still not possible because the
274 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400275bool bdrv_is_read_only(BlockDriverState *bs)
276{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500277 IO_CODE();
Vladimir Sementsov-Ogievskiy975da072021-05-27 18:40:55 +0300278 return !(bs->open_flags & BDRV_O_RDWR);
Jeff Cody93ed5242017-04-07 16:55:28 -0400279}
280
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200281int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
282 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400283{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500284 IO_CODE();
285
Jeff Codye2b82472017-04-07 16:55:26 -0400286 /* Do not set read_only if copy_on_read is enabled */
287 if (bs->copy_on_read && read_only) {
288 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
289 bdrv_get_device_or_node_name(bs));
290 return -EINVAL;
291 }
292
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400293 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200294 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
295 !ignore_allow_rdw)
296 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400297 error_setg(errp, "Node '%s' is read only",
298 bdrv_get_device_or_node_name(bs));
299 return -EPERM;
300 }
301
Jeff Cody45803a02017-04-07 16:55:29 -0400302 return 0;
303}
304
Kevin Wolfeaa24102018-10-12 11:27:41 +0200305/*
306 * Called by a driver that can only provide a read-only image.
307 *
308 * Returns 0 if the node is already read-only or it could switch the node to
309 * read-only because BDRV_O_AUTO_RDONLY is set.
310 *
311 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
312 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
313 * is not NULL, it is used as the error message for the Error object.
314 */
315int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
316 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400317{
318 int ret = 0;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500319 IO_CODE();
Jeff Cody45803a02017-04-07 16:55:29 -0400320
Kevin Wolfeaa24102018-10-12 11:27:41 +0200321 if (!(bs->open_flags & BDRV_O_RDWR)) {
322 return 0;
323 }
324 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
325 goto fail;
326 }
327
328 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400329 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200330 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400331 }
332
Kevin Wolfeaa24102018-10-12 11:27:41 +0200333 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200334
Jeff Codye2b82472017-04-07 16:55:26 -0400335 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200336
337fail:
338 error_setg(errp, "%s", errmsg ?: "Image is read-only");
339 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400340}
341
Max Reitz645ae7d2019-02-01 20:29:14 +0100342/*
343 * If @backing is empty, this function returns NULL without setting
344 * @errp. In all other cases, NULL will only be returned with @errp
345 * set.
346 *
347 * Therefore, a return value of NULL without @errp set means that
348 * there is no backing file; if @errp is set, there is one but its
349 * absolute filename cannot be generated.
350 */
351char *bdrv_get_full_backing_filename_from_filename(const char *backed,
352 const char *backing,
353 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100354{
Max Reitz645ae7d2019-02-01 20:29:14 +0100355 if (backing[0] == '\0') {
356 return NULL;
357 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
358 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100359 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
360 error_setg(errp, "Cannot use relative backing file names for '%s'",
361 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100362 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100363 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100364 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100365 }
366}
367
Max Reitz9f4793d2019-02-01 20:29:16 +0100368/*
369 * If @filename is empty or NULL, this function returns NULL without
370 * setting @errp. In all other cases, NULL will only be returned with
371 * @errp set.
372 */
373static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
374 const char *filename, Error **errp)
375{
Max Reitz8df68612019-02-01 20:29:23 +0100376 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100377
Max Reitz8df68612019-02-01 20:29:23 +0100378 if (!filename || filename[0] == '\0') {
379 return NULL;
380 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
381 return g_strdup(filename);
382 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100383
Max Reitz8df68612019-02-01 20:29:23 +0100384 dir = bdrv_dirname(relative_to, errp);
385 if (!dir) {
386 return NULL;
387 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100388
Max Reitz8df68612019-02-01 20:29:23 +0100389 full_name = g_strconcat(dir, filename, NULL);
390 g_free(dir);
391 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100392}
393
Max Reitz6b6833c2019-02-01 20:29:15 +0100394char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200395{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500396 GLOBAL_STATE_CODE();
Max Reitz9f4793d2019-02-01 20:29:16 +0100397 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200398}
399
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100400void bdrv_register(BlockDriver *bdrv)
401{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100402 assert(bdrv->format_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500403 GLOBAL_STATE_CODE();
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100404 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000405}
bellardb3380822004-03-14 21:38:54 +0000406
Markus Armbrustere4e99862014-10-07 13:59:03 +0200407BlockDriverState *bdrv_new(void)
408{
409 BlockDriverState *bs;
410 int i;
411
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500412 GLOBAL_STATE_CODE();
413
Markus Armbruster5839e532014-08-19 10:31:08 +0200414 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800415 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800416 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
417 QLIST_INIT(&bs->op_blockers[i]);
418 }
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200419 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200420 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800421 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200422 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200423
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300424 qemu_co_queue_init(&bs->flush_queue);
425
Hanna Reitz0bc329f2021-08-12 10:41:44 +0200426 qemu_co_mutex_init(&bs->bsc_modify_lock);
427 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
428
Kevin Wolf0f122642018-03-28 18:29:18 +0200429 for (i = 0; i < bdrv_drain_all_count; i++) {
430 bdrv_drained_begin(bs);
431 }
432
Max Reitz2c1d04e2016-01-29 16:36:11 +0100433 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
434
bellardb3380822004-03-14 21:38:54 +0000435 return bs;
436}
437
Marc Mari88d88792016-08-12 09:27:03 -0400438static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000439{
440 BlockDriver *drv1;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500441 GLOBAL_STATE_CODE();
Marc Mari88d88792016-08-12 09:27:03 -0400442
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100443 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
444 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000445 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100446 }
bellardea2384d2004-08-01 21:59:26 +0000447 }
Marc Mari88d88792016-08-12 09:27:03 -0400448
bellardea2384d2004-08-01 21:59:26 +0000449 return NULL;
450}
451
Marc Mari88d88792016-08-12 09:27:03 -0400452BlockDriver *bdrv_find_format(const char *format_name)
453{
454 BlockDriver *drv1;
455 int i;
456
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500457 GLOBAL_STATE_CODE();
458
Marc Mari88d88792016-08-12 09:27:03 -0400459 drv1 = bdrv_do_find_format(format_name);
460 if (drv1) {
461 return drv1;
462 }
463
464 /* The driver isn't registered, maybe we need to load a module */
465 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
466 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
467 block_module_load_one(block_driver_modules[i].library_name);
468 break;
469 }
470 }
471
472 return bdrv_do_find_format(format_name);
473}
474
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300475static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100476{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800477 static const char *whitelist_rw[] = {
478 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200479 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800480 };
481 static const char *whitelist_ro[] = {
482 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200483 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100484 };
485 const char **p;
486
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800487 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100488 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800489 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100490
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800491 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300492 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100493 return 1;
494 }
495 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800496 if (read_only) {
497 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300498 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800499 return 1;
500 }
501 }
502 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100503 return 0;
504}
505
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300506int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
507{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500508 GLOBAL_STATE_CODE();
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300509 return bdrv_format_is_whitelisted(drv->format_name, read_only);
510}
511
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000512bool bdrv_uses_whitelist(void)
513{
514 return use_bdrv_whitelist;
515}
516
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800517typedef struct CreateCo {
518 BlockDriver *drv;
519 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800520 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800521 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200522 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800523} CreateCo;
524
525static void coroutine_fn bdrv_create_co_entry(void *opaque)
526{
Max Reitzcc84d902013-09-06 17:14:26 +0200527 Error *local_err = NULL;
528 int ret;
529
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800530 CreateCo *cco = opaque;
531 assert(cco->drv);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -0500532 GLOBAL_STATE_CODE();
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800533
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200534 ret = cco->drv->bdrv_co_create_opts(cco->drv,
535 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300536 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200537 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800538}
539
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200540int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800541 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000542{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800543 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200544
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500545 GLOBAL_STATE_CODE();
546
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800547 Coroutine *co;
548 CreateCo cco = {
549 .drv = drv,
550 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800551 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800552 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200553 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800554 };
555
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100556 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200557 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300558 ret = -ENOTSUP;
559 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800560 }
561
562 if (qemu_in_coroutine()) {
563 /* Fast-path if already in coroutine context */
564 bdrv_create_co_entry(&cco);
565 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200566 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
567 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800568 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200569 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800570 }
571 }
572
573 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200574 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100575 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200576 error_propagate(errp, cco.err);
577 } else {
578 error_setg_errno(errp, -ret, "Could not create image");
579 }
580 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800581
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300582out:
583 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800584 return ret;
bellardea2384d2004-08-01 21:59:26 +0000585}
586
Max Reitzfd171462020-01-22 17:45:29 +0100587/**
588 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
589 * least the given @minimum_size.
590 *
591 * On success, return @blk's actual length.
592 * Otherwise, return -errno.
593 */
594static int64_t create_file_fallback_truncate(BlockBackend *blk,
595 int64_t minimum_size, Error **errp)
596{
597 Error *local_err = NULL;
598 int64_t size;
599 int ret;
600
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500601 GLOBAL_STATE_CODE();
602
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200603 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
604 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100605 if (ret < 0 && ret != -ENOTSUP) {
606 error_propagate(errp, local_err);
607 return ret;
608 }
609
610 size = blk_getlength(blk);
611 if (size < 0) {
612 error_free(local_err);
613 error_setg_errno(errp, -size,
614 "Failed to inquire the new image file's length");
615 return size;
616 }
617
618 if (size < minimum_size) {
619 /* Need to grow the image, but we failed to do that */
620 error_propagate(errp, local_err);
621 return -ENOTSUP;
622 }
623
624 error_free(local_err);
625 local_err = NULL;
626
627 return size;
628}
629
630/**
631 * Helper function for bdrv_create_file_fallback(): Zero the first
632 * sector to remove any potentially pre-existing image header.
633 */
Paolo Bonzini881a4c52022-09-22 10:49:00 +0200634static int coroutine_fn
635create_file_fallback_zero_first_sector(BlockBackend *blk,
636 int64_t current_size,
637 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100638{
639 int64_t bytes_to_clear;
640 int ret;
641
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500642 GLOBAL_STATE_CODE();
643
Max Reitzfd171462020-01-22 17:45:29 +0100644 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
645 if (bytes_to_clear) {
646 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
647 if (ret < 0) {
648 error_setg_errno(errp, -ret,
649 "Failed to clear the new image's first sector");
650 return ret;
651 }
652 }
653
654 return 0;
655}
656
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200657/**
658 * Simple implementation of bdrv_co_create_opts for protocol drivers
659 * which only support creation via opening a file
660 * (usually existing raw storage device)
661 */
662int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
663 const char *filename,
664 QemuOpts *opts,
665 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100666{
667 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100668 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100669 int64_t size = 0;
670 char *buf = NULL;
671 PreallocMode prealloc;
672 Error *local_err = NULL;
673 int ret;
674
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -0500675 GLOBAL_STATE_CODE();
676
Max Reitzfd171462020-01-22 17:45:29 +0100677 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
678 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
679 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
680 PREALLOC_MODE_OFF, &local_err);
681 g_free(buf);
682 if (local_err) {
683 error_propagate(errp, local_err);
684 return -EINVAL;
685 }
686
687 if (prealloc != PREALLOC_MODE_OFF) {
688 error_setg(errp, "Unsupported preallocation mode '%s'",
689 PreallocMode_str(prealloc));
690 return -ENOTSUP;
691 }
692
Max Reitzeeea1fa2020-02-25 16:56:18 +0100693 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100694 qdict_put_str(options, "driver", drv->format_name);
695
696 blk = blk_new_open(filename, NULL, options,
697 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
698 if (!blk) {
699 error_prepend(errp, "Protocol driver '%s' does not support image "
700 "creation, and opening the image failed: ",
701 drv->format_name);
702 return -EINVAL;
703 }
704
705 size = create_file_fallback_truncate(blk, size, errp);
706 if (size < 0) {
707 ret = size;
708 goto out;
709 }
710
711 ret = create_file_fallback_zero_first_sector(blk, size, errp);
712 if (ret < 0) {
713 goto out;
714 }
715
716 ret = 0;
717out:
718 blk_unref(blk);
719 return ret;
720}
721
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800722int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200723{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100724 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200725 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100726 QDict *qdict;
727 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200728
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500729 GLOBAL_STATE_CODE();
730
Max Reitzb65a5e12015-02-05 13:58:12 -0500731 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200732 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000733 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200734 }
735
Stefano Garzarella729222a2021-03-08 17:12:32 +0100736 if (!drv->create_opts) {
737 error_setg(errp, "Driver '%s' does not support image creation",
738 drv->format_name);
739 return -ENOTSUP;
740 }
741
742 /*
743 * 'opts' contains a QemuOptsList with a combination of format and protocol
744 * default values.
745 *
746 * The format properly removes its options, but the default values remain
747 * in 'opts->list'. So if the protocol has options with the same name
748 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
749 * of the format, since for overlapping options, the format wins.
750 *
751 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
752 * only the set options, and then convert it back to QemuOpts, using the
753 * create_opts of the protocol. So the new QemuOpts, will contain only the
754 * protocol defaults.
755 */
756 qdict = qemu_opts_to_qdict(opts, NULL);
757 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
758 if (protocol_opts == NULL) {
759 ret = -EINVAL;
760 goto out;
761 }
762
763 ret = bdrv_create(drv, filename, protocol_opts, errp);
764out:
765 qemu_opts_del(protocol_opts);
766 qobject_unref(qdict);
767 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200768}
769
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300770int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
771{
772 Error *local_err = NULL;
773 int ret;
774
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500775 IO_CODE();
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300776 assert(bs != NULL);
777
778 if (!bs->drv) {
779 error_setg(errp, "Block node '%s' is not opened", bs->filename);
780 return -ENOMEDIUM;
781 }
782
783 if (!bs->drv->bdrv_co_delete_file) {
784 error_setg(errp, "Driver '%s' does not support image deletion",
785 bs->drv->format_name);
786 return -ENOTSUP;
787 }
788
789 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
790 if (ret < 0) {
791 error_propagate(errp, local_err);
792 }
793
794 return ret;
795}
796
Maxim Levitskya890f082020-12-17 19:09:03 +0200797void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
798{
799 Error *local_err = NULL;
800 int ret;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -0500801 IO_CODE();
Maxim Levitskya890f082020-12-17 19:09:03 +0200802
803 if (!bs) {
804 return;
805 }
806
807 ret = bdrv_co_delete_file(bs, &local_err);
808 /*
809 * ENOTSUP will happen if the block driver doesn't support
810 * the 'bdrv_co_delete_file' interface. This is a predictable
811 * scenario and shouldn't be reported back to the user.
812 */
813 if (ret == -ENOTSUP) {
814 error_free(local_err);
815 } else if (ret < 0) {
816 error_report_err(local_err);
817 }
818}
819
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100820/**
821 * Try to get @bs's logical and physical block size.
822 * On success, store them in @bsz struct and return 0.
823 * On failure return -errno.
824 * @bs must not be empty.
825 */
826int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
827{
828 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200829 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500830 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100831
832 if (drv && drv->bdrv_probe_blocksizes) {
833 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200834 } else if (filtered) {
835 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100836 }
837
838 return -ENOTSUP;
839}
840
841/**
842 * Try to get @bs's geometry (cyls, heads, sectors).
843 * On success, store them in @geo struct and return 0.
844 * On failure return -errno.
845 * @bs must not be empty.
846 */
847int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
848{
849 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200850 BlockDriverState *filtered = bdrv_filter_bs(bs);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500851 GLOBAL_STATE_CODE();
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100852
853 if (drv && drv->bdrv_probe_geometry) {
854 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200855 } else if (filtered) {
856 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100857 }
858
859 return -ENOTSUP;
860}
861
Jim Meyeringeba25052012-05-28 09:27:54 +0200862/*
863 * Create a uniquely-named empty temporary file.
864 * Return 0 upon success, otherwise a negative errno value.
865 */
866int get_tmp_filename(char *filename, int size)
867{
bellardd5249392004-08-03 21:14:23 +0000868#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000869 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200870 /* GetTempFileName requires that its output buffer (4th param)
871 have length MAX_PATH or greater. */
872 assert(size >= MAX_PATH);
873 return (GetTempPath(MAX_PATH, temp_dir)
874 && GetTempFileName(temp_dir, "qem", 0, filename)
875 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000876#else
bellardea2384d2004-08-01 21:59:26 +0000877 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000878 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000879 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530880 if (!tmpdir) {
881 tmpdir = "/var/tmp";
882 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200883 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
884 return -EOVERFLOW;
885 }
bellardea2384d2004-08-01 21:59:26 +0000886 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800887 if (fd < 0) {
888 return -errno;
889 }
890 if (close(fd) != 0) {
891 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200892 return -errno;
893 }
894 return 0;
bellardd5249392004-08-03 21:14:23 +0000895#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200896}
bellardea2384d2004-08-01 21:59:26 +0000897
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200898/*
899 * Detect host devices. By convention, /dev/cdrom[N] is always
900 * recognized as a host CDROM.
901 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200902static BlockDriver *find_hdev_driver(const char *filename)
903{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200904 int score_max = 0, score;
905 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500906 GLOBAL_STATE_CODE();
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200907
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100908 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200909 if (d->bdrv_probe_device) {
910 score = d->bdrv_probe_device(filename);
911 if (score > score_max) {
912 score_max = score;
913 drv = d;
914 }
915 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200916 }
917
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200918 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200919}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200920
Marc Mari88d88792016-08-12 09:27:03 -0400921static BlockDriver *bdrv_do_find_protocol(const char *protocol)
922{
923 BlockDriver *drv1;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -0500924 GLOBAL_STATE_CODE();
Marc Mari88d88792016-08-12 09:27:03 -0400925
926 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
927 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
928 return drv1;
929 }
930 }
931
932 return NULL;
933}
934
Kevin Wolf98289622013-07-10 15:47:39 +0200935BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500936 bool allow_protocol_prefix,
937 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200938{
939 BlockDriver *drv1;
940 char protocol[128];
941 int len;
942 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400943 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200944
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -0500945 GLOBAL_STATE_CODE();
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200946 /* TODO Drivers without bdrv_file_open must be specified explicitly */
947
Christoph Hellwig39508e72010-06-23 12:25:17 +0200948 /*
949 * XXX(hch): we really should not let host device detection
950 * override an explicit protocol specification, but moving this
951 * later breaks access to device names with colons in them.
952 * Thanks to the brain-dead persistent naming schemes on udev-
953 * based Linux systems those actually are quite common.
954 */
955 drv1 = find_hdev_driver(filename);
956 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200957 return drv1;
958 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200959
Kevin Wolf98289622013-07-10 15:47:39 +0200960 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100961 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200962 }
Kevin Wolf98289622013-07-10 15:47:39 +0200963
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000964 p = strchr(filename, ':');
965 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200966 len = p - filename;
967 if (len > sizeof(protocol) - 1)
968 len = sizeof(protocol) - 1;
969 memcpy(protocol, filename, len);
970 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400971
972 drv1 = bdrv_do_find_protocol(protocol);
973 if (drv1) {
974 return drv1;
975 }
976
977 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
978 if (block_driver_modules[i].protocol_name &&
979 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
980 block_module_load_one(block_driver_modules[i].library_name);
981 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200982 }
983 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500984
Marc Mari88d88792016-08-12 09:27:03 -0400985 drv1 = bdrv_do_find_protocol(protocol);
986 if (!drv1) {
987 error_setg(errp, "Unknown protocol '%s'", protocol);
988 }
989 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200990}
991
Markus Armbrusterc6684242014-11-20 16:27:10 +0100992/*
993 * Guess image format by probing its contents.
994 * This is not a good idea when your image is raw (CVE-2008-2004), but
995 * we do it anyway for backward compatibility.
996 *
997 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100998 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
999 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001000 * @filename is its filename.
1001 *
1002 * For all block drivers, call the bdrv_probe() method to get its
1003 * probing score.
1004 * Return the first block driver with the highest probing score.
1005 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01001006BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1007 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +01001008{
1009 int score_max = 0, score;
1010 BlockDriver *drv = NULL, *d;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001011 IO_CODE();
Markus Armbrusterc6684242014-11-20 16:27:10 +01001012
1013 QLIST_FOREACH(d, &bdrv_drivers, list) {
1014 if (d->bdrv_probe) {
1015 score = d->bdrv_probe(buf, buf_size, filename);
1016 if (score > score_max) {
1017 score_max = score;
1018 drv = d;
1019 }
1020 }
1021 }
1022
1023 return drv;
1024}
1025
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001026static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +02001027 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +00001028{
Markus Armbrusterc6684242014-11-20 16:27:10 +01001029 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +01001030 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +01001031 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001032
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001033 GLOBAL_STATE_CODE();
1034
Kevin Wolf08a00552010-06-01 18:37:31 +02001035 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001036 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +01001037 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +02001038 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -07001039 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -07001040
Alberto Fariaa9262f52022-07-05 17:15:11 +01001041 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
bellard83f64092006-08-01 16:21:11 +00001042 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001043 error_setg_errno(errp, -ret, "Could not read image for determining its "
1044 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +02001045 *pdrv = NULL;
1046 return ret;
bellard83f64092006-08-01 16:21:11 +00001047 }
1048
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001049 drv = bdrv_probe_all(buf, sizeof(buf), filename);
Stefan Weilc98ac352010-07-21 21:51:51 +02001050 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001051 error_setg(errp, "Could not determine image format: No compatible "
1052 "driver found");
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001053 *pdrv = NULL;
1054 return -ENOENT;
Stefan Weilc98ac352010-07-21 21:51:51 +02001055 }
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001056
Stefan Weilc98ac352010-07-21 21:51:51 +02001057 *pdrv = drv;
Alberto Fariabf5b16f2022-07-05 17:15:09 +01001058 return 0;
bellardea2384d2004-08-01 21:59:26 +00001059}
1060
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001061/**
1062 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001063 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001064 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001065int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001066{
1067 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05001068 IO_CODE();
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001069
Max Reitzd470ad42017-11-10 21:31:09 +01001070 if (!drv) {
1071 return -ENOMEDIUM;
1072 }
1073
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001074 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001075 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001076 return 0;
1077
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001078 /* query actual device if possible, otherwise just trust the hint */
1079 if (drv->bdrv_getlength) {
1080 int64_t length = drv->bdrv_getlength(bs);
1081 if (length < 0) {
1082 return length;
1083 }
Fam Zheng7e382002013-11-06 19:48:06 +08001084 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001085 }
1086
1087 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001088
1089 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1090 return -EFBIG;
1091 }
1092
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001093 return 0;
1094}
1095
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001096/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001097 * Combines a QDict of new block driver @options with any missing options taken
1098 * from @old_options, so that leaving out an option defaults to its old value.
1099 */
1100static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1101 QDict *old_options)
1102{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001103 GLOBAL_STATE_CODE();
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001104 if (bs->drv && bs->drv->bdrv_join_options) {
1105 bs->drv->bdrv_join_options(options, old_options);
1106 } else {
1107 qdict_join(options, old_options, false);
1108 }
1109}
1110
Alberto Garcia543770b2018-09-06 12:37:09 +03001111static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1112 int open_flags,
1113 Error **errp)
1114{
1115 Error *local_err = NULL;
1116 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1117 BlockdevDetectZeroesOptions detect_zeroes =
1118 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1119 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001120 GLOBAL_STATE_CODE();
Alberto Garcia543770b2018-09-06 12:37:09 +03001121 g_free(value);
1122 if (local_err) {
1123 error_propagate(errp, local_err);
1124 return detect_zeroes;
1125 }
1126
1127 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1128 !(open_flags & BDRV_O_UNMAP))
1129 {
1130 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1131 "without setting discard operation to unmap");
1132 }
1133
1134 return detect_zeroes;
1135}
1136
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001137/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001138 * Set open flags for aio engine
1139 *
1140 * Return 0 on success, -1 if the engine specified is invalid
1141 */
1142int bdrv_parse_aio(const char *mode, int *flags)
1143{
1144 if (!strcmp(mode, "threads")) {
1145 /* do nothing, default */
1146 } else if (!strcmp(mode, "native")) {
1147 *flags |= BDRV_O_NATIVE_AIO;
1148#ifdef CONFIG_LINUX_IO_URING
1149 } else if (!strcmp(mode, "io_uring")) {
1150 *flags |= BDRV_O_IO_URING;
1151#endif
1152 } else {
1153 return -1;
1154 }
1155
1156 return 0;
1157}
1158
1159/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001160 * Set open flags for a given discard mode
1161 *
1162 * Return 0 on success, -1 if the discard mode was invalid.
1163 */
1164int bdrv_parse_discard_flags(const char *mode, int *flags)
1165{
1166 *flags &= ~BDRV_O_UNMAP;
1167
1168 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1169 /* do nothing */
1170 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1171 *flags |= BDRV_O_UNMAP;
1172 } else {
1173 return -1;
1174 }
1175
1176 return 0;
1177}
1178
1179/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001180 * Set open flags for a given cache mode
1181 *
1182 * Return 0 on success, -1 if the cache mode was invalid.
1183 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001184int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001185{
1186 *flags &= ~BDRV_O_CACHE_MASK;
1187
1188 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001189 *writethrough = false;
1190 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001191 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001192 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001193 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001194 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001195 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001196 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001197 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001198 *flags |= BDRV_O_NO_FLUSH;
1199 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001200 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001201 } else {
1202 return -1;
1203 }
1204
1205 return 0;
1206}
1207
Kevin Wolfb5411552017-01-17 15:56:16 +01001208static char *bdrv_child_get_parent_desc(BdrvChild *c)
1209{
1210 BlockDriverState *parent = c->opaque;
Vladimir Sementsov-Ogievskiy2c0a3ac2021-06-01 10:52:15 +03001211 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
Kevin Wolfb5411552017-01-17 15:56:16 +01001212}
1213
Kevin Wolf20018e12016-05-23 18:46:59 +02001214static void bdrv_child_cb_drained_begin(BdrvChild *child)
1215{
1216 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001217 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001218}
1219
Kevin Wolf89bd0302018-03-22 14:11:20 +01001220static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1221{
1222 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001223 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001224}
1225
Max Reitze037c092019-07-19 11:26:14 +02001226static void bdrv_child_cb_drained_end(BdrvChild *child,
1227 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001228{
1229 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001230 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001231}
1232
Kevin Wolf38701b62017-05-04 18:52:39 +02001233static int bdrv_child_cb_inactivate(BdrvChild *child)
1234{
1235 BlockDriverState *bs = child->opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001236 GLOBAL_STATE_CODE();
Kevin Wolf38701b62017-05-04 18:52:39 +02001237 assert(bs->open_flags & BDRV_O_INACTIVE);
1238 return 0;
1239}
1240
Kevin Wolf5d231842019-05-06 19:17:56 +02001241static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1242 GSList **ignore, Error **errp)
1243{
1244 BlockDriverState *bs = child->opaque;
1245 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1246}
1247
Kevin Wolf53a7d042019-05-06 19:17:59 +02001248static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1249 GSList **ignore)
1250{
1251 BlockDriverState *bs = child->opaque;
1252 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1253}
1254
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001255/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001256 * Returns the options and flags that a temporary snapshot should get, based on
1257 * the originally requested flags (the originally requested image will have
1258 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001259 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001260static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1261 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001262{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001263 GLOBAL_STATE_CODE();
Kevin Wolf73176be2016-03-07 13:02:15 +01001264 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1265
1266 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001267 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1268 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001269
Kevin Wolf3f486862019-04-04 17:04:43 +02001270 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001271 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001272 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001273
Kevin Wolf41869042016-06-16 12:59:30 +02001274 /* aio=native doesn't work for cache.direct=off, so disable it for the
1275 * temporary snapshot */
1276 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001277}
1278
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001279static void bdrv_backing_attach(BdrvChild *c)
1280{
1281 BlockDriverState *parent = c->opaque;
1282 BlockDriverState *backing_hd = c->bs;
1283
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001284 GLOBAL_STATE_CODE();
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001285 assert(!parent->backing_blocker);
1286 error_setg(&parent->backing_blocker,
1287 "node is used as backing hd of '%s'",
1288 bdrv_get_device_or_node_name(parent));
1289
Max Reitzf30c66b2019-02-01 20:29:05 +01001290 bdrv_refresh_filename(backing_hd);
1291
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001292 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001293
1294 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1295 /* Otherwise we won't be able to commit or stream */
1296 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1297 parent->backing_blocker);
1298 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1299 parent->backing_blocker);
1300 /*
1301 * We do backup in 3 ways:
1302 * 1. drive backup
1303 * The target bs is new opened, and the source is top BDS
1304 * 2. blockdev backup
1305 * Both the source and the target are top BDSes.
1306 * 3. internal backup(used for block replication)
1307 * Both the source and the target are backing file
1308 *
1309 * In case 1 and 2, neither the source nor the target is the backing file.
1310 * In case 3, we will block the top BDS, so there is only one block job
1311 * for the top BDS and its backing chain.
1312 */
1313 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1314 parent->backing_blocker);
1315 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1316 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001317}
Kevin Wolfd736f112017-12-18 16:05:48 +01001318
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001319static void bdrv_backing_detach(BdrvChild *c)
1320{
1321 BlockDriverState *parent = c->opaque;
1322
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001323 GLOBAL_STATE_CODE();
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001324 assert(parent->backing_blocker);
1325 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1326 error_free(parent->backing_blocker);
1327 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001328}
Kevin Wolfd736f112017-12-18 16:05:48 +01001329
Kevin Wolf6858eba2017-06-29 19:32:21 +02001330static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1331 const char *filename, Error **errp)
1332{
1333 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001334 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001335 int ret;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001336 GLOBAL_STATE_CODE();
Kevin Wolf6858eba2017-06-29 19:32:21 +02001337
Alberto Garciae94d3db2018-11-12 16:00:34 +02001338 if (read_only) {
1339 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001340 if (ret < 0) {
1341 return ret;
1342 }
1343 }
1344
Kevin Wolf6858eba2017-06-29 19:32:21 +02001345 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001346 base->drv ? base->drv->format_name : "",
1347 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001348 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001349 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001350 }
1351
Alberto Garciae94d3db2018-11-12 16:00:34 +02001352 if (read_only) {
1353 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001354 }
1355
Kevin Wolf6858eba2017-06-29 19:32:21 +02001356 return ret;
1357}
1358
Max Reitzfae8bd32020-05-13 13:05:20 +02001359/*
1360 * Returns the options and flags that a generic child of a BDS should
1361 * get, based on the given options and flags for the parent BDS.
1362 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001363static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1364 int *child_flags, QDict *child_options,
1365 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001366{
1367 int flags = parent_flags;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001368 GLOBAL_STATE_CODE();
Max Reitzfae8bd32020-05-13 13:05:20 +02001369
1370 /*
1371 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1372 * Generally, the question to answer is: Should this child be
1373 * format-probed by default?
1374 */
1375
1376 /*
1377 * Pure and non-filtered data children of non-format nodes should
1378 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1379 * set). This only affects a very limited set of drivers (namely
1380 * quorum and blkverify when this comment was written).
1381 * Force-clear BDRV_O_PROTOCOL then.
1382 */
1383 if (!parent_is_format &&
1384 (role & BDRV_CHILD_DATA) &&
1385 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1386 {
1387 flags &= ~BDRV_O_PROTOCOL;
1388 }
1389
1390 /*
1391 * All children of format nodes (except for COW children) and all
1392 * metadata children in general should never be format-probed.
1393 * Force-set BDRV_O_PROTOCOL then.
1394 */
1395 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1396 (role & BDRV_CHILD_METADATA))
1397 {
1398 flags |= BDRV_O_PROTOCOL;
1399 }
1400
1401 /*
1402 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1403 * the parent.
1404 */
1405 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1406 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1407 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1408
1409 if (role & BDRV_CHILD_COW) {
1410 /* backing files are opened read-only by default */
1411 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1412 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1413 } else {
1414 /* Inherit the read-only option from the parent if it's not set */
1415 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1416 qdict_copy_default(child_options, parent_options,
1417 BDRV_OPT_AUTO_READ_ONLY);
1418 }
1419
1420 /*
1421 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1422 * can default to enable it on lower layers regardless of the
1423 * parent option.
1424 */
1425 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1426
1427 /* Clear flags that only apply to the top layer */
1428 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1429
1430 if (role & BDRV_CHILD_METADATA) {
1431 flags &= ~BDRV_O_NO_IO;
1432 }
1433 if (role & BDRV_CHILD_COW) {
1434 flags &= ~BDRV_O_TEMPORARY;
1435 }
1436
1437 *child_flags = flags;
1438}
1439
Max Reitzca2f1232020-05-13 13:05:22 +02001440static void bdrv_child_cb_attach(BdrvChild *child)
1441{
1442 BlockDriverState *bs = child->opaque;
1443
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05001444 assert_bdrv_graph_writable(bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001445 QLIST_INSERT_HEAD(&bs->children, child, next);
1446
Max Reitzca2f1232020-05-13 13:05:22 +02001447 if (child->role & BDRV_CHILD_COW) {
1448 bdrv_backing_attach(child);
1449 }
1450
1451 bdrv_apply_subtree_drain(child, bs);
1452}
1453
Max Reitz48e08282020-05-13 13:05:23 +02001454static void bdrv_child_cb_detach(BdrvChild *child)
1455{
1456 BlockDriverState *bs = child->opaque;
1457
1458 if (child->role & BDRV_CHILD_COW) {
1459 bdrv_backing_detach(child);
1460 }
1461
1462 bdrv_unapply_subtree_drain(child, bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001463
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05001464 assert_bdrv_graph_writable(bs);
Hanna Reitza2253692021-11-15 15:53:58 +01001465 QLIST_REMOVE(child, next);
Max Reitz48e08282020-05-13 13:05:23 +02001466}
1467
Max Reitz43483552020-05-13 13:05:24 +02001468static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1469 const char *filename, Error **errp)
1470{
1471 if (c->role & BDRV_CHILD_COW) {
1472 return bdrv_backing_update_filename(c, base, filename, errp);
1473 }
1474 return 0;
1475}
1476
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001477AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001478{
1479 BlockDriverState *bs = c->opaque;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05001480 IO_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001481
1482 return bdrv_get_aio_context(bs);
1483}
1484
Max Reitz43483552020-05-13 13:05:24 +02001485const BdrvChildClass child_of_bds = {
1486 .parent_is_bds = true,
1487 .get_parent_desc = bdrv_child_get_parent_desc,
1488 .inherit_options = bdrv_inherited_options,
1489 .drained_begin = bdrv_child_cb_drained_begin,
1490 .drained_poll = bdrv_child_cb_drained_poll,
1491 .drained_end = bdrv_child_cb_drained_end,
1492 .attach = bdrv_child_cb_attach,
1493 .detach = bdrv_child_cb_detach,
1494 .inactivate = bdrv_child_cb_inactivate,
1495 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1496 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1497 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001498 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001499};
1500
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001501AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1502{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05001503 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001504 return c->klass->get_parent_aio_context(c);
1505}
1506
Kevin Wolf7b272452012-11-12 17:05:39 +01001507static int bdrv_open_flags(BlockDriverState *bs, int flags)
1508{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001509 int open_flags = flags;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001510 GLOBAL_STATE_CODE();
Kevin Wolf7b272452012-11-12 17:05:39 +01001511
1512 /*
1513 * Clear flags that are internal to the block layer before opening the
1514 * image.
1515 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001516 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001517
Kevin Wolf7b272452012-11-12 17:05:39 +01001518 return open_flags;
1519}
1520
Kevin Wolf91a097e2015-05-08 17:49:53 +02001521static void update_flags_from_options(int *flags, QemuOpts *opts)
1522{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001523 GLOBAL_STATE_CODE();
1524
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001525 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001526
Alberto Garcia57f9db92018-09-06 12:37:06 +03001527 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001528 *flags |= BDRV_O_NO_FLUSH;
1529 }
1530
Alberto Garcia57f9db92018-09-06 12:37:06 +03001531 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001532 *flags |= BDRV_O_NOCACHE;
1533 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001534
Alberto Garcia57f9db92018-09-06 12:37:06 +03001535 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001536 *flags |= BDRV_O_RDWR;
1537 }
1538
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001539 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1540 *flags |= BDRV_O_AUTO_RDONLY;
1541 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001542}
1543
1544static void update_options_from_flags(QDict *options, int flags)
1545{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001546 GLOBAL_STATE_CODE();
Kevin Wolf91a097e2015-05-08 17:49:53 +02001547 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001548 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001549 }
1550 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001551 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1552 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001553 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001554 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001555 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001556 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001557 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1558 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1559 flags & BDRV_O_AUTO_RDONLY);
1560 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001561}
1562
Kevin Wolf636ea372014-01-24 14:11:52 +01001563static void bdrv_assign_node_name(BlockDriverState *bs,
1564 const char *node_name,
1565 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001566{
Jeff Cody15489c72015-10-12 19:36:50 -04001567 char *gen_node_name = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001568 GLOBAL_STATE_CODE();
Benoît Canet6913c0c2014-01-23 21:31:33 +01001569
Jeff Cody15489c72015-10-12 19:36:50 -04001570 if (!node_name) {
1571 node_name = gen_node_name = id_generate(ID_BLOCK);
1572 } else if (!id_wellformed(node_name)) {
1573 /*
1574 * Check for empty string or invalid characters, but not if it is
1575 * generated (generated names use characters not available to the user)
1576 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001577 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001578 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001579 }
1580
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001581 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001582 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001583 error_setg(errp, "node-name=%s is conflicting with a device id",
1584 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001585 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001586 }
1587
Benoît Canet6913c0c2014-01-23 21:31:33 +01001588 /* takes care of avoiding duplicates node names */
1589 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001590 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001591 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001592 }
1593
Kevin Wolf824808d2018-07-04 13:28:29 +02001594 /* Make sure that the node name isn't truncated */
1595 if (strlen(node_name) >= sizeof(bs->node_name)) {
1596 error_setg(errp, "Node name too long");
1597 goto out;
1598 }
1599
Benoît Canet6913c0c2014-01-23 21:31:33 +01001600 /* copy node name into the bs and insert it into the graph list */
1601 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1602 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001603out:
1604 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001605}
1606
Kevin Wolf01a56502017-01-18 15:51:56 +01001607static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1608 const char *node_name, QDict *options,
1609 int open_flags, Error **errp)
1610{
1611 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001612 int i, ret;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05001613 GLOBAL_STATE_CODE();
Kevin Wolf01a56502017-01-18 15:51:56 +01001614
1615 bdrv_assign_node_name(bs, node_name, &local_err);
1616 if (local_err) {
1617 error_propagate(errp, local_err);
1618 return -EINVAL;
1619 }
1620
1621 bs->drv = drv;
1622 bs->opaque = g_malloc0(drv->instance_size);
1623
1624 if (drv->bdrv_file_open) {
1625 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1626 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001627 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001628 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001629 } else {
1630 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001631 }
1632
1633 if (ret < 0) {
1634 if (local_err) {
1635 error_propagate(errp, local_err);
1636 } else if (bs->filename[0]) {
1637 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1638 } else {
1639 error_setg_errno(errp, -ret, "Could not open image");
1640 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001641 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001642 }
1643
1644 ret = refresh_total_sectors(bs, bs->total_sectors);
1645 if (ret < 0) {
1646 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001647 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001648 }
1649
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001650 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001651 if (local_err) {
1652 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001653 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001654 }
1655
1656 assert(bdrv_opt_mem_align(bs) != 0);
1657 assert(bdrv_min_mem_align(bs) != 0);
1658 assert(is_power_of_2(bs->bl.request_alignment));
1659
Kevin Wolf0f122642018-03-28 18:29:18 +02001660 for (i = 0; i < bs->quiesce_counter; i++) {
1661 if (drv->bdrv_co_drain_begin) {
1662 drv->bdrv_co_drain_begin(bs);
1663 }
1664 }
1665
Kevin Wolf01a56502017-01-18 15:51:56 +01001666 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001667open_failed:
1668 bs->drv = NULL;
1669 if (bs->file != NULL) {
1670 bdrv_unref_child(bs, bs->file);
1671 bs->file = NULL;
1672 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001673 g_free(bs->opaque);
1674 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001675 return ret;
1676}
1677
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001678/*
1679 * Create and open a block node.
1680 *
1681 * @options is a QDict of options to pass to the block drivers, or NULL for an
1682 * empty set of options. The reference to the QDict belongs to the block layer
1683 * after the call (even on failure), so if the caller intends to reuse the
1684 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1685 */
1686BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1687 const char *node_name,
1688 QDict *options, int flags,
1689 Error **errp)
Kevin Wolf680c7f92017-01-18 17:16:41 +01001690{
1691 BlockDriverState *bs;
1692 int ret;
1693
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001694 GLOBAL_STATE_CODE();
1695
Kevin Wolf680c7f92017-01-18 17:16:41 +01001696 bs = bdrv_new();
1697 bs->open_flags = flags;
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001698 bs->options = options ?: qdict_new();
1699 bs->explicit_options = qdict_clone_shallow(bs->options);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001700 bs->opaque = NULL;
1701
1702 update_options_from_flags(bs->options, flags);
1703
1704 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1705 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001706 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001707 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001708 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001709 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001710 bdrv_unref(bs);
1711 return NULL;
1712 }
1713
1714 return bs;
1715}
1716
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001717/* Create and open a block node. */
1718BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1719 int flags, Error **errp)
1720{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05001721 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy621d1732021-09-20 14:55:34 +03001722 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1723}
1724
Kevin Wolfc5f30142016-10-06 11:33:17 +02001725QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001726 .name = "bdrv_common",
1727 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1728 .desc = {
1729 {
1730 .name = "node-name",
1731 .type = QEMU_OPT_STRING,
1732 .help = "Node name of the block device node",
1733 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001734 {
1735 .name = "driver",
1736 .type = QEMU_OPT_STRING,
1737 .help = "Block driver to use for the node",
1738 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001739 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001740 .name = BDRV_OPT_CACHE_DIRECT,
1741 .type = QEMU_OPT_BOOL,
1742 .help = "Bypass software writeback cache on the host",
1743 },
1744 {
1745 .name = BDRV_OPT_CACHE_NO_FLUSH,
1746 .type = QEMU_OPT_BOOL,
1747 .help = "Ignore flush requests",
1748 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001749 {
1750 .name = BDRV_OPT_READ_ONLY,
1751 .type = QEMU_OPT_BOOL,
1752 .help = "Node is opened in read-only mode",
1753 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001754 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001755 .name = BDRV_OPT_AUTO_READ_ONLY,
1756 .type = QEMU_OPT_BOOL,
1757 .help = "Node can become read-only if opening read-write fails",
1758 },
1759 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001760 .name = "detect-zeroes",
1761 .type = QEMU_OPT_STRING,
1762 .help = "try to optimize zero writes (off, on, unmap)",
1763 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001764 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001765 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001766 .type = QEMU_OPT_STRING,
1767 .help = "discard operation (ignore/off, unmap/on)",
1768 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001769 {
1770 .name = BDRV_OPT_FORCE_SHARE,
1771 .type = QEMU_OPT_BOOL,
1772 .help = "always accept other writers (default: off)",
1773 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001774 { /* end of list */ }
1775 },
1776};
1777
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001778QemuOptsList bdrv_create_opts_simple = {
1779 .name = "simple-create-opts",
1780 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001781 .desc = {
1782 {
1783 .name = BLOCK_OPT_SIZE,
1784 .type = QEMU_OPT_SIZE,
1785 .help = "Virtual disk size"
1786 },
1787 {
1788 .name = BLOCK_OPT_PREALLOC,
1789 .type = QEMU_OPT_STRING,
1790 .help = "Preallocation mode (allowed values: off)"
1791 },
1792 { /* end of list */ }
1793 }
1794};
1795
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001796/*
Kevin Wolf57915332010-04-14 15:24:50 +02001797 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001798 *
1799 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001800 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001801static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001802 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001803{
1804 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001805 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001806 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001807 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001808 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001809 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001810 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001811 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001812 bool ro;
Kevin Wolf57915332010-04-14 15:24:50 +02001813
Paolo Bonzini64058752012-05-08 16:51:49 +02001814 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001815 assert(options != NULL && bs->options != options);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001816 GLOBAL_STATE_CODE();
Kevin Wolf57915332010-04-14 15:24:50 +02001817
Kevin Wolf62392eb2015-04-24 16:38:02 +02001818 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001819 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001820 ret = -EINVAL;
1821 goto fail_opts;
1822 }
1823
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001824 update_flags_from_options(&bs->open_flags, opts);
1825
Kevin Wolf62392eb2015-04-24 16:38:02 +02001826 driver_name = qemu_opt_get(opts, "driver");
1827 drv = bdrv_find_format(driver_name);
1828 assert(drv != NULL);
1829
Fam Zheng5a9347c2017-05-03 00:35:37 +08001830 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1831
1832 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1833 error_setg(errp,
1834 BDRV_OPT_FORCE_SHARE
1835 "=on can only be used with read-only images");
1836 ret = -EINVAL;
1837 goto fail_opts;
1838 }
1839
Kevin Wolf45673672013-04-22 17:48:40 +02001840 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001841 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001842 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001843 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001844 /*
1845 * Caution: while qdict_get_try_str() is fine, getting
1846 * non-string types would require more care. When @options
1847 * come from -blockdev or blockdev_add, its members are typed
1848 * according to the QAPI schema, but when they come from
1849 * -drive, they're all QString.
1850 */
Kevin Wolf45673672013-04-22 17:48:40 +02001851 filename = qdict_get_try_str(options, "filename");
1852 }
1853
Max Reitz4a008242017-04-13 18:06:24 +02001854 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001855 error_setg(errp, "The '%s' block driver requires a file name",
1856 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001857 ret = -EINVAL;
1858 goto fail_opts;
1859 }
1860
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001861 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1862 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001863
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001864 ro = bdrv_is_read_only(bs);
1865
1866 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1867 if (!ro && bdrv_is_whitelisted(drv, true)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001868 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1869 } else {
1870 ret = -ENOTSUP;
1871 }
1872 if (ret < 0) {
1873 error_setg(errp,
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001874 !ro && bdrv_is_whitelisted(drv, true)
Kevin Wolf8be25de2019-01-22 13:15:31 +01001875 ? "Driver '%s' can only be used for read-only devices"
1876 : "Driver '%s' is not whitelisted",
1877 drv->format_name);
1878 goto fail_opts;
1879 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001880 }
Kevin Wolf57915332010-04-14 15:24:50 +02001881
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001882 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001883 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001884
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001885 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001886 if (!ro) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001887 bdrv_enable_copy_on_read(bs);
1888 } else {
1889 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001890 ret = -EINVAL;
1891 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001892 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001893 }
1894
Alberto Garcia415bbca2018-10-03 13:23:13 +03001895 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001896 if (discard != NULL) {
1897 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1898 error_setg(errp, "Invalid discard option");
1899 ret = -EINVAL;
1900 goto fail_opts;
1901 }
1902 }
1903
Alberto Garcia543770b2018-09-06 12:37:09 +03001904 bs->detect_zeroes =
1905 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1906 if (local_err) {
1907 error_propagate(errp, local_err);
1908 ret = -EINVAL;
1909 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001910 }
1911
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001912 if (filename != NULL) {
1913 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1914 } else {
1915 bs->filename[0] = '\0';
1916 }
Max Reitz91af7012014-07-18 20:24:56 +02001917 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001918
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001919 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001920 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001921 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001922
Kevin Wolf01a56502017-01-18 15:51:56 +01001923 assert(!drv->bdrv_file_open || file == NULL);
1924 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001925 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001926 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001927 }
1928
Kevin Wolf18edf282015-04-07 17:12:56 +02001929 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001930 return 0;
1931
Kevin Wolf18edf282015-04-07 17:12:56 +02001932fail_opts:
1933 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001934 return ret;
1935}
1936
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001937static QDict *parse_json_filename(const char *filename, Error **errp)
1938{
1939 QObject *options_obj;
1940 QDict *options;
1941 int ret;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001942 GLOBAL_STATE_CODE();
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001943
1944 ret = strstart(filename, "json:", &filename);
1945 assert(ret);
1946
Markus Armbruster5577fff2017-02-28 22:26:59 +01001947 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001948 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001949 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001950 return NULL;
1951 }
1952
Max Reitz7dc847e2018-02-24 16:40:29 +01001953 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001954 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001955 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001956 error_setg(errp, "Invalid JSON object given");
1957 return NULL;
1958 }
1959
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001960 qdict_flatten(options);
1961
1962 return options;
1963}
1964
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001965static void parse_json_protocol(QDict *options, const char **pfilename,
1966 Error **errp)
1967{
1968 QDict *json_options;
1969 Error *local_err = NULL;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05001970 GLOBAL_STATE_CODE();
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001971
1972 /* Parse json: pseudo-protocol */
1973 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1974 return;
1975 }
1976
1977 json_options = parse_json_filename(*pfilename, &local_err);
1978 if (local_err) {
1979 error_propagate(errp, local_err);
1980 return;
1981 }
1982
1983 /* Options given in the filename have lower priority than options
1984 * specified directly */
1985 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001986 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001987 *pfilename = NULL;
1988}
1989
Kevin Wolf57915332010-04-14 15:24:50 +02001990/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001991 * Fills in default options for opening images and converts the legacy
1992 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001993 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1994 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001995 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001996static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001997 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001998{
1999 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04002000 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002001 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02002002 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002003 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002004
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002005 GLOBAL_STATE_CODE();
2006
Markus Armbruster129c7d12017-03-30 19:43:12 +02002007 /*
2008 * Caution: while qdict_get_try_str() is fine, getting non-string
2009 * types would require more care. When @options come from
2010 * -blockdev or blockdev_add, its members are typed according to
2011 * the QAPI schema, but when they come from -drive, they're all
2012 * QString.
2013 */
Max Reitz53a29512015-03-19 14:53:16 -04002014 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02002015 if (drvname) {
2016 drv = bdrv_find_format(drvname);
2017 if (!drv) {
2018 error_setg(errp, "Unknown driver '%s'", drvname);
2019 return -ENOENT;
2020 }
2021 /* If the user has explicitly specified the driver, this choice should
2022 * override the BDRV_O_PROTOCOL flag */
2023 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04002024 }
2025
2026 if (protocol) {
2027 *flags |= BDRV_O_PROTOCOL;
2028 } else {
2029 *flags &= ~BDRV_O_PROTOCOL;
2030 }
2031
Kevin Wolf91a097e2015-05-08 17:49:53 +02002032 /* Translate cache options from flags into options */
2033 update_options_from_flags(*options, *flags);
2034
Kevin Wolff54120f2014-05-26 11:09:59 +02002035 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002036 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002037 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002038 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02002039 parse_filename = true;
2040 } else {
2041 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2042 "the same time");
2043 return -EINVAL;
2044 }
2045 }
2046
2047 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02002048 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02002049 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02002050
Max Reitz053e1572015-08-26 19:47:51 +02002051 if (!drvname && protocol) {
2052 if (filename) {
2053 drv = bdrv_find_protocol(filename, parse_filename, errp);
2054 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002055 return -EINVAL;
2056 }
Max Reitz053e1572015-08-26 19:47:51 +02002057
2058 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05002059 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02002060 } else {
2061 error_setg(errp, "Must specify either driver or file");
2062 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02002063 }
2064 }
2065
Kevin Wolf17b005f2014-05-27 10:50:29 +02002066 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02002067
2068 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02002069 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02002070 drv->bdrv_parse_filename(filename, *options, &local_err);
2071 if (local_err) {
2072 error_propagate(errp, local_err);
2073 return -EINVAL;
2074 }
2075
2076 if (!drv->bdrv_needs_filename) {
2077 qdict_del(*options, "filename");
2078 }
2079 }
2080
2081 return 0;
2082}
2083
Kevin Wolf148eb132017-09-14 14:32:04 +02002084typedef struct BlockReopenQueueEntry {
2085 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01002086 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02002087 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002088 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02002089} BlockReopenQueueEntry;
2090
2091/*
2092 * Return the flags that @bs will have after the reopens in @q have
2093 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2094 * return the current flags.
2095 */
2096static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2097{
2098 BlockReopenQueueEntry *entry;
2099
2100 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002101 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002102 if (entry->state.bs == bs) {
2103 return entry->state.flags;
2104 }
2105 }
2106 }
2107
2108 return bs->open_flags;
2109}
2110
2111/* Returns whether the image file can be written to after the reopen queue @q
2112 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002113static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2114 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002115{
2116 int flags = bdrv_reopen_get_flags(q, bs);
2117
2118 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2119}
2120
Max Reitzcc022142018-06-06 21:37:00 +02002121/*
2122 * Return whether the BDS can be written to. This is not necessarily
2123 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2124 * be written to but do not count as read-only images.
2125 */
2126bool bdrv_is_writable(BlockDriverState *bs)
2127{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05002128 IO_CODE();
Max Reitzcc022142018-06-06 21:37:00 +02002129 return bdrv_is_writable_after_reopen(bs, NULL);
2130}
2131
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002132static char *bdrv_child_user_desc(BdrvChild *c)
2133{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002134 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002135 return c->klass->get_parent_desc(c);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002136}
2137
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002138/*
2139 * Check that @a allows everything that @b needs. @a and @b must reference same
2140 * child node.
2141 */
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002142static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2143{
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002144 const char *child_bs_name;
2145 g_autofree char *a_user = NULL;
2146 g_autofree char *b_user = NULL;
2147 g_autofree char *perms = NULL;
2148
2149 assert(a->bs);
2150 assert(a->bs == b->bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002151 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002152
2153 if ((b->perm & a->shared_perm) == b->perm) {
2154 return true;
2155 }
2156
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002157 child_bs_name = bdrv_get_node_name(b->bs);
2158 a_user = bdrv_child_user_desc(a);
2159 b_user = bdrv_child_user_desc(b);
2160 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2161
2162 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2163 "both required by %s (uses node '%s' as '%s' child) and "
2164 "unshared by %s (uses node '%s' as '%s' child).",
2165 child_bs_name, perms,
2166 b_user, child_bs_name, b->name,
2167 a_user, child_bs_name, a->name);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002168
2169 return false;
2170}
2171
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002172static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002173{
2174 BdrvChild *a, *b;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002175 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002176
2177 /*
2178 * During the loop we'll look at each pair twice. That's correct because
2179 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2180 * directions.
2181 */
2182 QLIST_FOREACH(a, &bs->parents, next_parent) {
2183 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002184 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002185 continue;
2186 }
2187
2188 if (!bdrv_a_allow_b(a, b, errp)) {
2189 return true;
2190 }
2191 }
2192 }
2193
2194 return false;
2195}
2196
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002197static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002198 BdrvChild *c, BdrvChildRole role,
2199 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002200 uint64_t parent_perm, uint64_t parent_shared,
2201 uint64_t *nperm, uint64_t *nshared)
2202{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002203 assert(bs->drv && bs->drv->bdrv_child_perm);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002204 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002205 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002206 parent_perm, parent_shared,
2207 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002208 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002209 if (child_bs && child_bs->force_share) {
2210 *nshared = BLK_PERM_ALL;
2211 }
2212}
2213
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002214/*
2215 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2216 * nodes that are already in the @list, of course) so that final list is
2217 * topologically sorted. Return the result (GSList @list object is updated, so
2218 * don't use old reference after function call).
2219 *
2220 * On function start @list must be already topologically sorted and for any node
2221 * in the @list the whole subtree of the node must be in the @list as well. The
2222 * simplest way to satisfy this criteria: use only result of
2223 * bdrv_topological_dfs() or NULL as @list parameter.
2224 */
2225static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2226 BlockDriverState *bs)
2227{
2228 BdrvChild *child;
2229 g_autoptr(GHashTable) local_found = NULL;
2230
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002231 GLOBAL_STATE_CODE();
2232
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002233 if (!found) {
2234 assert(!list);
2235 found = local_found = g_hash_table_new(NULL, NULL);
2236 }
2237
2238 if (g_hash_table_contains(found, bs)) {
2239 return list;
2240 }
2241 g_hash_table_add(found, bs);
2242
2243 QLIST_FOREACH(child, &bs->children, next) {
2244 list = bdrv_topological_dfs(list, found, child->bs);
2245 }
2246
2247 return g_slist_prepend(list, bs);
2248}
2249
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002250typedef struct BdrvChildSetPermState {
2251 BdrvChild *child;
2252 uint64_t old_perm;
2253 uint64_t old_shared_perm;
2254} BdrvChildSetPermState;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002255
2256static void bdrv_child_set_perm_abort(void *opaque)
2257{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002258 BdrvChildSetPermState *s = opaque;
2259
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002260 GLOBAL_STATE_CODE();
2261
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002262 s->child->perm = s->old_perm;
2263 s->child->shared_perm = s->old_shared_perm;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002264}
2265
2266static TransactionActionDrv bdrv_child_set_pem_drv = {
2267 .abort = bdrv_child_set_perm_abort,
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002268 .clean = g_free,
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002269};
2270
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002271static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2272 uint64_t shared, Transaction *tran)
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002273{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002274 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002275 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002276
2277 *s = (BdrvChildSetPermState) {
2278 .child = c,
2279 .old_perm = c->perm,
2280 .old_shared_perm = c->shared_perm,
2281 };
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002282
2283 c->perm = perm;
2284 c->shared_perm = shared;
2285
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002286 tran_add(tran, &bdrv_child_set_pem_drv, s);
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002287}
2288
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002289static void bdrv_drv_set_perm_commit(void *opaque)
2290{
2291 BlockDriverState *bs = opaque;
2292 uint64_t cumulative_perms, cumulative_shared_perms;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002293 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002294
2295 if (bs->drv->bdrv_set_perm) {
2296 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2297 &cumulative_shared_perms);
2298 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2299 }
2300}
2301
2302static void bdrv_drv_set_perm_abort(void *opaque)
2303{
2304 BlockDriverState *bs = opaque;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002305 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002306
2307 if (bs->drv->bdrv_abort_perm_update) {
2308 bs->drv->bdrv_abort_perm_update(bs);
2309 }
2310}
2311
2312TransactionActionDrv bdrv_drv_set_perm_drv = {
2313 .abort = bdrv_drv_set_perm_abort,
2314 .commit = bdrv_drv_set_perm_commit,
2315};
2316
2317static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2318 uint64_t shared_perm, Transaction *tran,
2319 Error **errp)
2320{
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05002321 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002322 if (!bs->drv) {
2323 return 0;
2324 }
2325
2326 if (bs->drv->bdrv_check_perm) {
2327 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2328 if (ret < 0) {
2329 return ret;
2330 }
2331 }
2332
2333 if (tran) {
2334 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2335 }
2336
2337 return 0;
2338}
2339
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002340typedef struct BdrvReplaceChildState {
2341 BdrvChild *child;
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002342 BdrvChild **childp;
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002343 BlockDriverState *old_bs;
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002344 bool free_empty_child;
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002345} BdrvReplaceChildState;
2346
2347static void bdrv_replace_child_commit(void *opaque)
2348{
2349 BdrvReplaceChildState *s = opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002350 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002351
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002352 if (s->free_empty_child && !s->child->bs) {
2353 bdrv_child_free(s->child);
2354 }
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002355 bdrv_unref(s->old_bs);
2356}
2357
2358static void bdrv_replace_child_abort(void *opaque)
2359{
2360 BdrvReplaceChildState *s = opaque;
2361 BlockDriverState *new_bs = s->child->bs;
2362
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002363 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002364 /*
2365 * old_bs reference is transparently moved from @s to s->child.
2366 *
2367 * Pass &s->child here instead of s->childp, because:
2368 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2369 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2370 * will not modify s->child. From that perspective, it does not matter
2371 * whether we pass s->childp or &s->child.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002372 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2373 * it here.
2374 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2375 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2376 * must not pass a NULL *s->childp here.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002377 *
2378 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2379 * any case, there is no reason to pass it anyway.
2380 */
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002381 bdrv_replace_child_noperm(&s->child, s->old_bs, true);
2382 /*
2383 * The child was pre-existing, so s->old_bs must be non-NULL, and
2384 * s->child thus must not have been freed
2385 */
2386 assert(s->child != NULL);
2387 if (!new_bs) {
2388 /* As described above, *s->childp was cleared, so restore it */
2389 assert(s->childp != NULL);
2390 *s->childp = s->child;
2391 }
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002392 bdrv_unref(new_bs);
2393}
2394
2395static TransactionActionDrv bdrv_replace_child_drv = {
2396 .commit = bdrv_replace_child_commit,
2397 .abort = bdrv_replace_child_abort,
2398 .clean = g_free,
2399};
2400
2401/*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002402 * bdrv_replace_child_tran
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002403 *
2404 * Note: real unref of old_bs is done only on commit.
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002405 *
2406 * The function doesn't update permissions, caller is responsible for this.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002407 *
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002408 * (*childp)->bs must not be NULL.
2409 *
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002410 * Note that if new_bs == NULL, @childp is stored in a state object attached
2411 * to @tran, so that the old child can be reinstated in the abort handler.
2412 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2413 * transaction is committed or aborted.
2414 *
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002415 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2416 * freed (on commit). @free_empty_child should only be false if the
2417 * caller will free the BDrvChild themselves (which may be important
2418 * if this is in turn called in another transactional context).
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002419 */
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002420static void bdrv_replace_child_tran(BdrvChild **childp,
2421 BlockDriverState *new_bs,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002422 Transaction *tran,
2423 bool free_empty_child)
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002424{
2425 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2426 *s = (BdrvReplaceChildState) {
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002427 .child = *childp,
2428 .childp = new_bs == NULL ? childp : NULL,
2429 .old_bs = (*childp)->bs,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002430 .free_empty_child = free_empty_child,
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002431 };
2432 tran_add(tran, &bdrv_replace_child_drv, s);
2433
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002434 /* The abort handler relies on this */
2435 assert(s->old_bs != NULL);
2436
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002437 if (new_bs) {
2438 bdrv_ref(new_bs);
2439 }
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002440 /*
2441 * Pass free_empty_child=false, we will free the child (if
2442 * necessary) in bdrv_replace_child_commit() (if our
2443 * @free_empty_child parameter was true).
2444 */
2445 bdrv_replace_child_noperm(childp, new_bs, false);
Hanna Reitz82b54cf2021-11-15 15:54:04 +01002446 /* old_bs reference is transparently moved from *childp 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-Ogievskiy071b4742020-11-06 15:42:41 +03002594static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002595{
2596 int ret;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002597 Transaction *tran = tran_new();
2598 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002599 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002600
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002601 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2602 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002603
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002604 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002605}
2606
Kevin Wolf33a610c2016-12-15 13:04:20 +01002607int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2608 Error **errp)
2609{
Max Reitz10467792019-05-22 19:03:51 +02002610 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002611 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002612 int ret;
2613
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002614 GLOBAL_STATE_CODE();
2615
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002616 bdrv_child_set_perm(c, perm, shared, tran);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002617
2618 ret = bdrv_refresh_perms(c->bs, &local_err);
2619
2620 tran_finalize(tran, ret);
2621
Kevin Wolf33a610c2016-12-15 13:04:20 +01002622 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002623 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2624 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002625 error_propagate(errp, local_err);
2626 } else {
2627 /*
2628 * Our caller may intend to only loosen restrictions and
2629 * does not expect this function to fail. Errors are not
2630 * fatal in such a case, so we can just hide them from our
2631 * caller.
2632 */
2633 error_free(local_err);
2634 ret = 0;
2635 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002636 }
2637
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002638 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002639}
2640
Max Reitzc1087f12019-05-22 19:03:46 +02002641int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2642{
2643 uint64_t parent_perms, parent_shared;
2644 uint64_t perms, shared;
2645
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002646 GLOBAL_STATE_CODE();
2647
Max Reitzc1087f12019-05-22 19:03:46 +02002648 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002649 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002650 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002651
2652 return bdrv_child_try_set_perm(c, perms, shared, errp);
2653}
2654
Max Reitz87278af2020-05-13 13:05:40 +02002655/*
2656 * Default implementation for .bdrv_child_perm() for block filters:
2657 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2658 * filtered child.
2659 */
2660static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002661 BdrvChildRole role,
2662 BlockReopenQueue *reopen_queue,
2663 uint64_t perm, uint64_t shared,
2664 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002665{
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002666 GLOBAL_STATE_CODE();
Kevin Wolfe444fa82019-08-02 15:59:41 +02002667 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2668 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002669}
2670
Max Reitz70082db2020-05-13 13:05:26 +02002671static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002672 BdrvChildRole role,
2673 BlockReopenQueue *reopen_queue,
2674 uint64_t perm, uint64_t shared,
2675 uint64_t *nperm, uint64_t *nshared)
2676{
Max Reitze5d8a402020-05-13 13:05:44 +02002677 assert(role & BDRV_CHILD_COW);
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002678 GLOBAL_STATE_CODE();
Max Reitz70082db2020-05-13 13:05:26 +02002679
2680 /*
2681 * We want consistent read from backing files if the parent needs it.
2682 * No other operations are performed on backing files.
2683 */
2684 perm &= BLK_PERM_CONSISTENT_READ;
2685
2686 /*
2687 * If the parent can deal with changing data, we're okay with a
2688 * writable and resizable backing file.
2689 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2690 */
2691 if (shared & BLK_PERM_WRITE) {
2692 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2693 } else {
2694 shared = 0;
2695 }
2696
Vladimir Sementsov-Ogievskiy64631f32021-09-02 12:37:54 +03002697 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
Max Reitz70082db2020-05-13 13:05:26 +02002698
2699 if (bs->open_flags & BDRV_O_INACTIVE) {
2700 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2701 }
2702
2703 *nperm = perm;
2704 *nshared = shared;
2705}
2706
Max Reitz6f838a42020-05-13 13:05:27 +02002707static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002708 BdrvChildRole role,
2709 BlockReopenQueue *reopen_queue,
2710 uint64_t perm, uint64_t shared,
2711 uint64_t *nperm, uint64_t *nshared)
2712{
2713 int flags;
2714
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05002715 GLOBAL_STATE_CODE();
Max Reitze5d8a402020-05-13 13:05:44 +02002716 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002717
2718 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2719
2720 /*
2721 * Apart from the modifications below, the same permissions are
2722 * forwarded and left alone as for filters
2723 */
Max Reitze5d8a402020-05-13 13:05:44 +02002724 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002725 perm, shared, &perm, &shared);
2726
Max Reitzf8890542020-05-13 13:05:28 +02002727 if (role & BDRV_CHILD_METADATA) {
2728 /* Format drivers may touch metadata even if the guest doesn't write */
2729 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2730 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2731 }
2732
2733 /*
2734 * bs->file always needs to be consistent because of the
2735 * metadata. We can never allow other users to resize or write
2736 * to it.
2737 */
2738 if (!(flags & BDRV_O_NO_IO)) {
2739 perm |= BLK_PERM_CONSISTENT_READ;
2740 }
2741 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002742 }
2743
Max Reitzf8890542020-05-13 13:05:28 +02002744 if (role & BDRV_CHILD_DATA) {
2745 /*
2746 * Technically, everything in this block is a subset of the
2747 * BDRV_CHILD_METADATA path taken above, and so this could
2748 * be an "else if" branch. However, that is not obvious, and
2749 * this function is not performance critical, therefore we let
2750 * this be an independent "if".
2751 */
2752
2753 /*
2754 * We cannot allow other users to resize the file because the
2755 * format driver might have some assumptions about the size
2756 * (e.g. because it is stored in metadata, or because the file
2757 * is split into fixed-size data files).
2758 */
2759 shared &= ~BLK_PERM_RESIZE;
2760
2761 /*
2762 * WRITE_UNCHANGED often cannot be performed as such on the
2763 * data file. For example, the qcow2 driver may still need to
2764 * write copied clusters on copy-on-read.
2765 */
2766 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2767 perm |= BLK_PERM_WRITE;
2768 }
2769
2770 /*
2771 * If the data file is written to, the format driver may
2772 * expect to be able to resize it by writing beyond the EOF.
2773 */
2774 if (perm & BLK_PERM_WRITE) {
2775 perm |= BLK_PERM_RESIZE;
2776 }
Max Reitz6f838a42020-05-13 13:05:27 +02002777 }
Max Reitz6f838a42020-05-13 13:05:27 +02002778
2779 if (bs->open_flags & BDRV_O_INACTIVE) {
2780 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2781 }
2782
2783 *nperm = perm;
2784 *nshared = shared;
2785}
2786
Max Reitz2519f542020-05-13 13:05:29 +02002787void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002788 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002789 uint64_t perm, uint64_t shared,
2790 uint64_t *nperm, uint64_t *nshared)
2791{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05002792 GLOBAL_STATE_CODE();
Max Reitz2519f542020-05-13 13:05:29 +02002793 if (role & BDRV_CHILD_FILTERED) {
2794 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2795 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002796 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002797 perm, shared, nperm, nshared);
2798 } else if (role & BDRV_CHILD_COW) {
2799 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002800 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002801 perm, shared, nperm, nshared);
2802 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002803 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002804 perm, shared, nperm, nshared);
2805 } else {
2806 g_assert_not_reached();
2807 }
2808}
2809
Max Reitz7b1d9c42019-11-08 13:34:51 +01002810uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2811{
2812 static const uint64_t permissions[] = {
2813 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2814 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2815 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2816 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
Max Reitz7b1d9c42019-11-08 13:34:51 +01002817 };
2818
2819 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2820 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2821
2822 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2823
2824 return permissions[qapi_perm];
2825}
2826
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002827/**
2828 * Replace (*childp)->bs by @new_bs.
2829 *
2830 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2831 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2832 * BdrvChild.bs should generally immediately be followed by the
2833 * BdrvChild pointer being cleared as well.
2834 *
2835 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2836 * freed. @free_empty_child should only be false if the caller will
2837 * free the BdrvChild themselves (this may be important in a
2838 * transactional context, where it may only be freed on commit).
2839 */
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002840static void bdrv_replace_child_noperm(BdrvChild **childp,
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002841 BlockDriverState *new_bs,
2842 bool free_empty_child)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002843{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01002844 BdrvChild *child = *childp;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002845 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002846 int new_bs_quiesce_counter;
2847 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002848
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002849 assert(!child->frozen);
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02002850 assert(old_bs != new_bs);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002851 GLOBAL_STATE_CODE();
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002852
Fam Zhengbb2614e2017-04-07 14:54:10 +08002853 if (old_bs && new_bs) {
2854 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2855 }
Max Reitzdebc2922019-07-22 15:33:44 +02002856
2857 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2858 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2859
2860 /*
2861 * If the new child node is drained but the old one was not, flush
2862 * all outstanding requests to the old child node.
2863 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002864 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002865 bdrv_parent_drained_begin_single(child, true);
2866 drain_saldo--;
2867 }
2868
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002869 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002870 /* Detach first so that the recursive drain sections coming from @child
2871 * are already gone and we only end the drain sections that came from
2872 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002873 if (child->klass->detach) {
2874 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002875 }
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002876 assert_bdrv_graph_writable(old_bs);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002877 QLIST_REMOVE(child, next_parent);
2878 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002879
2880 child->bs = new_bs;
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002881 if (!new_bs) {
2882 *childp = NULL;
2883 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002884
2885 if (new_bs) {
Emanuele Giuseppe Esposito696bf4c2022-03-03 10:15:59 -05002886 assert_bdrv_graph_writable(new_bs);
Kevin Wolf36fe1332016-05-17 14:51:55 +02002887 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002888
2889 /*
2890 * Detaching the old node may have led to the new node's
2891 * quiesce_counter having been decreased. Not a problem, we
2892 * just need to recognize this here and then invoke
2893 * drained_end appropriately more often.
2894 */
2895 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2896 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002897
Kevin Wolfd736f112017-12-18 16:05:48 +01002898 /* Attach only after starting new drained sections, so that recursive
2899 * drain sections coming from @child don't get an extra .drained_begin
2900 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002901 if (child->klass->attach) {
2902 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002903 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002904 }
Max Reitzdebc2922019-07-22 15:33:44 +02002905
2906 /*
2907 * If the old child node was drained but the new one is not, allow
2908 * requests to come in only after the new node has been attached.
2909 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002910 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002911 bdrv_parent_drained_end_single(child);
2912 drain_saldo++;
2913 }
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002914
2915 if (free_empty_child && !child->bs) {
2916 bdrv_child_free(child);
2917 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002918}
2919
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002920/**
2921 * Free the given @child.
2922 *
2923 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2924 * unused (i.e. not in a children list).
2925 */
2926static void bdrv_child_free(BdrvChild *child)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002927{
2928 assert(!child->bs);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05002929 GLOBAL_STATE_CODE();
Hanna Reitza2253692021-11-15 15:53:58 +01002930 assert(!child->next.le_prev); /* not in children list */
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002931
2932 g_free(child->name);
2933 g_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002934}
2935
2936typedef struct BdrvAttachChildCommonState {
2937 BdrvChild **child;
2938 AioContext *old_parent_ctx;
2939 AioContext *old_child_ctx;
2940} BdrvAttachChildCommonState;
2941
2942static void bdrv_attach_child_common_abort(void *opaque)
2943{
2944 BdrvAttachChildCommonState *s = opaque;
2945 BdrvChild *child = *s->child;
2946 BlockDriverState *bs = child->bs;
2947
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05002948 GLOBAL_STATE_CODE();
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01002949 /*
2950 * Pass free_empty_child=false, because we still need the child
2951 * for the AioContext operations on the parent below; those
2952 * BdrvChildClass methods all work on a BdrvChild object, so we
2953 * need to keep it as an empty shell (after this function, it will
2954 * not be attached to any parent, and it will not have a .bs).
2955 */
2956 bdrv_replace_child_noperm(s->child, NULL, false);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002957
2958 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2959 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2960 }
2961
2962 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
Hanna Reitz26518062021-11-15 15:54:00 +01002963 GSList *ignore;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002964
Hanna Reitz26518062021-11-15 15:54:00 +01002965 /* No need to ignore `child`, because it has been detached already */
2966 ignore = NULL;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002967 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2968 &error_abort);
2969 g_slist_free(ignore);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002970
Hanna Reitz26518062021-11-15 15:54:00 +01002971 ignore = NULL;
2972 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002973 g_slist_free(ignore);
2974 }
2975
2976 bdrv_unref(bs);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01002977 bdrv_child_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002978}
2979
2980static TransactionActionDrv bdrv_attach_child_common_drv = {
2981 .abort = bdrv_attach_child_common_abort,
2982 .clean = g_free,
2983};
2984
2985/*
2986 * Common part of attaching bdrv child to bs or to blk or to job
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002987 *
2988 * Resulting new child is returned through @child.
2989 * At start *@child must be NULL.
2990 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2991 * NULL on abort(). So referenced variable must live at least until transaction
2992 * end.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002993 *
2994 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002995 */
2996static int bdrv_attach_child_common(BlockDriverState *child_bs,
2997 const char *child_name,
2998 const BdrvChildClass *child_class,
2999 BdrvChildRole child_role,
3000 uint64_t perm, uint64_t shared_perm,
3001 void *opaque, BdrvChild **child,
3002 Transaction *tran, Error **errp)
3003{
3004 BdrvChild *new_child;
3005 AioContext *parent_ctx;
3006 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3007
3008 assert(child);
3009 assert(*child == NULL);
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03003010 assert(child_class->get_parent_desc);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003011 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003012
3013 new_child = g_new(BdrvChild, 1);
3014 *new_child = (BdrvChild) {
3015 .bs = NULL,
3016 .name = g_strdup(child_name),
3017 .klass = child_class,
3018 .role = child_role,
3019 .perm = perm,
3020 .shared_perm = shared_perm,
3021 .opaque = opaque,
3022 };
3023
3024 /*
3025 * If the AioContexts don't match, first try to move the subtree of
3026 * child_bs into the AioContext of the new parent. If this doesn't work,
3027 * try moving the parent into the AioContext of child_bs instead.
3028 */
3029 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3030 if (child_ctx != parent_ctx) {
3031 Error *local_err = NULL;
3032 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
3033
3034 if (ret < 0 && child_class->can_set_aio_ctx) {
3035 GSList *ignore = g_slist_prepend(NULL, new_child);
3036 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
3037 NULL))
3038 {
3039 error_free(local_err);
3040 ret = 0;
3041 g_slist_free(ignore);
3042 ignore = g_slist_prepend(NULL, new_child);
3043 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
3044 }
3045 g_slist_free(ignore);
3046 }
3047
3048 if (ret < 0) {
3049 error_propagate(errp, local_err);
Hanna Reitz04c9c3a2021-11-15 15:53:59 +01003050 bdrv_child_free(new_child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003051 return ret;
3052 }
3053 }
3054
3055 bdrv_ref(child_bs);
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01003056 bdrv_replace_child_noperm(&new_child, child_bs, true);
3057 /* child_bs was non-NULL, so new_child must not have been freed */
3058 assert(new_child != NULL);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003059
3060 *child = new_child;
3061
3062 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3063 *s = (BdrvAttachChildCommonState) {
3064 .child = child,
3065 .old_parent_ctx = parent_ctx,
3066 .old_child_ctx = child_ctx,
3067 };
3068 tran_add(tran, &bdrv_attach_child_common_drv, s);
3069
3070 return 0;
3071}
3072
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003073/*
3074 * Variable referenced by @child must live at least until transaction end.
3075 * (see bdrv_attach_child_common() doc for details)
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003076 *
3077 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003078 */
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003079static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3080 BlockDriverState *child_bs,
3081 const char *child_name,
3082 const BdrvChildClass *child_class,
3083 BdrvChildRole child_role,
3084 BdrvChild **child,
3085 Transaction *tran,
3086 Error **errp)
3087{
3088 int ret;
3089 uint64_t perm, shared_perm;
3090
3091 assert(parent_bs->drv);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003092 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003093
Kevin Wolfbfb8aa62021-10-18 15:47:14 +02003094 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3095 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3096 child_bs->node_name, child_name, parent_bs->node_name);
3097 return -EINVAL;
3098 }
3099
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003100 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3101 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3102 perm, shared_perm, &perm, &shared_perm);
3103
3104 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3105 child_role, perm, shared_perm, parent_bs,
3106 child, tran, errp);
3107 if (ret < 0) {
3108 return ret;
3109 }
3110
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003111 return 0;
3112}
3113
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003114static void bdrv_detach_child(BdrvChild **childp)
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003115{
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003116 BlockDriverState *old_bs = (*childp)->bs;
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003117
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003118 GLOBAL_STATE_CODE();
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01003119 bdrv_replace_child_noperm(childp, NULL, true);
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03003120
3121 if (old_bs) {
3122 /*
3123 * Update permissions for old node. We're just taking a parent away, so
3124 * we're loosening restrictions. Errors of permission update are not
3125 * fatal in this case, ignore them.
3126 */
3127 bdrv_refresh_perms(old_bs, NULL);
3128
3129 /*
3130 * When the parent requiring a non-default AioContext is removed, the
3131 * node moves back to the main AioContext
3132 */
3133 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3134 }
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003135}
3136
Alberto Garciab441dc72019-05-13 16:46:18 +03003137/*
3138 * This function steals the reference to child_bs from the caller.
3139 * That reference is later dropped by bdrv_root_unref_child().
3140 *
3141 * On failure NULL is returned, errp is set and the reference to
3142 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003143 *
3144 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3145 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003146 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003147BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3148 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003149 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003150 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003151 uint64_t perm, uint64_t shared_perm,
3152 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003153{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003154 int ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003155 BdrvChild *child = NULL;
3156 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003157
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05003158 GLOBAL_STATE_CODE();
3159
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003160 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3161 child_role, perm, shared_perm, opaque,
3162 &child, tran, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003163 if (ret < 0) {
Kevin Wolfe878bb12021-05-03 13:05:54 +02003164 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003165 }
3166
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003167 ret = bdrv_refresh_perms(child_bs, errp);
Kevin Wolfdf581792015-06-15 11:53:47 +02003168
Kevin Wolfe878bb12021-05-03 13:05:54 +02003169out:
3170 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003171 /* child is unset on failure by bdrv_attach_child_common_abort() */
3172 assert((ret < 0) == !child);
3173
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003174 bdrv_unref(child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003175 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003176}
3177
Alberto Garciab441dc72019-05-13 16:46:18 +03003178/*
3179 * This function transfers the reference to child_bs from the caller
3180 * to parent_bs. That reference is later dropped by parent_bs on
3181 * bdrv_close() or if someone calls bdrv_unref_child().
3182 *
3183 * On failure NULL is returned, errp is set and the reference to
3184 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003185 *
3186 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3187 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003188 */
Wen Congyang98292c62016-05-10 15:36:38 +08003189BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3190 BlockDriverState *child_bs,
3191 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003192 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003193 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003194 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003195{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003196 int ret;
3197 BdrvChild *child = NULL;
3198 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003199
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003200 GLOBAL_STATE_CODE();
3201
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003202 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3203 child_role, &child, tran, errp);
3204 if (ret < 0) {
3205 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003206 }
3207
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003208 ret = bdrv_refresh_perms(parent_bs, errp);
3209 if (ret < 0) {
3210 goto out;
3211 }
3212
3213out:
3214 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03003215 /* child is unset on failure by bdrv_attach_child_common_abort() */
3216 assert((ret < 0) == !child);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003217
3218 bdrv_unref(child_bs);
3219
Kevin Wolff21d96d2016-03-08 13:47:46 +01003220 return child;
3221}
3222
Max Reitz7b99a262019-06-12 16:07:11 +02003223/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003224void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003225{
Kevin Wolf779020c2015-10-13 14:09:44 +02003226 BlockDriverState *child_bs;
3227
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003228 GLOBAL_STATE_CODE();
3229
Kevin Wolff21d96d2016-03-08 13:47:46 +01003230 child_bs = child->bs;
Hanna Reitzbe64bbb2021-11-15 15:54:01 +01003231 bdrv_detach_child(&child);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003232 bdrv_unref(child_bs);
3233}
3234
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003235typedef struct BdrvSetInheritsFrom {
3236 BlockDriverState *bs;
3237 BlockDriverState *old_inherits_from;
3238} BdrvSetInheritsFrom;
3239
3240static void bdrv_set_inherits_from_abort(void *opaque)
3241{
3242 BdrvSetInheritsFrom *s = opaque;
3243
3244 s->bs->inherits_from = s->old_inherits_from;
3245}
3246
3247static TransactionActionDrv bdrv_set_inherits_from_drv = {
3248 .abort = bdrv_set_inherits_from_abort,
3249 .clean = g_free,
3250};
3251
3252/* @tran is allowed to be NULL. In this case no rollback is possible */
3253static void bdrv_set_inherits_from(BlockDriverState *bs,
3254 BlockDriverState *new_inherits_from,
3255 Transaction *tran)
3256{
3257 if (tran) {
3258 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3259
3260 *s = (BdrvSetInheritsFrom) {
3261 .bs = bs,
3262 .old_inherits_from = bs->inherits_from,
3263 };
3264
3265 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3266 }
3267
3268 bs->inherits_from = new_inherits_from;
3269}
3270
Max Reitz3cf746b2019-07-03 19:28:07 +02003271/**
3272 * Clear all inherits_from pointers from children and grandchildren of
3273 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003274 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003275 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003276static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3277 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003278{
Max Reitz3cf746b2019-07-03 19:28:07 +02003279 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003280
Max Reitz3cf746b2019-07-03 19:28:07 +02003281 if (child->bs->inherits_from == root) {
3282 /*
3283 * Remove inherits_from only when the last reference between root and
3284 * child->bs goes away.
3285 */
3286 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003287 if (c != child && c->bs == child->bs) {
3288 break;
3289 }
3290 }
3291 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003292 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003293 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003294 }
3295
Max Reitz3cf746b2019-07-03 19:28:07 +02003296 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003297 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003298 }
3299}
3300
Max Reitz7b99a262019-06-12 16:07:11 +02003301/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003302void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3303{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003304 GLOBAL_STATE_CODE();
Max Reitz3cf746b2019-07-03 19:28:07 +02003305 if (child == NULL) {
3306 return;
3307 }
3308
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003309 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003310 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003311}
3312
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003313
3314static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3315{
3316 BdrvChild *c;
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003317 GLOBAL_STATE_CODE();
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003318 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003319 if (c->klass->change_media) {
3320 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003321 }
3322 }
3323}
3324
Alberto Garcia0065c452018-10-31 18:16:37 +02003325/* Return true if you can reach parent going through child->inherits_from
3326 * recursively. If parent or child are NULL, return false */
3327static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3328 BlockDriverState *parent)
3329{
3330 while (child && child != parent) {
3331 child = child->inherits_from;
3332 }
3333
3334 return child != NULL;
3335}
3336
Kevin Wolf5db15a52015-09-14 15:33:33 +02003337/*
Max Reitz25191e52020-05-13 13:05:33 +02003338 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3339 * mostly used for COW backing children (role = COW), but also for
3340 * filtered children (role = FILTERED | PRIMARY).
3341 */
3342static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3343{
3344 if (bs->drv && bs->drv->is_filter) {
3345 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3346 } else {
3347 return BDRV_CHILD_COW;
3348 }
3349}
3350
3351/*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003352 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3353 * callers which don't need their own reference any more must call bdrv_unref().
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003354 *
3355 * Function doesn't update permissions, caller is responsible for this.
Kevin Wolf5db15a52015-09-14 15:33:33 +02003356 */
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003357static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3358 BlockDriverState *child_bs,
3359 bool is_backing,
3360 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003361{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003362 int ret = 0;
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003363 bool update_inherits_from =
3364 bdrv_inherits_from_recursive(child_bs, parent_bs);
3365 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3366 BdrvChildRole role;
Alberto Garcia0065c452018-10-31 18:16:37 +02003367
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003368 GLOBAL_STATE_CODE();
3369
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003370 if (!parent_bs->drv) {
3371 /*
3372 * Node without drv is an object without a class :/. TODO: finally fix
3373 * qcow2 driver to never clear bs->drv and implement format corruption
3374 * handling in other way.
3375 */
3376 error_setg(errp, "Node corrupted");
3377 return -EINVAL;
3378 }
3379
3380 if (child && child->frozen) {
3381 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3382 child->name, parent_bs->node_name, child->bs->node_name);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003383 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003384 }
3385
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03003386 if (is_backing && !parent_bs->drv->is_filter &&
3387 !parent_bs->drv->supports_backing)
3388 {
3389 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3390 "files", parent_bs->drv->format_name, parent_bs->node_name);
3391 return -EINVAL;
3392 }
3393
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003394 if (parent_bs->drv->is_filter) {
3395 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3396 } else if (is_backing) {
3397 role = BDRV_CHILD_COW;
3398 } else {
3399 /*
3400 * We only can use same role as it is in existing child. We don't have
3401 * infrastructure to determine role of file child in generic way
3402 */
3403 if (!child) {
3404 error_setg(errp, "Cannot set file child to format node without "
3405 "file child");
3406 return -EINVAL;
3407 }
3408 role = child->role;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003409 }
3410
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003411 if (child) {
3412 bdrv_unset_inherits_from(parent_bs, child, tran);
3413 bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3414 }
3415
3416 if (!child_bs) {
Fam Zheng8d24cce2014-05-23 21:29:45 +08003417 goto out;
3418 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003419
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003420 ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3421 is_backing ? "backing" : "file",
3422 &child_of_bds, role,
3423 is_backing ? &parent_bs->backing :
3424 &parent_bs->file,
3425 tran, errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003426 if (ret < 0) {
3427 return ret;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003428 }
3429
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003430
3431 /*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003432 * If inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003433 * point directly to bs (else it will become NULL).
3434 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003435 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003436 bdrv_set_inherits_from(child_bs, parent_bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003437 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003438
Fam Zheng8d24cce2014-05-23 21:29:45 +08003439out:
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003440 bdrv_refresh_limits(parent_bs, tran, NULL);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003441
3442 return 0;
3443}
3444
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003445static int bdrv_set_backing_noperm(BlockDriverState *bs,
3446 BlockDriverState *backing_hd,
3447 Transaction *tran, Error **errp)
3448{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003449 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003450 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3451}
3452
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003453int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3454 Error **errp)
3455{
3456 int ret;
3457 Transaction *tran = tran_new();
3458
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003459 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003460 bdrv_drained_begin(bs);
3461
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003462 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3463 if (ret < 0) {
3464 goto out;
3465 }
3466
3467 ret = bdrv_refresh_perms(bs, errp);
3468out:
3469 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003470
Vladimir Sementsov-Ogievskiyc0829cb2022-01-24 18:37:41 +01003471 bdrv_drained_end(bs);
3472
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003473 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003474}
3475
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003476/*
3477 * Opens the backing file for a BlockDriverState if not yet open
3478 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003479 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3480 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3481 * itself, all options starting with "${bdref_key}." are considered part of the
3482 * BlockdevRef.
3483 *
3484 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003485 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003486int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3487 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003488{
Max Reitz6b6833c2019-02-01 20:29:15 +01003489 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003490 char *bdref_key_dot;
3491 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003492 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003493 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003494 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003495 QDict *options;
3496 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003497 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003498
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003499 GLOBAL_STATE_CODE();
3500
Kevin Wolf760e0062015-06-17 14:55:21 +02003501 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003502 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003503 }
3504
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003505 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003506 if (parent_options == NULL) {
3507 tmp_parent_options = qdict_new();
3508 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003509 }
3510
Paolo Bonzini9156df12012-10-18 16:49:17 +02003511 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003512
3513 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3514 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3515 g_free(bdref_key_dot);
3516
Markus Armbruster129c7d12017-03-30 19:43:12 +02003517 /*
3518 * Caution: while qdict_get_try_str() is fine, getting non-string
3519 * types would require more care. When @parent_options come from
3520 * -blockdev or blockdev_add, its members are typed according to
3521 * the QAPI schema, but when they come from -drive, they're all
3522 * QString.
3523 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003524 reference = qdict_get_try_str(parent_options, bdref_key);
3525 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003526 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003527 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003528 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003529 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003530 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003531 if (qdict_size(options) == 0) {
3532 /* If the user specifies options that do not modify the
3533 * backing file's behavior, we might still consider it the
3534 * implicit backing file. But it's easier this way, and
3535 * just specifying some of the backing BDS's options is
3536 * only possible with -drive anyway (otherwise the QAPI
3537 * schema forces the user to specify everything). */
3538 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3539 }
3540
Max Reitz6b6833c2019-02-01 20:29:15 +01003541 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003542 if (local_err) {
3543 ret = -EINVAL;
3544 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003545 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003546 goto free_exit;
3547 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003548 }
3549
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003550 if (!bs->drv || !bs->drv->supports_backing) {
3551 ret = -EINVAL;
3552 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003553 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003554 goto free_exit;
3555 }
3556
Peter Krempa6bff5972017-10-12 16:14:10 +02003557 if (!reference &&
3558 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003559 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003560 }
3561
Max Reitz6b6833c2019-02-01 20:29:15 +01003562 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003563 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003564 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003565 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003566 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003567 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003568 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003569 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003570
Max Reitz998c2012019-02-01 20:29:08 +01003571 if (implicit_backing) {
3572 bdrv_refresh_filename(backing_hd);
3573 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3574 backing_hd->filename);
3575 }
3576
Kevin Wolf5db15a52015-09-14 15:33:33 +02003577 /* Hook up the backing file link; drop our reference, bs owns the
3578 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003579 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003580 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003581 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003582 goto free_exit;
3583 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003584
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003585 qdict_del(parent_options, bdref_key);
3586
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003587free_exit:
3588 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003589 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003590 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003591}
3592
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003593static BlockDriverState *
3594bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003595 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003596 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003597{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003598 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003599 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003600 char *bdref_key_dot;
3601 const char *reference;
3602
Max Reitzbd86fb92020-05-13 13:05:13 +02003603 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003604
Max Reitzda557aa2013-12-20 19:28:11 +01003605 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3606 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3607 g_free(bdref_key_dot);
3608
Markus Armbruster129c7d12017-03-30 19:43:12 +02003609 /*
3610 * Caution: while qdict_get_try_str() is fine, getting non-string
3611 * types would require more care. When @options come from
3612 * -blockdev or blockdev_add, its members are typed according to
3613 * the QAPI schema, but when they come from -drive, they're all
3614 * QString.
3615 */
Max Reitzda557aa2013-12-20 19:28:11 +01003616 reference = qdict_get_try_str(options, bdref_key);
3617 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003618 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003619 error_setg(errp, "A block device must be specified for \"%s\"",
3620 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003621 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003622 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003623 goto done;
3624 }
3625
Max Reitz5b363932016-05-17 16:41:31 +02003626 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003627 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003628 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003629 goto done;
3630 }
3631
Max Reitzda557aa2013-12-20 19:28:11 +01003632done:
3633 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003634 return bs;
3635}
3636
3637/*
3638 * Opens a disk image whose options are given as BlockdevRef in another block
3639 * device's options.
3640 *
3641 * If allow_none is true, no image will be opened if filename is false and no
3642 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3643 *
3644 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3645 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3646 * itself, all options starting with "${bdref_key}." are considered part of the
3647 * BlockdevRef.
3648 *
3649 * The BlockdevRef will be removed from the options QDict.
3650 */
3651BdrvChild *bdrv_open_child(const char *filename,
3652 QDict *options, const char *bdref_key,
3653 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003654 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003655 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003656 bool allow_none, Error **errp)
3657{
3658 BlockDriverState *bs;
3659
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003660 GLOBAL_STATE_CODE();
3661
Max Reitzbd86fb92020-05-13 13:05:13 +02003662 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003663 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003664 if (bs == NULL) {
3665 return NULL;
3666 }
3667
Max Reitz258b7762020-05-13 13:05:15 +02003668 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3669 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003670}
3671
Max Reitzbd86fb92020-05-13 13:05:13 +02003672/*
3673 * TODO Future callers may need to specify parent/child_class in order for
3674 * option inheritance to work. Existing callers use it for the root node.
3675 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003676BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3677{
3678 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003679 QObject *obj = NULL;
3680 QDict *qdict = NULL;
3681 const char *reference = NULL;
3682 Visitor *v = NULL;
3683
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05003684 GLOBAL_STATE_CODE();
3685
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003686 if (ref->type == QTYPE_QSTRING) {
3687 reference = ref->u.reference;
3688 } else {
3689 BlockdevOptions *options = &ref->u.definition;
3690 assert(ref->type == QTYPE_QDICT);
3691
3692 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003693 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003694 visit_complete(v, &obj);
3695
Max Reitz7dc847e2018-02-24 16:40:29 +01003696 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003697 qdict_flatten(qdict);
3698
3699 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3700 * compatibility with other callers) rather than what we want as the
3701 * real defaults. Apply the defaults here instead. */
3702 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3703 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3704 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003705 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3706
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003707 }
3708
Max Reitz272c02e2020-05-13 13:05:17 +02003709 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003710 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003711 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003712 visit_free(v);
3713 return bs;
3714}
3715
Max Reitz66836182016-05-17 16:41:27 +02003716static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3717 int flags,
3718 QDict *snapshot_options,
3719 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003720{
3721 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003722 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003723 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003724 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003725 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003726 int ret;
3727
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05003728 GLOBAL_STATE_CODE();
3729
Kevin Wolfb9988752014-04-03 12:09:34 +02003730 /* if snapshot, we create a temporary backing file and open it
3731 instead of opening 'filename' directly */
3732
3733 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003734 total_size = bdrv_getlength(bs);
3735 if (total_size < 0) {
3736 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003737 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003738 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003739
3740 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003741 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003742 if (ret < 0) {
3743 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003744 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003745 }
3746
Max Reitzef810432014-12-02 18:32:42 +01003747 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003748 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003749 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003750 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003751 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003752 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003753 error_prepend(errp, "Could not create temporary overlay '%s': ",
3754 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003755 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003756 }
3757
Kevin Wolf73176be2016-03-07 13:02:15 +01003758 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003759 qdict_put_str(snapshot_options, "file.driver", "file");
3760 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3761 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003762
Max Reitz5b363932016-05-17 16:41:31 +02003763 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003764 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003765 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003766 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003767 }
3768
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003769 ret = bdrv_append(bs_snapshot, bs, errp);
3770 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003771 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003772 goto out;
3773 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003774
3775out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003776 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003777 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003778 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003779}
3780
Max Reitzda557aa2013-12-20 19:28:11 +01003781/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003782 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003783 *
3784 * options is a QDict of options to pass to the block drivers, or NULL for an
3785 * empty set of options. The reference to the QDict belongs to the block layer
3786 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003787 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003788 *
3789 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3790 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003791 *
3792 * The reference parameter may be used to specify an existing block device which
3793 * should be opened. If specified, neither options nor a filename may be given,
3794 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003795 */
Max Reitz5b363932016-05-17 16:41:31 +02003796static BlockDriverState *bdrv_open_inherit(const char *filename,
3797 const char *reference,
3798 QDict *options, int flags,
3799 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003800 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003801 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003802 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003803{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003804 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003805 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003806 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003807 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003808 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003809 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003810 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003811 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003812 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003813 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003814
Max Reitzbd86fb92020-05-13 13:05:13 +02003815 assert(!child_class || !flags);
3816 assert(!child_class == !parent);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05003817 GLOBAL_STATE_CODE();
Max Reitzf67503e2014-02-18 18:33:05 +01003818
Max Reitzddf56362014-02-18 18:33:06 +01003819 if (reference) {
3820 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003821 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003822
Max Reitzddf56362014-02-18 18:33:06 +01003823 if (filename || options_non_empty) {
3824 error_setg(errp, "Cannot reference an existing block device with "
3825 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003826 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003827 }
3828
3829 bs = bdrv_lookup_bs(reference, reference, errp);
3830 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003831 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003832 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003833
Max Reitzddf56362014-02-18 18:33:06 +01003834 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003835 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003836 }
3837
Max Reitz5b363932016-05-17 16:41:31 +02003838 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003839
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003840 /* NULL means an empty set of options */
3841 if (options == NULL) {
3842 options = qdict_new();
3843 }
3844
Kevin Wolf145f5982015-05-08 16:15:03 +02003845 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003846 parse_json_protocol(options, &filename, &local_err);
3847 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003848 goto fail;
3849 }
3850
Kevin Wolf145f5982015-05-08 16:15:03 +02003851 bs->explicit_options = qdict_clone_shallow(options);
3852
Max Reitzbd86fb92020-05-13 13:05:13 +02003853 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003854 bool parent_is_format;
3855
3856 if (parent->drv) {
3857 parent_is_format = parent->drv->is_format;
3858 } else {
3859 /*
3860 * parent->drv is not set yet because this node is opened for
3861 * (potential) format probing. That means that @parent is going
3862 * to be a format node.
3863 */
3864 parent_is_format = true;
3865 }
3866
Kevin Wolfbddcec32015-04-09 18:47:50 +02003867 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003868 child_class->inherit_options(child_role, parent_is_format,
3869 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003870 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003871 }
3872
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003873 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003874 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003875 goto fail;
3876 }
3877
Markus Armbruster129c7d12017-03-30 19:43:12 +02003878 /*
3879 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3880 * Caution: getting a boolean member of @options requires care.
3881 * When @options come from -blockdev or blockdev_add, members are
3882 * typed according to the QAPI schema, but when they come from
3883 * -drive, they're all QString.
3884 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003885 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3886 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3887 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3888 } else {
3889 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003890 }
3891
3892 if (flags & BDRV_O_SNAPSHOT) {
3893 snapshot_options = qdict_new();
3894 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3895 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003896 /* Let bdrv_backing_options() override "read-only" */
3897 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003898 bdrv_inherited_options(BDRV_CHILD_COW, true,
3899 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003900 }
3901
Kevin Wolf62392eb2015-04-24 16:38:02 +02003902 bs->open_flags = flags;
3903 bs->options = options;
3904 options = qdict_clone_shallow(options);
3905
Kevin Wolf76c591b2014-06-04 14:19:44 +02003906 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003907 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003908 drvname = qdict_get_try_str(options, "driver");
3909 if (drvname) {
3910 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003911 if (!drv) {
3912 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003913 goto fail;
3914 }
3915 }
3916
3917 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003918
Markus Armbruster129c7d12017-03-30 19:43:12 +02003919 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003920 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003921 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3922 (backing && *backing == '\0'))
3923 {
Max Reitz4f7be282018-02-24 16:40:33 +01003924 if (backing) {
3925 warn_report("Use of \"backing\": \"\" is deprecated; "
3926 "use \"backing\": null instead");
3927 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003928 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003929 qdict_del(bs->explicit_options, "backing");
3930 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003931 qdict_del(options, "backing");
3932 }
3933
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003934 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003935 * probing, the block drivers will do their own bdrv_open_child() for the
3936 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003937 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003938 BlockDriverState *file_bs;
3939
3940 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003941 &child_of_bds, BDRV_CHILD_IMAGE,
3942 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003943 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003944 goto fail;
3945 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003946 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003947 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3948 * looking at the header to guess the image format. This works even
3949 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003950 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003951 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003952 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003953 if (local_err) {
3954 goto fail;
3955 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003956
Eric Blake46f5ac22017-04-27 16:58:17 -05003957 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003958 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003959 }
3960
Kevin Wolf76c591b2014-06-04 14:19:44 +02003961 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003962 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003963 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003964 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003965 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003966 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003967 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003968 /*
3969 * This option update would logically belong in bdrv_fill_options(),
3970 * but we first need to open bs->file for the probing to work, while
3971 * opening bs->file already requires the (mostly) final set of options
3972 * so that cache mode etc. can be inherited.
3973 *
3974 * Adding the driver later is somewhat ugly, but it's not an option
3975 * that would ever be inherited, so it's correct. We just need to make
3976 * sure to update both bs->options (which has the full effective
3977 * options for bs) and options (which has file.* already removed).
3978 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003979 qdict_put_str(bs->options, "driver", drv->format_name);
3980 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003981 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003982 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003983 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003984 }
3985
Max Reitz53a29512015-03-19 14:53:16 -04003986 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3987 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3988 /* file must be NULL if a protocol BDS is about to be created
3989 * (the inverse results in an error message from bdrv_open_common()) */
3990 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3991
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003992 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003993 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003994 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003995 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003996 }
3997
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003998 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003999 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01004000 file = NULL;
4001 }
4002
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004003 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02004004 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01004005 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004006 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004007 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004008 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004009 }
4010
Alberto Garcia50196d72018-09-06 12:37:03 +03004011 /* Remove all children options and references
4012 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03004013 QLIST_FOREACH(child, &bs->children, next) {
4014 char *child_key_dot;
4015 child_key_dot = g_strdup_printf("%s.", child->name);
4016 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4017 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03004018 qdict_del(bs->explicit_options, child->name);
4019 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03004020 g_free(child_key_dot);
4021 }
4022
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004023 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01004024 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004025 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01004026 if (flags & BDRV_O_PROTOCOL) {
4027 error_setg(errp, "Block protocol '%s' doesn't support the option "
4028 "'%s'", drv->format_name, entry->key);
4029 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01004030 error_setg(errp,
4031 "Block format '%s' does not support the option '%s'",
4032 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01004033 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004034
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004035 goto close_and_fail;
4036 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004037
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01004038 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004039
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004040 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03004041 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004042
4043 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4044 * temporary snapshot afterwards. */
4045 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02004046 BlockDriverState *snapshot_bs;
4047 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4048 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01004049 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004050 if (local_err) {
4051 goto close_and_fail;
4052 }
Max Reitz5b363932016-05-17 16:41:31 +02004053 /* We are not going to return bs but the overlay on top of it
4054 * (snapshot_bs); thus, we have to drop the strong reference to bs
4055 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4056 * though, because the overlay still has a reference to it. */
4057 bdrv_unref(bs);
4058 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02004059 }
4060
Max Reitz5b363932016-05-17 16:41:31 +02004061 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004062
Kevin Wolf8bfea152014-04-11 19:16:36 +02004063fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01004064 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004065 qobject_unref(snapshot_options);
4066 qobject_unref(bs->explicit_options);
4067 qobject_unref(bs->options);
4068 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004069 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03004070 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02004071 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004072 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004073 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01004074
Kevin Wolfb6ad4912013-03-15 10:35:04 +01004075close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02004076 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004077 qobject_unref(snapshot_options);
4078 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004079 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02004080 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02004081}
4082
Max Reitz5b363932016-05-17 16:41:31 +02004083BlockDriverState *bdrv_open(const char *filename, const char *reference,
4084 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02004085{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004086 GLOBAL_STATE_CODE();
4087
Max Reitz5b363932016-05-17 16:41:31 +02004088 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02004089 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02004090}
4091
Alberto Garciafaf116b2019-03-12 18:48:49 +02004092/* Return true if the NULL-terminated @list contains @str */
4093static bool is_str_in_list(const char *str, const char *const *list)
4094{
4095 if (str && list) {
4096 int i;
4097 for (i = 0; list[i] != NULL; i++) {
4098 if (!strcmp(str, list[i])) {
4099 return true;
4100 }
4101 }
4102 }
4103 return false;
4104}
4105
4106/*
4107 * Check that every option set in @bs->options is also set in
4108 * @new_opts.
4109 *
4110 * Options listed in the common_options list and in
4111 * @bs->drv->mutable_opts are skipped.
4112 *
4113 * Return 0 on success, otherwise return -EINVAL and set @errp.
4114 */
4115static int bdrv_reset_options_allowed(BlockDriverState *bs,
4116 const QDict *new_opts, Error **errp)
4117{
4118 const QDictEntry *e;
4119 /* These options are common to all block drivers and are handled
4120 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4121 const char *const common_options[] = {
4122 "node-name", "discard", "cache.direct", "cache.no-flush",
4123 "read-only", "auto-read-only", "detect-zeroes", NULL
4124 };
4125
4126 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4127 if (!qdict_haskey(new_opts, e->key) &&
4128 !is_str_in_list(e->key, common_options) &&
4129 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4130 error_setg(errp, "Option '%s' cannot be reset "
4131 "to its default value", e->key);
4132 return -EINVAL;
4133 }
4134 }
4135
4136 return 0;
4137}
4138
Jeff Codye971aa12012-09-20 15:13:19 -04004139/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004140 * Returns true if @child can be reached recursively from @bs
4141 */
4142static bool bdrv_recurse_has_child(BlockDriverState *bs,
4143 BlockDriverState *child)
4144{
4145 BdrvChild *c;
4146
4147 if (bs == child) {
4148 return true;
4149 }
4150
4151 QLIST_FOREACH(c, &bs->children, next) {
4152 if (bdrv_recurse_has_child(c->bs, child)) {
4153 return true;
4154 }
4155 }
4156
4157 return false;
4158}
4159
4160/*
Jeff Codye971aa12012-09-20 15:13:19 -04004161 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4162 * reopen of multiple devices.
4163 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004164 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04004165 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4166 * be created and initialized. This newly created BlockReopenQueue should be
4167 * passed back in for subsequent calls that are intended to be of the same
4168 * atomic 'set'.
4169 *
4170 * bs is the BlockDriverState to add to the reopen queue.
4171 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004172 * options contains the changed options for the associated bs
4173 * (the BlockReopenQueue takes ownership)
4174 *
Jeff Codye971aa12012-09-20 15:13:19 -04004175 * flags contains the open flags for the associated bs
4176 *
4177 * returns a pointer to bs_queue, which is either the newly allocated
4178 * bs_queue, or the existing bs_queue being used.
4179 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004180 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004181 */
Kevin Wolf28518102015-05-08 17:07:31 +02004182static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4183 BlockDriverState *bs,
4184 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02004185 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02004186 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004187 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02004188 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004189 int parent_flags,
4190 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04004191{
4192 assert(bs != NULL);
4193
4194 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02004195 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004196 QDict *old_options, *explicit_options, *options_copy;
4197 int flags;
4198 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004199
Kevin Wolf1a63a902017-12-06 20:24:44 +01004200 /* Make sure that the caller remembered to use a drained section. This is
4201 * important to avoid graph changes between the recursive queuing here and
4202 * bdrv_reopen_multiple(). */
4203 assert(bs->quiesce_counter > 0);
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05004204 GLOBAL_STATE_CODE();
Kevin Wolf1a63a902017-12-06 20:24:44 +01004205
Jeff Codye971aa12012-09-20 15:13:19 -04004206 if (bs_queue == NULL) {
4207 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004208 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04004209 }
4210
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004211 if (!options) {
4212 options = qdict_new();
4213 }
4214
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004215 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004216 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004217 if (bs == bs_entry->state.bs) {
4218 break;
4219 }
4220 }
4221
Kevin Wolf28518102015-05-08 17:07:31 +02004222 /*
4223 * Precedence of options:
4224 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004225 * 2. Retained from explicitly set options of bs
4226 * 3. Inherited from parent node
4227 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004228 */
4229
Kevin Wolf145f5982015-05-08 16:15:03 +02004230 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004231 if (bs_entry || keep_old_opts) {
4232 old_options = qdict_clone_shallow(bs_entry ?
4233 bs_entry->state.explicit_options :
4234 bs->explicit_options);
4235 bdrv_join_options(bs, options, old_options);
4236 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004237 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004238
4239 explicit_options = qdict_clone_shallow(options);
4240
Kevin Wolf28518102015-05-08 17:07:31 +02004241 /* Inherit from parent node */
4242 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004243 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004244 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004245 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004246 } else {
4247 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004248 }
4249
Alberto Garcia077e8e22019-03-12 18:48:44 +02004250 if (keep_old_opts) {
4251 /* Old values are used for options that aren't set yet */
4252 old_options = qdict_clone_shallow(bs->options);
4253 bdrv_join_options(bs, options, old_options);
4254 qobject_unref(old_options);
4255 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004256
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004257 /* We have the final set of options so let's update the flags */
4258 options_copy = qdict_clone_shallow(options);
4259 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4260 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4261 update_flags_from_options(&flags, opts);
4262 qemu_opts_del(opts);
4263 qobject_unref(options_copy);
4264
Kevin Wolffd452022017-08-03 17:02:59 +02004265 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004266 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004267 if (flags & BDRV_O_RDWR) {
4268 flags |= BDRV_O_ALLOW_RDWR;
4269 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004270
Kevin Wolf1857c972017-09-14 14:53:46 +02004271 if (!bs_entry) {
4272 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004273 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004274 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004275 qobject_unref(bs_entry->state.options);
4276 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004277 }
4278
4279 bs_entry->state.bs = bs;
4280 bs_entry->state.options = options;
4281 bs_entry->state.explicit_options = explicit_options;
4282 bs_entry->state.flags = flags;
4283
Alberto Garcia85466322019-03-12 18:48:45 +02004284 /*
4285 * If keep_old_opts is false then it means that unspecified
4286 * options must be reset to their original value. We don't allow
4287 * resetting 'backing' but we need to know if the option is
4288 * missing in order to decide if we have to return an error.
4289 */
4290 if (!keep_old_opts) {
4291 bs_entry->state.backing_missing =
4292 !qdict_haskey(options, "backing") &&
4293 !qdict_haskey(options, "backing.driver");
4294 }
4295
Kevin Wolf67251a32015-04-09 18:54:04 +02004296 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004297 QDict *new_child_options = NULL;
4298 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004299
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004300 /* reopen can only change the options of block devices that were
4301 * implicitly created and inherited options. For other (referenced)
4302 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004303 if (child->bs->inherits_from != bs) {
4304 continue;
4305 }
4306
Alberto Garcia85466322019-03-12 18:48:45 +02004307 /* Check if the options contain a child reference */
4308 if (qdict_haskey(options, child->name)) {
4309 const char *childref = qdict_get_try_str(options, child->name);
4310 /*
4311 * The current child must not be reopened if the child
4312 * reference is null or points to a different node.
4313 */
4314 if (g_strcmp0(childref, child->bs->node_name)) {
4315 continue;
4316 }
4317 /*
4318 * If the child reference points to the current child then
4319 * reopen it with its existing set of options (note that
4320 * it can still inherit new options from the parent).
4321 */
4322 child_keep_old = true;
4323 } else {
4324 /* Extract child options ("child-name.*") */
4325 char *child_key_dot = g_strdup_printf("%s.", child->name);
4326 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4327 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4328 g_free(child_key_dot);
4329 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004330
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004331 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004332 child->klass, child->role, bs->drv->is_format,
4333 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004334 }
4335
Jeff Codye971aa12012-09-20 15:13:19 -04004336 return bs_queue;
4337}
4338
Kevin Wolf28518102015-05-08 17:07:31 +02004339BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4340 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004341 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004342{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004343 GLOBAL_STATE_CODE();
4344
Max Reitz3cdc69d2020-05-13 13:05:18 +02004345 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4346 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004347}
4348
Alberto Garciaab5b52282021-07-08 13:47:05 +02004349void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4350{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004351 GLOBAL_STATE_CODE();
Alberto Garciaab5b52282021-07-08 13:47:05 +02004352 if (bs_queue) {
4353 BlockReopenQueueEntry *bs_entry, *next;
4354 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4355 qobject_unref(bs_entry->state.explicit_options);
4356 qobject_unref(bs_entry->state.options);
4357 g_free(bs_entry);
4358 }
4359 g_free(bs_queue);
4360 }
4361}
4362
Jeff Codye971aa12012-09-20 15:13:19 -04004363/*
4364 * Reopen multiple BlockDriverStates atomically & transactionally.
4365 *
4366 * The queue passed in (bs_queue) must have been built up previous
4367 * via bdrv_reopen_queue().
4368 *
4369 * Reopens all BDS specified in the queue, with the appropriate
4370 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004371 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004372 * data cleaned up.
4373 *
4374 * If all devices prepare successfully, then the changes are committed
4375 * to all devices.
4376 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004377 * All affected nodes must be drained between bdrv_reopen_queue() and
4378 * bdrv_reopen_multiple().
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004379 *
4380 * To be called from the main thread, with all other AioContexts unlocked.
Jeff Codye971aa12012-09-20 15:13:19 -04004381 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004382int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004383{
4384 int ret = -1;
4385 BlockReopenQueueEntry *bs_entry, *next;
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004386 AioContext *ctx;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004387 Transaction *tran = tran_new();
4388 g_autoptr(GHashTable) found = NULL;
4389 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004390
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004391 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Jeff Codye971aa12012-09-20 15:13:19 -04004392 assert(bs_queue != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004393 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004394
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004395 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004396 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4397 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004398 ret = bdrv_flush(bs_entry->state.bs);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004399 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004400 if (ret < 0) {
4401 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004402 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004403 }
4404 }
4405
4406 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004407 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004408 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4409 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004410 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004411 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004412 if (ret < 0) {
4413 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004414 }
4415 bs_entry->prepared = true;
4416 }
4417
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004418 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004419 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004420 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004421
4422 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4423 if (state->old_backing_bs) {
4424 refresh_list = bdrv_topological_dfs(refresh_list, found,
4425 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004426 }
Alberto Garciaecd30d22021-06-10 15:05:36 +03004427 if (state->old_file_bs) {
4428 refresh_list = bdrv_topological_dfs(refresh_list, found,
4429 state->old_file_bs);
4430 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004431 }
4432
4433 /*
4434 * Note that file-posix driver rely on permission update done during reopen
4435 * (even if no permission changed), because it wants "new" permissions for
4436 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4437 * in raw_reopen_prepare() which is called with "old" permissions.
4438 */
4439 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4440 if (ret < 0) {
4441 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004442 }
4443
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004444 /*
4445 * If we reach this point, we have success and just need to apply the
4446 * changes.
4447 *
4448 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4449 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4450 * children are usually goes after parents in reopen-queue, so go from last
4451 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004452 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004453 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004454 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4455 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004456 bdrv_reopen_commit(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004457 aio_context_release(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004458 }
4459
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004460 tran_commit(tran);
4461
4462 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4463 BlockDriverState *bs = bs_entry->state.bs;
4464
4465 if (bs->drv->bdrv_reopen_commit_post) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004466 ctx = bdrv_get_aio_context(bs);
4467 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004468 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004469 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004470 }
4471 }
4472
Jeff Codye971aa12012-09-20 15:13:19 -04004473 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004474 goto cleanup;
4475
4476abort:
4477 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004478 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004479 if (bs_entry->prepared) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004480 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4481 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004482 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004483 aio_context_release(ctx);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004484 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004485 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004486
Jeff Codye971aa12012-09-20 15:13:19 -04004487cleanup:
Alberto Garciaab5b52282021-07-08 13:47:05 +02004488 bdrv_reopen_queue_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004489
Jeff Codye971aa12012-09-20 15:13:19 -04004490 return ret;
4491}
4492
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004493int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4494 Error **errp)
4495{
4496 AioContext *ctx = bdrv_get_aio_context(bs);
4497 BlockReopenQueue *queue;
4498 int ret;
4499
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004500 GLOBAL_STATE_CODE();
4501
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004502 bdrv_subtree_drained_begin(bs);
4503 if (ctx != qemu_get_aio_context()) {
4504 aio_context_release(ctx);
4505 }
4506
4507 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4508 ret = bdrv_reopen_multiple(queue, errp);
4509
4510 if (ctx != qemu_get_aio_context()) {
4511 aio_context_acquire(ctx);
4512 }
4513 bdrv_subtree_drained_end(bs);
4514
4515 return ret;
4516}
4517
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004518int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4519 Error **errp)
4520{
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004521 QDict *opts = qdict_new();
4522
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004523 GLOBAL_STATE_CODE();
4524
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004525 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4526
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004527 return bdrv_reopen(bs, opts, true, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004528}
4529
Jeff Codye971aa12012-09-20 15:13:19 -04004530/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004531 * Take a BDRVReopenState and check if the value of 'backing' in the
4532 * reopen_state->options QDict is valid or not.
4533 *
4534 * If 'backing' is missing from the QDict then return 0.
4535 *
4536 * If 'backing' contains the node name of the backing file of
4537 * reopen_state->bs then return 0.
4538 *
4539 * If 'backing' contains a different node name (or is null) then check
4540 * whether the current backing file can be replaced with the new one.
4541 * If that's the case then reopen_state->replace_backing_bs is set to
4542 * true and reopen_state->new_backing_bs contains a pointer to the new
4543 * backing BlockDriverState (or NULL).
4544 *
4545 * Return 0 on success, otherwise return < 0 and set @errp.
4546 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004547static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4548 bool is_backing, Transaction *tran,
4549 Error **errp)
Alberto Garciacb828c32019-03-12 18:48:47 +02004550{
4551 BlockDriverState *bs = reopen_state->bs;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004552 BlockDriverState *new_child_bs;
4553 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4554 child_bs(bs->file);
4555 const char *child_name = is_backing ? "backing" : "file";
Alberto Garciacb828c32019-03-12 18:48:47 +02004556 QObject *value;
4557 const char *str;
4558
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05004559 GLOBAL_STATE_CODE();
4560
Alberto Garciaecd30d22021-06-10 15:05:36 +03004561 value = qdict_get(reopen_state->options, child_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004562 if (value == NULL) {
4563 return 0;
4564 }
4565
4566 switch (qobject_type(value)) {
4567 case QTYPE_QNULL:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004568 assert(is_backing); /* The 'file' option does not allow a null value */
4569 new_child_bs = NULL;
Alberto Garciacb828c32019-03-12 18:48:47 +02004570 break;
4571 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004572 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciaecd30d22021-06-10 15:05:36 +03004573 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4574 if (new_child_bs == NULL) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004575 return -EINVAL;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004576 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4577 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4578 "cycle", str, child_name, bs->node_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004579 return -EINVAL;
4580 }
4581 break;
4582 default:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004583 /*
4584 * The options QDict has been flattened, so 'backing' and 'file'
4585 * do not allow any other data type here.
4586 */
Alberto Garciacb828c32019-03-12 18:48:47 +02004587 g_assert_not_reached();
4588 }
4589
Alberto Garciaecd30d22021-06-10 15:05:36 +03004590 if (old_child_bs == new_child_bs) {
4591 return 0;
4592 }
4593
4594 if (old_child_bs) {
4595 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004596 return 0;
4597 }
4598
Alberto Garciaecd30d22021-06-10 15:05:36 +03004599 if (old_child_bs->implicit) {
4600 error_setg(errp, "Cannot replace implicit %s child of %s",
4601 child_name, bs->node_name);
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004602 return -EPERM;
4603 }
4604 }
4605
Alberto Garciaecd30d22021-06-10 15:05:36 +03004606 if (bs->drv->is_filter && !old_child_bs) {
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004607 /*
4608 * Filters always have a file or a backing child, so we are trying to
4609 * change wrong child
4610 */
4611 error_setg(errp, "'%s' is a %s filter node that does not support a "
Alberto Garciaecd30d22021-06-10 15:05:36 +03004612 "%s child", bs->node_name, bs->drv->format_name, child_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004613 return -EINVAL;
4614 }
4615
Alberto Garciaecd30d22021-06-10 15:05:36 +03004616 if (is_backing) {
4617 reopen_state->old_backing_bs = old_child_bs;
4618 } else {
4619 reopen_state->old_file_bs = old_child_bs;
4620 }
4621
4622 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4623 tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004624}
4625
4626/*
Jeff Codye971aa12012-09-20 15:13:19 -04004627 * Prepares a BlockDriverState for reopen. All changes are staged in the
4628 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4629 * the block driver layer .bdrv_reopen_prepare()
4630 *
4631 * bs is the BlockDriverState to reopen
4632 * flags are the new open flags
4633 * queue is the reopen queue
4634 *
4635 * Returns 0 on success, non-zero on error. On error errp will be set
4636 * as well.
4637 *
4638 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4639 * It is the responsibility of the caller to then call the abort() or
4640 * commit() for any other BDS that have been left in a prepare() state
4641 *
4642 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004643static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004644 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +03004645 Transaction *change_child_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004646{
4647 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004648 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004649 Error *local_err = NULL;
4650 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004651 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004652 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004653 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004654 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004655 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004656
4657 assert(reopen_state != NULL);
4658 assert(reopen_state->bs->drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004659 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004660 drv = reopen_state->bs->drv;
4661
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004662 /* This function and each driver's bdrv_reopen_prepare() remove
4663 * entries from reopen_state->options as they are processed, so
4664 * we need to make a copy of the original QDict. */
4665 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4666
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004667 /* Process generic block layer options */
4668 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004669 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004670 ret = -EINVAL;
4671 goto error;
4672 }
4673
Alberto Garciae6d79c42018-11-12 16:00:47 +02004674 /* This was already called in bdrv_reopen_queue_child() so the flags
4675 * are up-to-date. This time we simply want to remove the options from
4676 * QemuOpts in order to indicate that they have been processed. */
4677 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004678 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004679 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004680
Alberto Garcia415bbca2018-10-03 13:23:13 +03004681 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004682 if (discard != NULL) {
4683 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4684 error_setg(errp, "Invalid discard option");
4685 ret = -EINVAL;
4686 goto error;
4687 }
4688 }
4689
Alberto Garcia543770b2018-09-06 12:37:09 +03004690 reopen_state->detect_zeroes =
4691 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4692 if (local_err) {
4693 error_propagate(errp, local_err);
4694 ret = -EINVAL;
4695 goto error;
4696 }
4697
Alberto Garcia57f9db92018-09-06 12:37:06 +03004698 /* All other options (including node-name and driver) must be unchanged.
4699 * Put them back into the QDict, so that they are checked at the end
4700 * of this function. */
4701 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004702
Jeff Cody3d8ce172017-04-07 16:55:30 -04004703 /* If we are to stay read-only, do not allow permission change
4704 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4705 * not set, or if the BDS still has copy_on_read enabled */
4706 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004707 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004708 if (local_err) {
4709 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004710 goto error;
4711 }
4712
Jeff Codye971aa12012-09-20 15:13:19 -04004713 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004714 /*
4715 * If a driver-specific option is missing, it means that we
4716 * should reset it to its default value.
4717 * But not all options allow that, so we need to check it first.
4718 */
4719 ret = bdrv_reset_options_allowed(reopen_state->bs,
4720 reopen_state->options, errp);
4721 if (ret) {
4722 goto error;
4723 }
4724
Jeff Codye971aa12012-09-20 15:13:19 -04004725 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4726 if (ret) {
4727 if (local_err != NULL) {
4728 error_propagate(errp, local_err);
4729 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004730 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004731 error_setg(errp, "failed while preparing to reopen image '%s'",
4732 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004733 }
4734 goto error;
4735 }
4736 } else {
4737 /* It is currently mandatory to have a bdrv_reopen_prepare()
4738 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004739 error_setg(errp, "Block format '%s' used by node '%s' "
4740 "does not support reopening files", drv->format_name,
4741 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004742 ret = -1;
4743 goto error;
4744 }
4745
Max Reitz9ad08c42018-11-16 17:45:24 +01004746 drv_prepared = true;
4747
Alberto Garciabacd9b82019-03-12 18:48:46 +02004748 /*
4749 * We must provide the 'backing' option if the BDS has a backing
4750 * file or if the image file has a backing file name as part of
4751 * its metadata. Otherwise the 'backing' option can be omitted.
4752 */
4753 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004754 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004755 error_setg(errp, "backing is missing for '%s'",
4756 reopen_state->bs->node_name);
4757 ret = -EINVAL;
4758 goto error;
4759 }
4760
Alberto Garciacb828c32019-03-12 18:48:47 +02004761 /*
4762 * Allow changing the 'backing' option. The new value can be
4763 * either a reference to an existing node (using its node name)
4764 * or NULL to simply detach the current backing file.
4765 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004766 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4767 change_child_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004768 if (ret < 0) {
4769 goto error;
4770 }
4771 qdict_del(reopen_state->options, "backing");
4772
Alberto Garciaecd30d22021-06-10 15:05:36 +03004773 /* Allow changing the 'file' option. In this case NULL is not allowed */
4774 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4775 change_child_tran, errp);
4776 if (ret < 0) {
4777 goto error;
4778 }
4779 qdict_del(reopen_state->options, "file");
4780
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004781 /* Options that are not handled are only okay if they are unchanged
4782 * compared to the old state. It is expected that some options are only
4783 * used for the initial open, but not reopen (e.g. filename) */
4784 if (qdict_size(reopen_state->options)) {
4785 const QDictEntry *entry = qdict_first(reopen_state->options);
4786
4787 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004788 QObject *new = entry->value;
4789 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004790
Alberto Garciadb905282018-09-06 12:37:05 +03004791 /* Allow child references (child_name=node_name) as long as they
4792 * point to the current child (i.e. everything stays the same). */
4793 if (qobject_type(new) == QTYPE_QSTRING) {
4794 BdrvChild *child;
4795 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4796 if (!strcmp(child->name, entry->key)) {
4797 break;
4798 }
4799 }
4800
4801 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004802 if (!strcmp(child->bs->node_name,
4803 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004804 continue; /* Found child with this name, skip option */
4805 }
4806 }
4807 }
4808
Max Reitz54fd1b02017-11-14 19:01:26 +01004809 /*
4810 * TODO: When using -drive to specify blockdev options, all values
4811 * will be strings; however, when using -blockdev, blockdev-add or
4812 * filenames using the json:{} pseudo-protocol, they will be
4813 * correctly typed.
4814 * In contrast, reopening options are (currently) always strings
4815 * (because you can only specify them through qemu-io; all other
4816 * callers do not specify any options).
4817 * Therefore, when using anything other than -drive to create a BDS,
4818 * this cannot detect non-string options as unchanged, because
4819 * qobject_is_equal() always returns false for objects of different
4820 * type. In the future, this should be remedied by correctly typing
4821 * all options. For now, this is not too big of an issue because
4822 * the user can simply omit options which cannot be changed anyway,
4823 * so they will stay unchanged.
4824 */
4825 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004826 error_setg(errp, "Cannot change the option '%s'", entry->key);
4827 ret = -EINVAL;
4828 goto error;
4829 }
4830 } while ((entry = qdict_next(reopen_state->options, entry)));
4831 }
4832
Jeff Codye971aa12012-09-20 15:13:19 -04004833 ret = 0;
4834
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004835 /* Restore the original reopen_state->options QDict */
4836 qobject_unref(reopen_state->options);
4837 reopen_state->options = qobject_ref(orig_reopen_opts);
4838
Jeff Codye971aa12012-09-20 15:13:19 -04004839error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004840 if (ret < 0 && drv_prepared) {
4841 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4842 * call drv->bdrv_reopen_abort() before signaling an error
4843 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4844 * when the respective bdrv_reopen_prepare() has failed) */
4845 if (drv->bdrv_reopen_abort) {
4846 drv->bdrv_reopen_abort(reopen_state);
4847 }
4848 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004849 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004850 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004851 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004852 return ret;
4853}
4854
4855/*
4856 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4857 * makes them final by swapping the staging BlockDriverState contents into
4858 * the active BlockDriverState contents.
4859 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004860static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004861{
4862 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004863 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004864 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004865
4866 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004867 bs = reopen_state->bs;
4868 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004869 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004870 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004871
4872 /* If there are any driver level actions to take */
4873 if (drv->bdrv_reopen_commit) {
4874 drv->bdrv_reopen_commit(reopen_state);
4875 }
4876
4877 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004878 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004879 qobject_unref(bs->options);
Alberto Garciaab5b52282021-07-08 13:47:05 +02004880 qobject_ref(reopen_state->explicit_options);
4881 qobject_ref(reopen_state->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004882
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004883 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004884 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004885 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004886 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004887
Alberto Garcia50196d72018-09-06 12:37:03 +03004888 /* Remove child references from bs->options and bs->explicit_options.
4889 * Child options were already removed in bdrv_reopen_queue_child() */
4890 QLIST_FOREACH(child, &bs->children, next) {
4891 qdict_del(bs->explicit_options, child->name);
4892 qdict_del(bs->options, child->name);
4893 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004894 /* backing is probably removed, so it's not handled by previous loop */
4895 qdict_del(bs->explicit_options, "backing");
4896 qdict_del(bs->options, "backing");
4897
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004898 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004899}
4900
4901/*
4902 * Abort the reopen, and delete and free the staged changes in
4903 * reopen_state
4904 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004905static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004906{
4907 BlockDriver *drv;
4908
4909 assert(reopen_state != NULL);
4910 drv = reopen_state->bs->drv;
4911 assert(drv != NULL);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05004912 GLOBAL_STATE_CODE();
Jeff Codye971aa12012-09-20 15:13:19 -04004913
4914 if (drv->bdrv_reopen_abort) {
4915 drv->bdrv_reopen_abort(reopen_state);
4916 }
4917}
4918
4919
Max Reitz64dff522016-01-29 16:36:10 +01004920static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004921{
Max Reitz33384422014-06-20 21:57:33 +02004922 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004923 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004924
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004925 GLOBAL_STATE_CODE();
Max Reitz30f55fb2016-05-17 16:41:32 +02004926 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004927
Paolo Bonzinifc272912015-12-23 11:48:24 +01004928 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004929 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004930 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004931
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004932 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004933 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004934 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004935 bs->drv->bdrv_close(bs);
4936 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004937 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004938 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004939
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004940 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004941 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004942 }
4943
Alberto Garciadd4118c2019-05-13 16:46:17 +03004944 bs->backing = NULL;
4945 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004946 g_free(bs->opaque);
4947 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004948 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004949 bs->backing_file[0] = '\0';
4950 bs->backing_format[0] = '\0';
4951 bs->total_sectors = 0;
4952 bs->encrypted = false;
4953 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004954 qobject_unref(bs->options);
4955 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004956 bs->options = NULL;
4957 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004958 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004959 bs->full_open_options = NULL;
Hanna Reitz0bc329f2021-08-12 10:41:44 +02004960 g_free(bs->block_status_cache);
4961 bs->block_status_cache = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004962
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004963 bdrv_release_named_dirty_bitmaps(bs);
4964 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4965
Max Reitz33384422014-06-20 21:57:33 +02004966 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4967 g_free(ban);
4968 }
4969 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004970 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004971
4972 /*
4973 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4974 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4975 * gets called.
4976 */
4977 if (bs->quiesce_counter) {
4978 bdrv_drain_all_end_quiesce(bs);
4979 }
bellardb3380822004-03-14 21:38:54 +00004980}
4981
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004982void bdrv_close_all(void)
4983{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004984 assert(job_next(NULL) == NULL);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05004985 GLOBAL_STATE_CODE();
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004986
Max Reitzca9bd242016-01-29 16:36:14 +01004987 /* Drop references from requests still in flight, such as canceled block
4988 * jobs whose AIO context has not been polled yet */
4989 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004990
Max Reitzca9bd242016-01-29 16:36:14 +01004991 blk_remove_all_bs();
4992 blockdev_close_all_bdrv_states();
4993
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004994 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004995}
4996
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004997static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004998{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004999 GQueue *queue;
5000 GHashTable *found;
5001 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005002
Max Reitzbd86fb92020-05-13 13:05:13 +02005003 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005004 return false;
5005 }
5006
Max Reitzec9f10f2018-06-13 20:18:15 +02005007 /* If the child @c belongs to the BDS @to, replacing the current
5008 * c->bs by @to would mean to create a loop.
5009 *
5010 * Such a case occurs when appending a BDS to a backing chain.
5011 * For instance, imagine the following chain:
5012 *
5013 * guest device -> node A -> further backing chain...
5014 *
5015 * Now we create a new BDS B which we want to put on top of this
5016 * chain, so we first attach A as its backing node:
5017 *
5018 * node B
5019 * |
5020 * v
5021 * guest device -> node A -> further backing chain...
5022 *
5023 * Finally we want to replace A by B. When doing that, we want to
5024 * replace all pointers to A by pointers to B -- except for the
5025 * pointer from B because (1) that would create a loop, and (2)
5026 * that pointer should simply stay intact:
5027 *
5028 * guest device -> node B
5029 * |
5030 * v
5031 * node A -> further backing chain...
5032 *
5033 * In general, when replacing a node A (c->bs) by a node B (@to),
5034 * if A is a child of B, that means we cannot replace A by B there
5035 * because that would create a loop. Silently detaching A from B
5036 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005037 * place there is the most sensible choice.
5038 *
5039 * We would also create a loop in any cases where @c is only
5040 * indirectly referenced by @to. Prevent this by returning false
5041 * if @c is found (by breadth-first search) anywhere in the whole
5042 * subtree of @to.
5043 */
5044
5045 ret = true;
5046 found = g_hash_table_new(NULL, NULL);
5047 g_hash_table_add(found, to);
5048 queue = g_queue_new();
5049 g_queue_push_tail(queue, to);
5050
5051 while (!g_queue_is_empty(queue)) {
5052 BlockDriverState *v = g_queue_pop_head(queue);
5053 BdrvChild *c2;
5054
5055 QLIST_FOREACH(c2, &v->children, next) {
5056 if (c2 == c) {
5057 ret = false;
5058 break;
5059 }
5060
5061 if (g_hash_table_contains(found, c2->bs)) {
5062 continue;
5063 }
5064
5065 g_queue_push_tail(queue, c2->bs);
5066 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005067 }
5068 }
5069
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03005070 g_queue_free(queue);
5071 g_hash_table_destroy(found);
5072
5073 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01005074}
5075
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005076typedef struct BdrvRemoveFilterOrCowChild {
5077 BdrvChild *child;
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005078 BlockDriverState *bs;
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005079 bool is_backing;
5080} BdrvRemoveFilterOrCowChild;
5081
5082static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
5083{
5084 BdrvRemoveFilterOrCowChild *s = opaque;
5085 BlockDriverState *parent_bs = s->child->opaque;
5086
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005087 if (s->is_backing) {
5088 parent_bs->backing = s->child;
5089 } else {
5090 parent_bs->file = s->child;
5091 }
5092
5093 /*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03005094 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005095 * because that function is transactionable and it registered own completion
5096 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
5097 * called automatically.
5098 */
5099}
5100
5101static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
5102{
5103 BdrvRemoveFilterOrCowChild *s = opaque;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005104 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005105 bdrv_child_free(s->child);
5106}
5107
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005108static void bdrv_remove_filter_or_cow_child_clean(void *opaque)
5109{
5110 BdrvRemoveFilterOrCowChild *s = opaque;
5111
5112 /* Drop the bs reference after the transaction is done */
5113 bdrv_unref(s->bs);
5114 g_free(s);
5115}
5116
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005117static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
5118 .abort = bdrv_remove_filter_or_cow_child_abort,
5119 .commit = bdrv_remove_filter_or_cow_child_commit,
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005120 .clean = bdrv_remove_filter_or_cow_child_clean,
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005121};
5122
5123/*
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005124 * A function to remove backing or file child of @bs.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03005125 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005126 */
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005127static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
5128 BdrvChild *child,
5129 Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005130{
Hanna Reitz562bda82021-11-15 15:54:02 +01005131 BdrvChild **childp;
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005132 BdrvRemoveFilterOrCowChild *s;
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005133
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005134 if (!child) {
5135 return;
5136 }
5137
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005138 /*
5139 * Keep a reference to @bs so @childp will stay valid throughout the
5140 * transaction (required by bdrv_replace_child_tran())
5141 */
5142 bdrv_ref(bs);
Hanna Reitz562bda82021-11-15 15:54:02 +01005143 if (child == bs->backing) {
5144 childp = &bs->backing;
5145 } else if (child == bs->file) {
5146 childp = &bs->file;
5147 } else {
5148 g_assert_not_reached();
5149 }
5150
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005151 if (child->bs) {
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005152 /*
5153 * Pass free_empty_child=false, we will free the child in
5154 * bdrv_remove_filter_or_cow_child_commit()
5155 */
5156 bdrv_replace_child_tran(childp, NULL, tran, false);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005157 }
5158
5159 s = g_new(BdrvRemoveFilterOrCowChild, 1);
5160 *s = (BdrvRemoveFilterOrCowChild) {
5161 .child = child,
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005162 .bs = bs,
Hanna Reitz562bda82021-11-15 15:54:02 +01005163 .is_backing = (childp == &bs->backing),
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005164 };
5165 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03005166}
5167
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03005168/*
5169 * A function to remove backing-chain child of @bs if exists: cow child for
5170 * format nodes (always .backing) and filter child for filters (may be .file or
5171 * .backing)
5172 */
5173static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
5174 Transaction *tran)
5175{
5176 bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
5177}
5178
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005179static int bdrv_replace_node_noperm(BlockDriverState *from,
5180 BlockDriverState *to,
5181 bool auto_skip, Transaction *tran,
5182 Error **errp)
5183{
5184 BdrvChild *c, *next;
5185
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005186 assert(to != NULL);
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005187 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005188
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005189 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5190 assert(c->bs == from);
5191 if (!should_update_child(c, to)) {
5192 if (auto_skip) {
5193 continue;
5194 }
5195 error_setg(errp, "Should not change '%s' link to '%s'",
5196 c->name, from->node_name);
5197 return -EINVAL;
5198 }
5199 if (c->frozen) {
5200 error_setg(errp, "Cannot change '%s' link to '%s'",
5201 c->name, from->node_name);
5202 return -EPERM;
5203 }
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005204
5205 /*
5206 * Passing a pointer to the local variable @c is fine here, because
5207 * @to is not NULL, and so &c will not be attached to the transaction.
5208 */
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005209 bdrv_replace_child_tran(&c, to, tran, true);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005210 }
5211
5212 return 0;
5213}
5214
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005215/*
5216 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5217 * if it creates a parent-child relation loop or if parent is block-job.
5218 *
5219 * With auto_skip=false the error is returned if from has a parent which should
5220 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005221 *
5222 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5223 * case backing link of the cow-parent of @to is removed.
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005224 *
5225 * @to must not be NULL.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005226 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005227static int bdrv_replace_node_common(BlockDriverState *from,
5228 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005229 bool auto_skip, bool detach_subchain,
5230 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005231{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005232 Transaction *tran = tran_new();
5233 g_autoptr(GHashTable) found = NULL;
5234 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04005235 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005236 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005237
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05005238 GLOBAL_STATE_CODE();
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005239 assert(to != NULL);
5240
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005241 if (detach_subchain) {
5242 assert(bdrv_chain_contains(from, to));
5243 assert(from != to);
5244 for (to_cow_parent = from;
5245 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5246 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5247 {
5248 ;
5249 }
5250 }
5251
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005252 /* Make sure that @from doesn't go away until we have successfully attached
5253 * all of its parents to @to. */
5254 bdrv_ref(from);
5255
Kevin Wolff871abd2019-05-21 19:00:25 +02005256 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01005257 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02005258 bdrv_drained_begin(from);
5259
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005260 /*
5261 * Do the replacement without permission update.
5262 * Replacement may influence the permissions, we should calculate new
5263 * permissions based on new graph. If we fail, we'll roll-back the
5264 * replacement.
5265 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03005266 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5267 if (ret < 0) {
5268 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005269 }
5270
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005271 if (detach_subchain) {
5272 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
5273 }
5274
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005275 found = g_hash_table_new(NULL, NULL);
5276
5277 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5278 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5279
5280 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005281 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005282 goto out;
5283 }
5284
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005285 ret = 0;
5286
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005287out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005288 tran_finalize(tran, ret);
5289
Kevin Wolff871abd2019-05-21 19:00:25 +02005290 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005291 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005292
5293 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005294}
5295
Hanna Reitz82b54cf2021-11-15 15:54:04 +01005296/**
5297 * Replace node @from by @to (where neither may be NULL).
5298 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005299int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5300 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005301{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005302 GLOBAL_STATE_CODE();
5303
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005304 return bdrv_replace_node_common(from, to, true, false, errp);
5305}
5306
5307int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5308{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005309 GLOBAL_STATE_CODE();
5310
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005311 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5312 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005313}
5314
Jeff Cody8802d1f2012-02-28 15:54:06 -05005315/*
5316 * Add new bs contents at the top of an image chain while the chain is
5317 * live, while keeping required fields on the top layer.
5318 *
5319 * This will modify the BlockDriverState fields, and swap contents
5320 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5321 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005322 * bs_new must not be attached to a BlockBackend and must not have backing
5323 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005324 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005325 * This function does not create any image files.
5326 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005327int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5328 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005329{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005330 int ret;
5331 Transaction *tran = tran_new();
5332
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005333 GLOBAL_STATE_CODE();
5334
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005335 assert(!bs_new->backing);
5336
5337 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5338 &child_of_bds, bdrv_backing_role(bs_new),
5339 &bs_new->backing, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005340 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005341 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005342 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005343
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005344 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005345 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005346 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005347 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005348
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005349 ret = bdrv_refresh_perms(bs_new, errp);
5350out:
5351 tran_finalize(tran, ret);
5352
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005353 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005354
5355 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005356}
5357
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005358/* Not for empty child */
5359int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5360 Error **errp)
5361{
5362 int ret;
5363 Transaction *tran = tran_new();
5364 g_autoptr(GHashTable) found = NULL;
5365 g_autoptr(GSList) refresh_list = NULL;
5366 BlockDriverState *old_bs = child->bs;
5367
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005368 GLOBAL_STATE_CODE();
5369
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005370 bdrv_ref(old_bs);
5371 bdrv_drained_begin(old_bs);
5372 bdrv_drained_begin(new_bs);
5373
Hanna Reitzb0a9f6f2021-11-15 15:54:05 +01005374 bdrv_replace_child_tran(&child, new_bs, tran, true);
5375 /* @new_bs must have been non-NULL, so @child must not have been freed */
5376 assert(child != NULL);
Vladimir Sementsov-Ogievskiybd8f4c42021-08-24 11:38:23 +03005377
5378 found = g_hash_table_new(NULL, NULL);
5379 refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5380 refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5381
5382 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5383
5384 tran_finalize(tran, ret);
5385
5386 bdrv_drained_end(old_bs);
5387 bdrv_drained_end(new_bs);
5388 bdrv_unref(old_bs);
5389
5390 return ret;
5391}
5392
Fam Zheng4f6fd342013-08-23 09:14:47 +08005393static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005394{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005395 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005396 assert(!bs->refcnt);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005397 GLOBAL_STATE_CODE();
Markus Armbruster18846de2010-06-29 16:58:30 +02005398
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005399 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005400 if (bs->node_name[0] != '\0') {
5401 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5402 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005403 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5404
Anton Kuchin30c321f2019-05-07 11:12:56 +03005405 bdrv_close(bs);
5406
Anthony Liguori7267c092011-08-20 22:09:37 -05005407 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005408}
5409
Vladimir Sementsov-Ogievskiy96796fa2021-09-20 14:55:36 +03005410
5411/*
5412 * Replace @bs by newly created block node.
5413 *
5414 * @options is a QDict of options to pass to the block drivers, or NULL for an
5415 * empty set of options. The reference to the QDict belongs to the block layer
5416 * after the call (even on failure), so if the caller intends to reuse the
5417 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5418 */
5419BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005420 int flags, Error **errp)
5421{
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005422 ERRP_GUARD();
5423 int ret;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005424 BlockDriverState *new_node_bs = NULL;
5425 const char *drvname, *node_name;
5426 BlockDriver *drv;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005427
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005428 drvname = qdict_get_try_str(options, "driver");
5429 if (!drvname) {
5430 error_setg(errp, "driver is not specified");
5431 goto fail;
5432 }
5433
5434 drv = bdrv_find_format(drvname);
5435 if (!drv) {
5436 error_setg(errp, "Unknown driver: '%s'", drvname);
5437 goto fail;
5438 }
5439
5440 node_name = qdict_get_try_str(options, "node-name");
5441
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005442 GLOBAL_STATE_CODE();
5443
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005444 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5445 errp);
5446 options = NULL; /* bdrv_new_open_driver() eats options */
5447 if (!new_node_bs) {
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005448 error_prepend(errp, "Could not create node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005449 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005450 }
5451
5452 bdrv_drained_begin(bs);
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005453 ret = bdrv_replace_node(bs, new_node_bs, errp);
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005454 bdrv_drained_end(bs);
5455
Vladimir Sementsov-Ogievskiyf053b7e2021-09-20 14:55:35 +03005456 if (ret < 0) {
5457 error_prepend(errp, "Could not replace node: ");
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005458 goto fail;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005459 }
5460
5461 return new_node_bs;
Vladimir Sementsov-Ogievskiyb11c8732021-09-20 14:55:37 +03005462
5463fail:
5464 qobject_unref(options);
5465 bdrv_unref(new_node_bs);
5466 return NULL;
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005467}
5468
aliguorie97fc192009-04-21 23:11:50 +00005469/*
5470 * Run consistency checks on an image
5471 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005472 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005473 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005474 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005475 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005476int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5477 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005478{
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05005479 IO_CODE();
Max Reitz908bcd52014-08-07 22:47:55 +02005480 if (bs->drv == NULL) {
5481 return -ENOMEDIUM;
5482 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005483 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005484 return -ENOTSUP;
5485 }
5486
Kevin Wolfe076f332010-06-29 11:43:13 +02005487 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005488 return bs->drv->bdrv_co_check(bs, res, fix);
5489}
5490
Kevin Wolf756e6732010-01-12 12:55:17 +01005491/*
5492 * Return values:
5493 * 0 - success
5494 * -EINVAL - backing format specified, but no file
5495 * -ENOSPC - can't update the backing file because no space is left in the
5496 * image file header
5497 * -ENOTSUP - format driver doesn't support changing the backing file
5498 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005499int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
Eric Blake497a30d2021-05-03 14:36:00 -07005500 const char *backing_fmt, bool require)
Kevin Wolf756e6732010-01-12 12:55:17 +01005501{
5502 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005503 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005504
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005505 GLOBAL_STATE_CODE();
5506
Max Reitzd470ad42017-11-10 21:31:09 +01005507 if (!drv) {
5508 return -ENOMEDIUM;
5509 }
5510
Paolo Bonzini5f377792012-04-12 14:01:01 +02005511 /* Backing file format doesn't make sense without a backing file */
5512 if (backing_fmt && !backing_file) {
5513 return -EINVAL;
5514 }
5515
Eric Blake497a30d2021-05-03 14:36:00 -07005516 if (require && backing_file && !backing_fmt) {
5517 return -EINVAL;
Eric Blakee54ee1b2020-07-06 15:39:53 -05005518 }
5519
Kevin Wolf756e6732010-01-12 12:55:17 +01005520 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005521 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005522 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005523 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005524 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005525
5526 if (ret == 0) {
5527 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5528 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005529 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5530 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005531 }
5532 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005533}
5534
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005535/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005536 * Finds the first non-filter node above bs in the chain between
5537 * active and bs. The returned node is either an immediate parent of
5538 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005539 *
5540 * Returns NULL if bs is not found in active's image chain,
5541 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005542 *
5543 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005544 */
5545BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5546 BlockDriverState *bs)
5547{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005548
5549 GLOBAL_STATE_CODE();
5550
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005551 bs = bdrv_skip_filters(bs);
5552 active = bdrv_skip_filters(active);
5553
5554 while (active) {
5555 BlockDriverState *next = bdrv_backing_chain_next(active);
5556 if (bs == next) {
5557 return active;
5558 }
5559 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005560 }
5561
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005562 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005563}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005564
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005565/* Given a BDS, searches for the base layer. */
5566BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5567{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005568 GLOBAL_STATE_CODE();
5569
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005570 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005571}
5572
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005573/*
Max Reitz7b99a262019-06-12 16:07:11 +02005574 * Return true if at least one of the COW (backing) and filter links
5575 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005576 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005577 */
5578bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5579 Error **errp)
5580{
5581 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005582 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005583
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005584 GLOBAL_STATE_CODE();
5585
Max Reitz7b99a262019-06-12 16:07:11 +02005586 for (i = bs; i != base; i = child_bs(child)) {
5587 child = bdrv_filter_or_cow_child(i);
5588
5589 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005590 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005591 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005592 return true;
5593 }
5594 }
5595
5596 return false;
5597}
5598
5599/*
Max Reitz7b99a262019-06-12 16:07:11 +02005600 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005601 * If any of the links is already frozen the operation is aborted and
5602 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005603 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005604 * Returns 0 on success. On failure returns < 0 and sets @errp.
5605 */
5606int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5607 Error **errp)
5608{
5609 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005610 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005611
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005612 GLOBAL_STATE_CODE();
5613
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005614 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5615 return -EPERM;
5616 }
5617
Max Reitz7b99a262019-06-12 16:07:11 +02005618 for (i = bs; i != base; i = child_bs(child)) {
5619 child = bdrv_filter_or_cow_child(i);
5620 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005621 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005622 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005623 return -EPERM;
5624 }
5625 }
5626
Max Reitz7b99a262019-06-12 16:07:11 +02005627 for (i = bs; i != base; i = child_bs(child)) {
5628 child = bdrv_filter_or_cow_child(i);
5629 if (child) {
5630 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005631 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005632 }
5633
5634 return 0;
5635}
5636
5637/*
Max Reitz7b99a262019-06-12 16:07:11 +02005638 * Unfreeze all COW (backing) and filter links between @bs and @base.
5639 * The caller must ensure that all links are frozen before using this
5640 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005641 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005642 */
5643void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5644{
5645 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005646 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005647
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005648 GLOBAL_STATE_CODE();
5649
Max Reitz7b99a262019-06-12 16:07:11 +02005650 for (i = bs; i != base; i = child_bs(child)) {
5651 child = bdrv_filter_or_cow_child(i);
5652 if (child) {
5653 assert(child->frozen);
5654 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005655 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005656 }
5657}
5658
5659/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005660 * Drops images above 'base' up to and including 'top', and sets the image
5661 * above 'top' to have base as its backing file.
5662 *
5663 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5664 * information in 'bs' can be properly updated.
5665 *
5666 * E.g., this will convert the following chain:
5667 * bottom <- base <- intermediate <- top <- active
5668 *
5669 * to
5670 *
5671 * bottom <- base <- active
5672 *
5673 * It is allowed for bottom==base, in which case it converts:
5674 *
5675 * base <- intermediate <- top <- active
5676 *
5677 * to
5678 *
5679 * base <- active
5680 *
Jeff Cody54e26902014-06-25 15:40:10 -04005681 * If backing_file_str is non-NULL, it will be used when modifying top's
5682 * overlay image metadata.
5683 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005684 * Error conditions:
5685 * if active == top, that is considered an error
5686 *
5687 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005688int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5689 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005690{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005691 BlockDriverState *explicit_top = top;
5692 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005693 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005694 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005695 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005696 g_autoptr(GSList) updated_children = NULL;
5697 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005698
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005699 GLOBAL_STATE_CODE();
5700
Kevin Wolf6858eba2017-06-29 19:32:21 +02005701 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005702 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005703
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005704 if (!top->drv || !base->drv) {
5705 goto exit;
5706 }
5707
Kevin Wolf5db15a52015-09-14 15:33:33 +02005708 /* Make sure that base is in the backing chain of top */
5709 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005710 goto exit;
5711 }
5712
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005713 /* If 'base' recursively inherits from 'top' then we should set
5714 * base->inherits_from to top->inherits_from after 'top' and all
5715 * other intermediate nodes have been dropped.
5716 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5717 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005718 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005719 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5720
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005721 /* success - we can delete the intermediate states, and link top->base */
Max Reitzf30c66b2019-02-01 20:29:05 +01005722 if (!backing_file_str) {
5723 bdrv_refresh_filename(base);
5724 backing_file_str = base->filename;
5725 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005726
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005727 QLIST_FOREACH(c, &top->parents, next_parent) {
5728 updated_children = g_slist_prepend(updated_children, c);
5729 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005730
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005731 /*
5732 * It seems correct to pass detach_subchain=true here, but it triggers
5733 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5734 * another drained section, which modify the graph (for example, removing
5735 * the child, which we keep in updated_children list). So, it's a TODO.
5736 *
5737 * Note, bug triggered if pass detach_subchain=true here and run
5738 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5739 * That's a FIXME.
5740 */
5741 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005742 if (local_err) {
5743 error_report_err(local_err);
5744 goto exit;
5745 }
5746
5747 for (p = updated_children; p; p = p->next) {
5748 c = p->data;
5749
Max Reitzbd86fb92020-05-13 13:05:13 +02005750 if (c->klass->update_filename) {
5751 ret = c->klass->update_filename(c, base, backing_file_str,
5752 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005753 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005754 /*
5755 * TODO: Actually, we want to rollback all previous iterations
5756 * of this loop, and (which is almost impossible) previous
5757 * bdrv_replace_node()...
5758 *
5759 * Note, that c->klass->update_filename may lead to permission
5760 * update, so it's a bad idea to call it inside permission
5761 * update transaction of bdrv_replace_node.
5762 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005763 error_report_err(local_err);
5764 goto exit;
5765 }
5766 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005767 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005768
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005769 if (update_inherits_from) {
5770 base->inherits_from = explicit_top->inherits_from;
5771 }
5772
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005773 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005774exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005775 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005776 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005777 return ret;
5778}
5779
bellard83f64092006-08-01 16:21:11 +00005780/**
Max Reitz081e4652019-06-12 18:14:13 +02005781 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5782 * sums the size of all data-bearing children. (This excludes backing
5783 * children.)
5784 */
5785static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5786{
5787 BdrvChild *child;
5788 int64_t child_size, sum = 0;
5789
5790 QLIST_FOREACH(child, &bs->children, next) {
5791 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5792 BDRV_CHILD_FILTERED))
5793 {
5794 child_size = bdrv_get_allocated_file_size(child->bs);
5795 if (child_size < 0) {
5796 return child_size;
5797 }
5798 sum += child_size;
5799 }
5800 }
5801
5802 return sum;
5803}
5804
5805/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005806 * Length of a allocated file in bytes. Sparse files are counted by actual
5807 * allocated space. Return < 0 if error or unknown.
5808 */
5809int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5810{
5811 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005812 IO_CODE();
5813
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005814 if (!drv) {
5815 return -ENOMEDIUM;
5816 }
5817 if (drv->bdrv_get_allocated_file_size) {
5818 return drv->bdrv_get_allocated_file_size(bs);
5819 }
Max Reitz081e4652019-06-12 18:14:13 +02005820
5821 if (drv->bdrv_file_open) {
5822 /*
5823 * Protocol drivers default to -ENOTSUP (most of their data is
5824 * not stored in any of their children (if they even have any),
5825 * so there is no generic way to figure it out).
5826 */
5827 return -ENOTSUP;
5828 } else if (drv->is_filter) {
5829 /* Filter drivers default to the size of their filtered child */
5830 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5831 } else {
5832 /* Other drivers default to summing their children's sizes */
5833 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005834 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005835}
5836
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005837/*
5838 * bdrv_measure:
5839 * @drv: Format driver
5840 * @opts: Creation options for new image
5841 * @in_bs: Existing image containing data for new image (may be NULL)
5842 * @errp: Error object
5843 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5844 * or NULL on error
5845 *
5846 * Calculate file size required to create a new image.
5847 *
5848 * If @in_bs is given then space for allocated clusters and zero clusters
5849 * from that image are included in the calculation. If @opts contains a
5850 * backing file that is shared by @in_bs then backing clusters may be omitted
5851 * from the calculation.
5852 *
5853 * If @in_bs is NULL then the calculation includes no allocated clusters
5854 * unless a preallocation option is given in @opts.
5855 *
5856 * Note that @in_bs may use a different BlockDriver from @drv.
5857 *
5858 * If an error occurs the @errp pointer is set.
5859 */
5860BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5861 BlockDriverState *in_bs, Error **errp)
5862{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005863 IO_CODE();
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005864 if (!drv->bdrv_measure) {
5865 error_setg(errp, "Block driver '%s' does not support size measurement",
5866 drv->format_name);
5867 return NULL;
5868 }
5869
5870 return drv->bdrv_measure(opts, in_bs, errp);
5871}
5872
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005873/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005874 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005875 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005876int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005877{
5878 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005879 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005880
bellard83f64092006-08-01 16:21:11 +00005881 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005882 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005883
Kevin Wolfb94a2612013-10-29 12:18:58 +01005884 if (drv->has_variable_length) {
5885 int ret = refresh_total_sectors(bs, bs->total_sectors);
5886 if (ret < 0) {
5887 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005888 }
bellard83f64092006-08-01 16:21:11 +00005889 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005890 return bs->total_sectors;
5891}
5892
5893/**
5894 * Return length in bytes on success, -errno on error.
5895 * The length is always a multiple of BDRV_SECTOR_SIZE.
5896 */
5897int64_t bdrv_getlength(BlockDriverState *bs)
5898{
5899 int64_t ret = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005900 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005901
Eric Blake122860b2020-11-05 09:51:22 -06005902 if (ret < 0) {
5903 return ret;
5904 }
5905 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5906 return -EFBIG;
5907 }
5908 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005909}
5910
bellard19cb3732006-08-19 11:45:59 +00005911/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005912void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005913{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005914 int64_t nb_sectors = bdrv_nb_sectors(bs);
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005915 IO_CODE();
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005916
5917 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005918}
bellardcf989512004-02-16 21:56:36 +00005919
Eric Blake54115412016-06-23 16:37:26 -06005920bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005921{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005922 IO_CODE();
ths985a03b2007-12-24 16:10:43 +00005923 return bs->sg;
5924}
5925
Max Reitzae23f782019-06-12 22:57:15 +02005926/**
5927 * Return whether the given node supports compressed writes.
5928 */
5929bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5930{
5931 BlockDriverState *filtered;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005932 IO_CODE();
Max Reitzae23f782019-06-12 22:57:15 +02005933
5934 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5935 return false;
5936 }
5937
5938 filtered = bdrv_filter_bs(bs);
5939 if (filtered) {
5940 /*
5941 * Filters can only forward compressed writes, so we have to
5942 * check the child.
5943 */
5944 return bdrv_supports_compressed_writes(filtered);
5945 }
5946
5947 return true;
5948}
5949
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005950const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005951{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05005952 IO_CODE();
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005953 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005954}
5955
Stefan Hajnocziada42402014-08-27 12:08:55 +01005956static int qsort_strcmp(const void *a, const void *b)
5957{
Max Reitzceff5bd2016-10-12 22:49:05 +02005958 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005959}
5960
ths5fafdf22007-09-16 21:08:06 +00005961void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005962 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005963{
5964 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005965 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005966 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005967 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005968
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05005969 GLOBAL_STATE_CODE();
5970
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005971 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005972 if (drv->format_name) {
5973 bool found = false;
5974 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005975
5976 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5977 continue;
5978 }
5979
Jeff Codye855e4f2014-04-28 18:29:54 -04005980 while (formats && i && !found) {
5981 found = !strcmp(formats[--i], drv->format_name);
5982 }
5983
5984 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005985 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005986 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005987 }
5988 }
bellardea2384d2004-08-01 21:59:26 +00005989 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005990
Max Reitzeb0df692016-10-12 22:49:06 +02005991 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5992 const char *format_name = block_driver_modules[i].format_name;
5993
5994 if (format_name) {
5995 bool found = false;
5996 int j = count;
5997
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005998 if (use_bdrv_whitelist &&
5999 !bdrv_format_is_whitelisted(format_name, read_only)) {
6000 continue;
6001 }
6002
Max Reitzeb0df692016-10-12 22:49:06 +02006003 while (formats && j && !found) {
6004 found = !strcmp(formats[--j], format_name);
6005 }
6006
6007 if (!found) {
6008 formats = g_renew(const char *, formats, count + 1);
6009 formats[count++] = format_name;
6010 }
6011 }
6012 }
6013
Stefan Hajnocziada42402014-08-27 12:08:55 +01006014 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
6015
6016 for (i = 0; i < count; i++) {
6017 it(opaque, formats[i]);
6018 }
6019
Jeff Codye855e4f2014-04-28 18:29:54 -04006020 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00006021}
6022
Benoît Canetdc364f42014-01-23 21:31:32 +01006023/* This function is to find a node in the bs graph */
6024BlockDriverState *bdrv_find_node(const char *node_name)
6025{
6026 BlockDriverState *bs;
6027
6028 assert(node_name);
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006029 GLOBAL_STATE_CODE();
Benoît Canetdc364f42014-01-23 21:31:32 +01006030
6031 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6032 if (!strcmp(node_name, bs->node_name)) {
6033 return bs;
6034 }
6035 }
6036 return NULL;
6037}
6038
Benoît Canetc13163f2014-01-23 21:31:34 +01006039/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01006040BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6041 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01006042{
Eric Blake9812e712020-10-27 00:05:47 -05006043 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01006044 BlockDriverState *bs;
6045
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006046 GLOBAL_STATE_CODE();
6047
Benoît Canetc13163f2014-01-23 21:31:34 +01006048 list = NULL;
6049 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01006050 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03006051 if (!info) {
6052 qapi_free_BlockDeviceInfoList(list);
6053 return NULL;
6054 }
Eric Blake9812e712020-10-27 00:05:47 -05006055 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01006056 }
6057
6058 return list;
6059}
6060
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006061typedef struct XDbgBlockGraphConstructor {
6062 XDbgBlockGraph *graph;
6063 GHashTable *graph_nodes;
6064} XDbgBlockGraphConstructor;
6065
6066static XDbgBlockGraphConstructor *xdbg_graph_new(void)
6067{
6068 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
6069
6070 gr->graph = g_new0(XDbgBlockGraph, 1);
6071 gr->graph_nodes = g_hash_table_new(NULL, NULL);
6072
6073 return gr;
6074}
6075
6076static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
6077{
6078 XDbgBlockGraph *graph = gr->graph;
6079
6080 g_hash_table_destroy(gr->graph_nodes);
6081 g_free(gr);
6082
6083 return graph;
6084}
6085
6086static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
6087{
6088 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
6089
6090 if (ret != 0) {
6091 return ret;
6092 }
6093
6094 /*
6095 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6096 * answer of g_hash_table_lookup.
6097 */
6098 ret = g_hash_table_size(gr->graph_nodes) + 1;
6099 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6100
6101 return ret;
6102}
6103
6104static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6105 XDbgBlockGraphNodeType type, const char *name)
6106{
6107 XDbgBlockGraphNode *n;
6108
6109 n = g_new0(XDbgBlockGraphNode, 1);
6110
6111 n->id = xdbg_graph_node_num(gr, node);
6112 n->type = type;
6113 n->name = g_strdup(name);
6114
Eric Blake9812e712020-10-27 00:05:47 -05006115 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006116}
6117
6118static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6119 const BdrvChild *child)
6120{
Max Reitzcdb1cec2019-11-08 13:34:52 +01006121 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006122 XDbgBlockGraphEdge *edge;
Emanuele Giuseppe Esposito862fded2022-03-03 10:15:55 -05006123 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006124
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006125 edge = g_new0(XDbgBlockGraphEdge, 1);
6126
6127 edge->parent = xdbg_graph_node_num(gr, parent);
6128 edge->child = xdbg_graph_node_num(gr, child->bs);
6129 edge->name = g_strdup(child->name);
6130
Max Reitzcdb1cec2019-11-08 13:34:52 +01006131 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6132 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6133
6134 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006135 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006136 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01006137 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05006138 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006139 }
6140 }
6141
Eric Blake9812e712020-10-27 00:05:47 -05006142 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006143}
6144
6145
6146XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6147{
6148 BlockBackend *blk;
6149 BlockJob *job;
6150 BlockDriverState *bs;
6151 BdrvChild *child;
6152 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6153
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006154 GLOBAL_STATE_CODE();
6155
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03006156 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6157 char *allocated_name = NULL;
6158 const char *name = blk_name(blk);
6159
6160 if (!*name) {
6161 name = allocated_name = blk_get_attached_dev_id(blk);
6162 }
6163 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6164 name);
6165 g_free(allocated_name);
6166 if (blk_root(blk)) {
6167 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6168 }
6169 }
6170
6171 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
6172 GSList *el;
6173
6174 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6175 job->job.id);
6176 for (el = job->nodes; el; el = el->next) {
6177 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6178 }
6179 }
6180
6181 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6182 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6183 bs->node_name);
6184 QLIST_FOREACH(child, &bs->children, next) {
6185 xdbg_graph_add_edge(gr, bs, child);
6186 }
6187 }
6188
6189 return xdbg_graph_finalize(gr);
6190}
6191
Benoît Canet12d3ba82014-01-23 21:31:35 +01006192BlockDriverState *bdrv_lookup_bs(const char *device,
6193 const char *node_name,
6194 Error **errp)
6195{
Markus Armbruster7f06d472014-10-07 13:59:12 +02006196 BlockBackend *blk;
6197 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006198
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006199 GLOBAL_STATE_CODE();
6200
Benoît Canet12d3ba82014-01-23 21:31:35 +01006201 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02006202 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006203
Markus Armbruster7f06d472014-10-07 13:59:12 +02006204 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006205 bs = blk_bs(blk);
6206 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02006207 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02006208 }
6209
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02006210 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006211 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006212 }
6213
Benoît Canetdd67fa52014-02-12 17:15:06 +01006214 if (node_name) {
6215 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01006216
Benoît Canetdd67fa52014-02-12 17:15:06 +01006217 if (bs) {
6218 return bs;
6219 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01006220 }
6221
Connor Kuehl785ec4b2021-03-05 09:19:28 -06006222 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01006223 device ? device : "",
6224 node_name ? node_name : "");
6225 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01006226}
6227
Jeff Cody5a6684d2014-06-25 15:40:09 -04006228/* If 'base' is in the same chain as 'top', return true. Otherwise,
6229 * return false. If either argument is NULL, return false. */
6230bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6231{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006232
6233 GLOBAL_STATE_CODE();
6234
Jeff Cody5a6684d2014-06-25 15:40:09 -04006235 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006236 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04006237 }
6238
6239 return top != NULL;
6240}
6241
Fam Zheng04df7652014-10-31 11:32:54 +08006242BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6243{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006244 GLOBAL_STATE_CODE();
Fam Zheng04df7652014-10-31 11:32:54 +08006245 if (!bs) {
6246 return QTAILQ_FIRST(&graph_bdrv_states);
6247 }
6248 return QTAILQ_NEXT(bs, node_list);
6249}
6250
Kevin Wolf0f122642018-03-28 18:29:18 +02006251BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6252{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006253 GLOBAL_STATE_CODE();
Kevin Wolf0f122642018-03-28 18:29:18 +02006254 if (!bs) {
6255 return QTAILQ_FIRST(&all_bdrv_states);
6256 }
6257 return QTAILQ_NEXT(bs, bs_list);
6258}
6259
Fam Zheng20a9e772014-10-31 11:32:55 +08006260const char *bdrv_get_node_name(const BlockDriverState *bs)
6261{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006262 IO_CODE();
Fam Zheng20a9e772014-10-31 11:32:55 +08006263 return bs->node_name;
6264}
6265
Kevin Wolf1f0c4612016-03-22 18:38:44 +01006266const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006267{
6268 BdrvChild *c;
6269 const char *name;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05006270 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006271
6272 /* If multiple parents have a name, just pick the first one. */
6273 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006274 if (c->klass->get_name) {
6275 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006276 if (name && *name) {
6277 return name;
6278 }
6279 }
6280 }
6281
6282 return NULL;
6283}
6284
Markus Armbruster7f06d472014-10-07 13:59:12 +02006285/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02006286const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00006287{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006288 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006289 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00006290}
6291
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006292/* This can be used to identify nodes that might not have a device
6293 * name associated. Since node and device names live in the same
6294 * namespace, the result is unambiguous. The exception is if both are
6295 * absent, then this returns an empty (non-null) string. */
6296const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6297{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006298 IO_CODE();
Kevin Wolf4c265bf2016-02-26 10:22:16 +01006299 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03006300}
6301
Markus Armbrusterc8433282012-06-05 16:49:24 +02006302int bdrv_get_flags(BlockDriverState *bs)
6303{
Hanna Reitz15aee7a2022-04-27 13:40:54 +02006304 IO_CODE();
Markus Armbrusterc8433282012-06-05 16:49:24 +02006305 return bs->open_flags;
6306}
6307
Peter Lieven3ac21622013-06-28 12:47:42 +02006308int bdrv_has_zero_init_1(BlockDriverState *bs)
6309{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006310 GLOBAL_STATE_CODE();
Peter Lieven3ac21622013-06-28 12:47:42 +02006311 return 1;
6312}
6313
Kevin Wolff2feebb2010-04-14 17:30:35 +02006314int bdrv_has_zero_init(BlockDriverState *bs)
6315{
Max Reitz93393e62019-06-12 17:03:38 +02006316 BlockDriverState *filtered;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006317 GLOBAL_STATE_CODE();
Max Reitz93393e62019-06-12 17:03:38 +02006318
Max Reitzd470ad42017-11-10 21:31:09 +01006319 if (!bs->drv) {
6320 return 0;
6321 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006322
Paolo Bonzini11212d82013-09-04 19:00:27 +02006323 /* If BS is a copy on write image, it is initialized to
6324 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02006325 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02006326 return 0;
6327 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02006328 if (bs->drv->bdrv_has_zero_init) {
6329 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02006330 }
Max Reitz93393e62019-06-12 17:03:38 +02006331
6332 filtered = bdrv_filter_bs(bs);
6333 if (filtered) {
6334 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006335 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02006336
Peter Lieven3ac21622013-06-28 12:47:42 +02006337 /* safe default */
6338 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02006339}
6340
Peter Lieven4ce78692013-10-24 12:06:54 +02006341bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6342{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006343 IO_CODE();
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03006344 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02006345 return false;
6346 }
6347
Eric Blakee24d8132018-01-26 13:34:39 -06006348 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02006349}
6350
ths5fafdf22007-09-16 21:08:06 +00006351void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00006352 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00006353{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006354 IO_CODE();
Kevin Wolf3574c602011-10-26 11:02:11 +02006355 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00006356}
6357
bellardfaea38e2006-08-05 21:31:00 +00006358int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6359{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006360 int ret;
bellardfaea38e2006-08-05 21:31:00 +00006361 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006362 IO_CODE();
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006363 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6364 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00006365 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006366 }
6367 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02006368 BlockDriverState *filtered = bdrv_filter_bs(bs);
6369 if (filtered) {
6370 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006371 }
bellardfaea38e2006-08-05 21:31:00 +00006372 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03006373 }
bellardfaea38e2006-08-05 21:31:00 +00006374 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03006375 ret = drv->bdrv_get_info(bs, bdi);
6376 if (ret < 0) {
6377 return ret;
6378 }
6379
6380 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6381 return -EINVAL;
6382 }
6383
6384 return 0;
bellardfaea38e2006-08-05 21:31:00 +00006385}
6386
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006387ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6388 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02006389{
6390 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006391 IO_CODE();
Max Reitzeae041f2013-10-09 10:46:16 +02006392 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03006393 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02006394 }
6395 return NULL;
6396}
6397
Anton Nefedovd9245592019-09-23 15:17:37 +03006398BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6399{
6400 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006401 IO_CODE();
Anton Nefedovd9245592019-09-23 15:17:37 +03006402 if (!drv || !drv->bdrv_get_specific_stats) {
6403 return NULL;
6404 }
6405 return drv->bdrv_get_specific_stats(bs);
6406}
6407
Eric Blakea31939e2015-11-18 01:52:54 -07006408void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006409{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006410 IO_CODE();
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006411 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006412 return;
6413 }
6414
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006415 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006416}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006417
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006418static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01006419{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006420 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006421 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02006422 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006423 }
6424
6425 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006426 assert(bs->drv->bdrv_debug_remove_breakpoint);
6427 return bs;
6428 }
6429
6430 return NULL;
6431}
6432
6433int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6434 const char *tag)
6435{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006436 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006437 bs = bdrv_find_debug_node(bs);
6438 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006439 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6440 }
6441
6442 return -ENOTSUP;
6443}
6444
Fam Zheng4cc70e92013-11-20 10:01:54 +08006445int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6446{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006447 GLOBAL_STATE_CODE();
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006448 bs = bdrv_find_debug_node(bs);
6449 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006450 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6451 }
6452
6453 return -ENOTSUP;
6454}
6455
Kevin Wolf41c695c2012-12-06 14:32:58 +01006456int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6457{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006458 GLOBAL_STATE_CODE();
Max Reitz938789e2014-03-10 23:44:08 +01006459 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006460 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006461 }
6462
6463 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6464 return bs->drv->bdrv_debug_resume(bs, tag);
6465 }
6466
6467 return -ENOTSUP;
6468}
6469
6470bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6471{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006472 GLOBAL_STATE_CODE();
Kevin Wolf41c695c2012-12-06 14:32:58 +01006473 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006474 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006475 }
6476
6477 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6478 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6479 }
6480
6481 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006482}
6483
Jeff Codyb1b1d782012-10-16 15:49:09 -04006484/* backing_file can either be relative, or absolute, or a protocol. If it is
6485 * relative, it must be relative to the chain. So, passing in bs->filename
6486 * from a BDS as backing_file should not be done, as that may be relative to
6487 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006488BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6489 const char *backing_file)
6490{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006491 char *filename_full = NULL;
6492 char *backing_file_full = NULL;
6493 char *filename_tmp = NULL;
6494 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006495 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006496 BlockDriverState *curr_bs = NULL;
6497 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006498 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006499
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006500 GLOBAL_STATE_CODE();
6501
Jeff Codyb1b1d782012-10-16 15:49:09 -04006502 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006503 return NULL;
6504 }
6505
Jeff Codyb1b1d782012-10-16 15:49:09 -04006506 filename_full = g_malloc(PATH_MAX);
6507 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006508
6509 is_protocol = path_has_protocol(backing_file);
6510
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006511 /*
6512 * Being largely a legacy function, skip any filters here
6513 * (because filters do not have normal filenames, so they cannot
6514 * match anyway; and allowing json:{} filenames is a bit out of
6515 * scope).
6516 */
6517 for (curr_bs = bdrv_skip_filters(bs);
6518 bdrv_cow_child(curr_bs) != NULL;
6519 curr_bs = bs_below)
6520 {
6521 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006522
Max Reitz0b877d02018-08-01 20:34:11 +02006523 if (bdrv_backing_overridden(curr_bs)) {
6524 /*
6525 * If the backing file was overridden, we can only compare
6526 * directly against the backing node's filename.
6527 */
6528
6529 if (!filenames_refreshed) {
6530 /*
6531 * This will automatically refresh all of the
6532 * filenames in the rest of the backing chain, so we
6533 * only need to do this once.
6534 */
6535 bdrv_refresh_filename(bs_below);
6536 filenames_refreshed = true;
6537 }
6538
6539 if (strcmp(backing_file, bs_below->filename) == 0) {
6540 retval = bs_below;
6541 break;
6542 }
6543 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6544 /*
6545 * If either of the filename paths is actually a protocol, then
6546 * compare unmodified paths; otherwise make paths relative.
6547 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006548 char *backing_file_full_ret;
6549
Jeff Codyb1b1d782012-10-16 15:49:09 -04006550 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006551 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006552 break;
6553 }
Jeff Cody418661e2017-01-25 20:08:20 -05006554 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006555 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6556 NULL);
6557 if (backing_file_full_ret) {
6558 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6559 g_free(backing_file_full_ret);
6560 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006561 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006562 break;
6563 }
Jeff Cody418661e2017-01-25 20:08:20 -05006564 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006565 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006566 /* If not an absolute filename path, make it relative to the current
6567 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006568 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6569 NULL);
6570 /* We are going to compare canonicalized absolute pathnames */
6571 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6572 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006573 continue;
6574 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006575 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006576
6577 /* We need to make sure the backing filename we are comparing against
6578 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006579 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6580 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6581 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006582 continue;
6583 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006584 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006585
6586 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006587 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006588 break;
6589 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006590 }
6591 }
6592
Jeff Codyb1b1d782012-10-16 15:49:09 -04006593 g_free(filename_full);
6594 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006595 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006596}
6597
bellardea2384d2004-08-01 21:59:26 +00006598void bdrv_init(void)
6599{
Kevin Wolfe5f05f82021-07-09 18:41:41 +02006600#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6601 use_bdrv_whitelist = 1;
6602#endif
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006603 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006604}
pbrookce1a14d2006-08-07 02:38:06 +00006605
Markus Armbrustereb852012009-10-27 18:41:44 +01006606void bdrv_init_with_whitelist(void)
6607{
6608 use_bdrv_whitelist = 1;
6609 bdrv_init();
6610}
6611
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006612int bdrv_activate(BlockDriverState *bs, Error **errp)
6613{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006614 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006615 Error *local_err = NULL;
6616 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006617 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006618
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006619 GLOBAL_STATE_CODE();
6620
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006621 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006622 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006623 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006624
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006625 QLIST_FOREACH(child, &bs->children, next) {
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006626 bdrv_activate(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006627 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006628 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006629 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006630 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006631 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006632
Kevin Wolfdafe0962017-11-16 13:00:01 +01006633 /*
6634 * Update permissions, they may differ for inactive nodes.
6635 *
6636 * Note that the required permissions of inactive images are always a
6637 * subset of the permissions required after activating the image. This
6638 * allows us to just get the permissions upfront without restricting
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006639 * bdrv_co_invalidate_cache().
Kevin Wolfdafe0962017-11-16 13:00:01 +01006640 *
6641 * It also means that in error cases, we don't have to try and revert to
6642 * the old permissions (which is an operation that could fail, too). We can
6643 * just keep the extended permissions for the next time that an activation
6644 * of the image is tried.
6645 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006646 if (bs->open_flags & BDRV_O_INACTIVE) {
6647 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006648 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006649 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006650 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006651 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006652 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006653
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006654 ret = bdrv_invalidate_cache(bs, errp);
6655 if (ret < 0) {
6656 bs->open_flags |= BDRV_O_INACTIVE;
6657 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006658 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006659
Kevin Wolf7bb49412019-12-17 15:06:38 +01006660 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6661 bdrv_dirty_bitmap_skip_store(bm, false);
6662 }
6663
6664 ret = refresh_total_sectors(bs, bs->total_sectors);
6665 if (ret < 0) {
6666 bs->open_flags |= BDRV_O_INACTIVE;
6667 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006668 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006669 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006670 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006671
6672 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006673 if (parent->klass->activate) {
6674 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006675 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006676 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006677 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006678 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006679 }
6680 }
6681 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006682
6683 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006684}
6685
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006686int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6687{
6688 Error *local_err = NULL;
Emanuele Giuseppe Esposito1581a702022-03-03 10:16:09 -05006689 IO_CODE();
Emanuele Giuseppe Esposito11d0c9b2022-02-09 05:54:52 -05006690
6691 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6692
6693 if (bs->drv->bdrv_co_invalidate_cache) {
6694 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6695 if (local_err) {
6696 error_propagate(errp, local_err);
6697 return -EINVAL;
6698 }
6699 }
6700
6701 return 0;
6702}
6703
Emanuele Giuseppe Esposito3b717192022-02-09 05:54:51 -05006704void bdrv_activate_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006705{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006706 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006707 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006708
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006709 GLOBAL_STATE_CODE();
6710
Kevin Wolf88be7b42016-05-20 18:49:07 +02006711 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006712 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006713 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006714
6715 aio_context_acquire(aio_context);
Emanuele Giuseppe Espositoa94750d2022-02-09 05:54:50 -05006716 ret = bdrv_activate(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006717 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006718 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006719 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006720 return;
6721 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006722 }
6723}
6724
Kevin Wolf9e372712018-11-23 15:11:14 +01006725static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6726{
6727 BdrvChild *parent;
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05006728 GLOBAL_STATE_CODE();
Kevin Wolf9e372712018-11-23 15:11:14 +01006729
6730 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006731 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006732 BlockDriverState *parent_bs = parent->opaque;
6733 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6734 return true;
6735 }
6736 }
6737 }
6738
6739 return false;
6740}
6741
6742static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006743{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006744 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006745 int ret;
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006746 uint64_t cumulative_perms, cumulative_shared_perms;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006747
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05006748 GLOBAL_STATE_CODE();
6749
Max Reitzd470ad42017-11-10 21:31:09 +01006750 if (!bs->drv) {
6751 return -ENOMEDIUM;
6752 }
6753
Kevin Wolf9e372712018-11-23 15:11:14 +01006754 /* Make sure that we don't inactivate a child before its parent.
6755 * It will be covered by recursion from the yet active parent. */
6756 if (bdrv_has_bds_parent(bs, true)) {
6757 return 0;
6758 }
6759
6760 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6761
6762 /* Inactivate this node */
6763 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006764 ret = bs->drv->bdrv_inactivate(bs);
6765 if (ret < 0) {
6766 return ret;
6767 }
6768 }
6769
Kevin Wolf9e372712018-11-23 15:11:14 +01006770 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006771 if (parent->klass->inactivate) {
6772 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006773 if (ret < 0) {
6774 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006775 }
6776 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006777 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006778
Vladimir Sementsov-Ogievskiya13de402021-09-11 15:00:27 +03006779 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6780 &cumulative_shared_perms);
6781 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6782 /* Our inactive parents still need write access. Inactivation failed. */
6783 return -EPERM;
6784 }
6785
Kevin Wolf9e372712018-11-23 15:11:14 +01006786 bs->open_flags |= BDRV_O_INACTIVE;
6787
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006788 /*
6789 * Update permissions, they may differ for inactive nodes.
6790 * We only tried to loosen restrictions, so errors are not fatal, ignore
6791 * them.
6792 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006793 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006794
6795 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006796 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006797 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006798 if (ret < 0) {
6799 return ret;
6800 }
6801 }
6802
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006803 return 0;
6804}
6805
6806int bdrv_inactivate_all(void)
6807{
Max Reitz79720af2016-03-16 19:54:44 +01006808 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006809 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006810 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006811 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006812
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006813 GLOBAL_STATE_CODE();
6814
Kevin Wolf88be7b42016-05-20 18:49:07 +02006815 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006816 AioContext *aio_context = bdrv_get_aio_context(bs);
6817
6818 if (!g_slist_find(aio_ctxs, aio_context)) {
6819 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6820 aio_context_acquire(aio_context);
6821 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006822 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006823
Kevin Wolf9e372712018-11-23 15:11:14 +01006824 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6825 /* Nodes with BDS parents are covered by recursion from the last
6826 * parent that gets inactivated. Don't inactivate them a second
6827 * time if that has already happened. */
6828 if (bdrv_has_bds_parent(bs, false)) {
6829 continue;
6830 }
6831 ret = bdrv_inactivate_recurse(bs);
6832 if (ret < 0) {
6833 bdrv_next_cleanup(&it);
6834 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006835 }
6836 }
6837
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006838out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006839 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6840 AioContext *aio_context = ctx->data;
6841 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006842 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006843 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006844
6845 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006846}
6847
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006848/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006849/* removable device support */
6850
6851/**
6852 * Return TRUE if the media is present
6853 */
Max Reitze031f752015-10-19 17:53:11 +02006854bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006855{
6856 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006857 BdrvChild *child;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006858 IO_CODE();
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006859
Max Reitze031f752015-10-19 17:53:11 +02006860 if (!drv) {
6861 return false;
6862 }
Max Reitz28d7a782015-10-19 17:53:13 +02006863 if (drv->bdrv_is_inserted) {
6864 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006865 }
Max Reitz28d7a782015-10-19 17:53:13 +02006866 QLIST_FOREACH(child, &bs->children, next) {
6867 if (!bdrv_is_inserted(child->bs)) {
6868 return false;
6869 }
6870 }
6871 return true;
bellard19cb3732006-08-19 11:45:59 +00006872}
6873
6874/**
bellard19cb3732006-08-19 11:45:59 +00006875 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6876 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006877void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006878{
6879 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006880 IO_CODE();
bellard19cb3732006-08-19 11:45:59 +00006881
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006882 if (drv && drv->bdrv_eject) {
6883 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006884 }
bellard19cb3732006-08-19 11:45:59 +00006885}
6886
bellard19cb3732006-08-19 11:45:59 +00006887/**
6888 * Lock or unlock the media (if it is locked, the user won't be able
6889 * to eject it manually).
6890 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006891void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006892{
6893 BlockDriver *drv = bs->drv;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05006894 IO_CODE();
Markus Armbruster025e8492011-09-06 18:58:47 +02006895 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006896
Markus Armbruster025e8492011-09-06 18:58:47 +02006897 if (drv && drv->bdrv_lock_medium) {
6898 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006899 }
6900}
ths985a03b2007-12-24 16:10:43 +00006901
Fam Zheng9fcb0252013-08-23 09:14:46 +08006902/* Get a reference to bs */
6903void bdrv_ref(BlockDriverState *bs)
6904{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006905 GLOBAL_STATE_CODE();
Fam Zheng9fcb0252013-08-23 09:14:46 +08006906 bs->refcnt++;
6907}
6908
6909/* Release a previously grabbed reference to bs.
6910 * If after releasing, reference count is zero, the BlockDriverState is
6911 * deleted. */
6912void bdrv_unref(BlockDriverState *bs)
6913{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006914 GLOBAL_STATE_CODE();
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006915 if (!bs) {
6916 return;
6917 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006918 assert(bs->refcnt > 0);
6919 if (--bs->refcnt == 0) {
6920 bdrv_delete(bs);
6921 }
6922}
6923
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006924struct BdrvOpBlocker {
6925 Error *reason;
6926 QLIST_ENTRY(BdrvOpBlocker) list;
6927};
6928
6929bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6930{
6931 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006932 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006933 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6934 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6935 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006936 error_propagate_prepend(errp, error_copy(blocker->reason),
6937 "Node '%s' is busy: ",
6938 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006939 return true;
6940 }
6941 return false;
6942}
6943
6944void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6945{
6946 BdrvOpBlocker *blocker;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006947 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006948 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6949
Markus Armbruster5839e532014-08-19 10:31:08 +02006950 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006951 blocker->reason = reason;
6952 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6953}
6954
6955void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6956{
6957 BdrvOpBlocker *blocker, *next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006958 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006959 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6960 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6961 if (blocker->reason == reason) {
6962 QLIST_REMOVE(blocker, list);
6963 g_free(blocker);
6964 }
6965 }
6966}
6967
6968void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6969{
6970 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006971 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006972 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6973 bdrv_op_block(bs, i, reason);
6974 }
6975}
6976
6977void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6978{
6979 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006980 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006981 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6982 bdrv_op_unblock(bs, i, reason);
6983 }
6984}
6985
6986bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6987{
6988 int i;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05006989 GLOBAL_STATE_CODE();
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006990 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6991 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6992 return false;
6993 }
6994 }
6995 return true;
6996}
6997
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006998void bdrv_img_create(const char *filename, const char *fmt,
6999 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08007000 char *options, uint64_t img_size, int flags, bool quiet,
7001 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007002{
Chunyan Liu83d05212014-06-05 17:20:51 +08007003 QemuOptsList *create_opts = NULL;
7004 QemuOpts *opts = NULL;
7005 const char *backing_fmt, *backing_file;
7006 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007007 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02007008 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007009 int ret = 0;
7010
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007011 GLOBAL_STATE_CODE();
7012
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007013 /* Find driver and parse its options */
7014 drv = bdrv_find_format(fmt);
7015 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02007016 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02007017 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007018 }
7019
Max Reitzb65a5e12015-02-05 13:58:12 -05007020 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007021 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02007022 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007023 }
7024
Max Reitzc6149722014-12-02 18:32:45 +01007025 if (!drv->create_opts) {
7026 error_setg(errp, "Format driver '%s' does not support image creation",
7027 drv->format_name);
7028 return;
7029 }
7030
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02007031 if (!proto_drv->create_opts) {
7032 error_setg(errp, "Protocol driver '%s' does not support image creation",
7033 proto_drv->format_name);
7034 return;
7035 }
7036
Kevin Wolff6dc1c32019-11-26 16:45:49 +01007037 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007038 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02007039 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007040
Chunyan Liu83d05212014-06-05 17:20:51 +08007041 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007042
7043 /* Parse -o options */
7044 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02007045 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007046 goto out;
7047 }
7048 }
7049
Kevin Wolff6dc1c32019-11-26 16:45:49 +01007050 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7051 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7052 } else if (img_size != UINT64_C(-1)) {
7053 error_setg(errp, "The image size must be specified only once");
7054 goto out;
7055 }
7056
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007057 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02007058 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02007059 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02007060 error_setg(errp, "Backing file not supported for file format '%s'",
7061 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007062 goto out;
7063 }
7064 }
7065
7066 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02007067 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02007068 error_setg(errp, "Backing file format not supported for file "
7069 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007070 goto out;
7071 }
7072 }
7073
Chunyan Liu83d05212014-06-05 17:20:51 +08007074 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
7075 if (backing_file) {
7076 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02007077 error_setg(errp, "Error: Trying to create an image with the "
7078 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01007079 goto out;
7080 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05007081 if (backing_file[0] == '\0') {
7082 error_setg(errp, "Expected backing file name, got empty string");
7083 goto out;
7084 }
Jes Sorensen792da932010-12-16 13:52:17 +01007085 }
7086
Chunyan Liu83d05212014-06-05 17:20:51 +08007087 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007088
John Snow6e6e55f2017-07-17 20:34:22 -04007089 /* The size for the image must always be specified, unless we have a backing
7090 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05007091 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04007092 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
7093 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01007094 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04007095 int back_flags;
7096 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02007097
Max Reitz645ae7d2019-02-01 20:29:14 +01007098 full_backing =
7099 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7100 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04007101 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007102 goto out;
7103 }
Max Reitz645ae7d2019-02-01 20:29:14 +01007104 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04007105
Max Reitzd5b23992021-06-22 16:00:30 +02007106 /*
7107 * No need to do I/O here, which allows us to open encrypted
7108 * backing images without needing the secret
7109 */
John Snow6e6e55f2017-07-17 20:34:22 -04007110 back_flags = flags;
7111 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02007112 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04007113
Fam Zhengcc954f02017-12-15 16:04:45 +08007114 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04007115 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04007116 qdict_put_str(backing_options, "driver", backing_fmt);
7117 }
Fam Zhengcc954f02017-12-15 16:04:45 +08007118 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04007119
7120 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7121 &local_err);
7122 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05007123 if (!bs) {
7124 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04007125 goto out;
7126 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05007127 if (!backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007128 error_setg(&local_err,
7129 "Backing file specified without backing format");
7130 error_append_hint(&local_err, "Detected format of %s.",
7131 bs->drv->format_name);
7132 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007133 }
John Snow6e6e55f2017-07-17 20:34:22 -04007134 if (size == -1) {
7135 /* Opened BS, have no size */
7136 size = bdrv_getlength(bs);
7137 if (size < 0) {
7138 error_setg_errno(errp, -size, "Could not get size of '%s'",
7139 backing_file);
7140 bdrv_unref(bs);
7141 goto out;
7142 }
7143 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7144 }
7145 bdrv_unref(bs);
7146 }
Eric Blaked9f059a2020-07-06 15:39:54 -05007147 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7148 } else if (backing_file && !backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07007149 error_setg(&local_err,
7150 "Backing file specified without backing format");
7151 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05007152 }
John Snow6e6e55f2017-07-17 20:34:22 -04007153
7154 if (size == -1) {
7155 error_setg(errp, "Image creation needs a size parameter");
7156 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007157 }
7158
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007159 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02007160 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08007161 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007162 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05007163 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01007164 }
Chunyan Liu83d05212014-06-05 17:20:51 +08007165
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007166 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08007167
Max Reitzcc84d902013-09-06 17:14:26 +02007168 if (ret == -EFBIG) {
7169 /* This is generally a better message than whatever the driver would
7170 * deliver (especially because of the cluster_size_hint), since that
7171 * is most probably not much different from "image too large". */
7172 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08007173 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02007174 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007175 }
Max Reitzcc84d902013-09-06 17:14:26 +02007176 error_setg(errp, "The image size is too large for file format '%s'"
7177 "%s", fmt, cluster_size_hint);
7178 error_free(local_err);
7179 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007180 }
7181
7182out:
Chunyan Liu83d05212014-06-05 17:20:51 +08007183 qemu_opts_del(opts);
7184 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03007185 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01007186}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007187
7188AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7189{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007190 IO_CODE();
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00007191 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007192}
7193
Kevin Wolfe336fd42020-10-05 17:58:53 +02007194AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7195{
7196 Coroutine *self = qemu_coroutine_self();
7197 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7198 AioContext *new_ctx;
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007199 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007200
7201 /*
7202 * Increase bs->in_flight to ensure that this operation is completed before
7203 * moving the node to a different AioContext. Read new_ctx only afterwards.
7204 */
7205 bdrv_inc_in_flight(bs);
7206
7207 new_ctx = bdrv_get_aio_context(bs);
7208 aio_co_reschedule_self(new_ctx);
7209 return old_ctx;
7210}
7211
7212void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7213{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007214 IO_CODE();
Kevin Wolfe336fd42020-10-05 17:58:53 +02007215 aio_co_reschedule_self(old_ctx);
7216 bdrv_dec_in_flight(bs);
7217}
7218
Kevin Wolf18c6ac12020-10-05 17:58:54 +02007219void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7220{
7221 AioContext *ctx = bdrv_get_aio_context(bs);
7222
7223 /* In the main thread, bs->aio_context won't change concurrently */
7224 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7225
7226 /*
7227 * We're in coroutine context, so we already hold the lock of the main
7228 * loop AioContext. Don't lock it twice to avoid deadlocks.
7229 */
7230 assert(qemu_in_coroutine());
7231 if (ctx != qemu_get_aio_context()) {
7232 aio_context_acquire(ctx);
7233 }
7234}
7235
7236void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7237{
7238 AioContext *ctx = bdrv_get_aio_context(bs);
7239
7240 assert(qemu_in_coroutine());
7241 if (ctx != qemu_get_aio_context()) {
7242 aio_context_release(ctx);
7243 }
7244}
7245
Fam Zheng052a7572017-04-10 20:09:25 +08007246void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7247{
Emanuele Giuseppe Esposito384a48f2022-03-03 10:15:50 -05007248 IO_CODE();
Fam Zheng052a7572017-04-10 20:09:25 +08007249 aio_co_enter(bdrv_get_aio_context(bs), co);
7250}
7251
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007252static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7253{
Emanuele Giuseppe Espositobdb73472022-03-03 10:16:02 -05007254 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007255 QLIST_REMOVE(ban, list);
7256 g_free(ban);
7257}
7258
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007259static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007260{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007261 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02007262
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007263 assert(!bs->walking_aio_notifiers);
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007264 GLOBAL_STATE_CODE();
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007265 bs->walking_aio_notifiers = true;
7266 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7267 if (baf->deleted) {
7268 bdrv_do_remove_aio_context_notifier(baf);
7269 } else {
7270 baf->detach_aio_context(baf->opaque);
7271 }
Max Reitz33384422014-06-20 21:57:33 +02007272 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007273 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7274 * remove remaining aio notifiers if we aren't called again.
7275 */
7276 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02007277
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007278 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007279 bs->drv->bdrv_detach_aio_context(bs);
7280 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007281
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007282 if (bs->quiesce_counter) {
7283 aio_enable_external(bs->aio_context);
7284 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007285 bs->aio_context = NULL;
7286}
7287
Kevin Wolfa3a683c2019-05-06 19:17:57 +02007288static void bdrv_attach_aio_context(BlockDriverState *bs,
7289 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007290{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007291 BdrvAioNotifier *ban, *ban_tmp;
Emanuele Giuseppe Espositoda359902022-03-03 10:16:11 -05007292 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007293
Kevin Wolfe64f25f2019-02-08 16:51:17 +01007294 if (bs->quiesce_counter) {
7295 aio_disable_external(new_context);
7296 }
7297
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007298 bs->aio_context = new_context;
7299
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02007300 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007301 bs->drv->bdrv_attach_aio_context(bs, new_context);
7302 }
Max Reitz33384422014-06-20 21:57:33 +02007303
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007304 assert(!bs->walking_aio_notifiers);
7305 bs->walking_aio_notifiers = true;
7306 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7307 if (ban->deleted) {
7308 bdrv_do_remove_aio_context_notifier(ban);
7309 } else {
7310 ban->attached_aio_context(new_context, ban->opaque);
7311 }
Max Reitz33384422014-06-20 21:57:33 +02007312 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007313 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007314}
7315
Kevin Wolf42a65f02019-05-07 18:31:38 +02007316/*
7317 * Changes the AioContext used for fd handlers, timers, and BHs by this
7318 * BlockDriverState and all its children and parents.
7319 *
Max Reitz43eaaae2019-07-22 15:30:54 +02007320 * Must be called from the main AioContext.
7321 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02007322 * The caller must own the AioContext lock for the old AioContext of bs, but it
7323 * must not own the AioContext lock for new_context (unless new_context is the
7324 * same as the current context of bs).
7325 *
7326 * @ignore will accumulate all visited BdrvChild object. The caller is
7327 * responsible for freeing the list afterwards.
7328 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02007329void bdrv_set_aio_context_ignore(BlockDriverState *bs,
7330 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007331{
Max Reitze037c092019-07-19 11:26:14 +02007332 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007333 GSList *children_to_process = NULL;
7334 GSList *parents_to_process = NULL;
7335 GSList *entry;
7336 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02007337
Max Reitz43eaaae2019-07-22 15:30:54 +02007338 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05007339 GLOBAL_STATE_CODE();
Max Reitz43eaaae2019-07-22 15:30:54 +02007340
Max Reitze037c092019-07-19 11:26:14 +02007341 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03007342 return;
7343 }
7344
Kevin Wolfd70d5952019-02-08 16:53:37 +01007345 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02007346
7347 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007348 if (g_slist_find(*ignore, child)) {
7349 continue;
7350 }
7351 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01007352 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02007353 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007354
7355 QLIST_FOREACH(parent, &bs->parents, next_parent) {
7356 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02007357 continue;
7358 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01007359 *ignore = g_slist_prepend(*ignore, parent);
7360 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02007361 }
7362
Sergio Lopez722d8e72021-02-01 13:50:31 +01007363 for (entry = children_to_process;
7364 entry != NULL;
7365 entry = g_slist_next(entry)) {
7366 child = entry->data;
7367 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
7368 }
7369 g_slist_free(children_to_process);
7370
7371 for (entry = parents_to_process;
7372 entry != NULL;
7373 entry = g_slist_next(entry)) {
7374 parent = entry->data;
7375 assert(parent->klass->set_aio_ctx);
7376 parent->klass->set_aio_ctx(parent, new_context, ignore);
7377 }
7378 g_slist_free(parents_to_process);
7379
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007380 bdrv_detach_aio_context(bs);
7381
Max Reitze037c092019-07-19 11:26:14 +02007382 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02007383 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007384 aio_context_acquire(new_context);
7385 }
7386
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02007387 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02007388
7389 /*
7390 * If this function was recursively called from
7391 * bdrv_set_aio_context_ignore(), there may be nodes in the
7392 * subtree that have not yet been moved to the new AioContext.
7393 * Release the old one so bdrv_drained_end() can poll them.
7394 */
Max Reitz43eaaae2019-07-22 15:30:54 +02007395 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007396 aio_context_release(old_context);
7397 }
7398
Kevin Wolfd70d5952019-02-08 16:53:37 +01007399 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02007400
Max Reitz43eaaae2019-07-22 15:30:54 +02007401 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02007402 aio_context_acquire(old_context);
7403 }
Max Reitz43eaaae2019-07-22 15:30:54 +02007404 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02007405 aio_context_release(new_context);
7406 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01007407}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02007408
Kevin Wolf5d231842019-05-06 19:17:56 +02007409static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7410 GSList **ignore, Error **errp)
7411{
Emanuele Giuseppe Espositof0c28322022-03-03 10:16:13 -05007412 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007413 if (g_slist_find(*ignore, c)) {
7414 return true;
7415 }
7416 *ignore = g_slist_prepend(*ignore, c);
7417
Max Reitzbd86fb92020-05-13 13:05:13 +02007418 /*
7419 * A BdrvChildClass that doesn't handle AioContext changes cannot
7420 * tolerate any AioContext changes
7421 */
7422 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007423 char *user = bdrv_child_user_desc(c);
7424 error_setg(errp, "Changing iothreads is not supported by %s", user);
7425 g_free(user);
7426 return false;
7427 }
Max Reitzbd86fb92020-05-13 13:05:13 +02007428 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02007429 assert(!errp || *errp);
7430 return false;
7431 }
7432 return true;
7433}
7434
7435bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7436 GSList **ignore, Error **errp)
7437{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007438 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007439 if (g_slist_find(*ignore, c)) {
7440 return true;
7441 }
7442 *ignore = g_slist_prepend(*ignore, c);
7443 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
7444}
7445
7446/* @ignore will accumulate all visited BdrvChild object. The caller is
7447 * responsible for freeing the list afterwards. */
7448bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7449 GSList **ignore, Error **errp)
7450{
7451 BdrvChild *c;
7452
7453 if (bdrv_get_aio_context(bs) == ctx) {
7454 return true;
7455 }
7456
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007457 GLOBAL_STATE_CODE();
7458
Kevin Wolf5d231842019-05-06 19:17:56 +02007459 QLIST_FOREACH(c, &bs->parents, next_parent) {
7460 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
7461 return false;
7462 }
7463 }
7464 QLIST_FOREACH(c, &bs->children, next) {
7465 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
7466 return false;
7467 }
7468 }
7469
7470 return true;
7471}
7472
7473int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7474 BdrvChild *ignore_child, Error **errp)
7475{
7476 GSList *ignore;
7477 bool ret;
7478
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007479 GLOBAL_STATE_CODE();
7480
Kevin Wolf5d231842019-05-06 19:17:56 +02007481 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7482 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7483 g_slist_free(ignore);
7484
7485 if (!ret) {
7486 return -EPERM;
7487 }
7488
Kevin Wolf53a7d042019-05-06 19:17:59 +02007489 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7490 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7491 g_slist_free(ignore);
7492
Kevin Wolf5d231842019-05-06 19:17:56 +02007493 return 0;
7494}
7495
7496int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7497 Error **errp)
7498{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007499 GLOBAL_STATE_CODE();
Kevin Wolf5d231842019-05-06 19:17:56 +02007500 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7501}
7502
Max Reitz33384422014-06-20 21:57:33 +02007503void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7504 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7505 void (*detach_aio_context)(void *opaque), void *opaque)
7506{
7507 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7508 *ban = (BdrvAioNotifier){
7509 .attached_aio_context = attached_aio_context,
7510 .detach_aio_context = detach_aio_context,
7511 .opaque = opaque
7512 };
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007513 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007514
7515 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7516}
7517
7518void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7519 void (*attached_aio_context)(AioContext *,
7520 void *),
7521 void (*detach_aio_context)(void *),
7522 void *opaque)
7523{
7524 BdrvAioNotifier *ban, *ban_next;
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007525 GLOBAL_STATE_CODE();
Max Reitz33384422014-06-20 21:57:33 +02007526
7527 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7528 if (ban->attached_aio_context == attached_aio_context &&
7529 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007530 ban->opaque == opaque &&
7531 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007532 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007533 if (bs->walking_aio_notifiers) {
7534 ban->deleted = true;
7535 } else {
7536 bdrv_do_remove_aio_context_notifier(ban);
7537 }
Max Reitz33384422014-06-20 21:57:33 +02007538 return;
7539 }
7540 }
7541
7542 abort();
7543}
7544
Max Reitz77485432014-10-27 11:12:50 +01007545int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007546 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007547 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007548 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007549{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007550 GLOBAL_STATE_CODE();
Max Reitzd470ad42017-11-10 21:31:09 +01007551 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007552 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007553 return -ENOMEDIUM;
7554 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007555 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007556 error_setg(errp, "Block driver '%s' does not support option amendment",
7557 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007558 return -ENOTSUP;
7559 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007560 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7561 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007562}
Benoît Canetf6186f42013-10-02 14:33:48 +02007563
Max Reitz5d69b5a2020-02-18 11:34:41 +01007564/*
7565 * This function checks whether the given @to_replace is allowed to be
7566 * replaced by a node that always shows the same data as @bs. This is
7567 * used for example to verify whether the mirror job can replace
7568 * @to_replace by the target mirrored from @bs.
7569 * To be replaceable, @bs and @to_replace may either be guaranteed to
7570 * always show the same data (because they are only connected through
7571 * filters), or some driver may allow replacing one of its children
7572 * because it can guarantee that this child's data is not visible at
7573 * all (for example, for dissenting quorum children that have no other
7574 * parents).
7575 */
7576bool bdrv_recurse_can_replace(BlockDriverState *bs,
7577 BlockDriverState *to_replace)
7578{
Max Reitz93393e62019-06-12 17:03:38 +02007579 BlockDriverState *filtered;
7580
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007581 GLOBAL_STATE_CODE();
7582
Max Reitz5d69b5a2020-02-18 11:34:41 +01007583 if (!bs || !bs->drv) {
7584 return false;
7585 }
7586
7587 if (bs == to_replace) {
7588 return true;
7589 }
7590
7591 /* See what the driver can do */
7592 if (bs->drv->bdrv_recurse_can_replace) {
7593 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7594 }
7595
7596 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007597 filtered = bdrv_filter_bs(bs);
7598 if (filtered) {
7599 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007600 }
7601
7602 /* Safe default */
7603 return false;
7604}
7605
Max Reitz810803a2020-02-18 11:34:44 +01007606/*
7607 * Check whether the given @node_name can be replaced by a node that
7608 * has the same data as @parent_bs. If so, return @node_name's BDS;
7609 * NULL otherwise.
7610 *
7611 * @node_name must be a (recursive) *child of @parent_bs (or this
7612 * function will return NULL).
7613 *
7614 * The result (whether the node can be replaced or not) is only valid
7615 * for as long as no graph or permission changes occur.
7616 */
Wen Congyange12f3782015-07-17 10:12:22 +08007617BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7618 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007619{
7620 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007621 AioContext *aio_context;
7622
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007623 GLOBAL_STATE_CODE();
7624
Benoît Canet09158f02014-06-27 18:25:25 +02007625 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007626 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007627 return NULL;
7628 }
7629
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007630 aio_context = bdrv_get_aio_context(to_replace_bs);
7631 aio_context_acquire(aio_context);
7632
Benoît Canet09158f02014-06-27 18:25:25 +02007633 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007634 to_replace_bs = NULL;
7635 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007636 }
7637
7638 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7639 * most non filter in order to prevent data corruption.
7640 * Another benefit is that this tests exclude backing files which are
7641 * blocked by the backing blockers.
7642 */
Max Reitz810803a2020-02-18 11:34:44 +01007643 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7644 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7645 "because it cannot be guaranteed that doing so would not "
7646 "lead to an abrupt change of visible data",
7647 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007648 to_replace_bs = NULL;
7649 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007650 }
7651
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007652out:
7653 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007654 return to_replace_bs;
7655}
Ming Lei448ad912014-07-04 18:04:33 +08007656
Max Reitz97e2f022019-02-01 20:29:27 +01007657/**
7658 * Iterates through the list of runtime option keys that are said to
7659 * be "strong" for a BDS. An option is called "strong" if it changes
7660 * a BDS's data. For example, the null block driver's "size" and
7661 * "read-zeroes" options are strong, but its "latency-ns" option is
7662 * not.
7663 *
7664 * If a key returned by this function ends with a dot, all options
7665 * starting with that prefix are strong.
7666 */
7667static const char *const *strong_options(BlockDriverState *bs,
7668 const char *const *curopt)
7669{
7670 static const char *const global_options[] = {
7671 "driver", "filename", NULL
7672 };
7673
7674 if (!curopt) {
7675 return &global_options[0];
7676 }
7677
7678 curopt++;
7679 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7680 curopt = bs->drv->strong_runtime_opts;
7681 }
7682
7683 return (curopt && *curopt) ? curopt : NULL;
7684}
7685
7686/**
7687 * Copies all strong runtime options from bs->options to the given
7688 * QDict. The set of strong option keys is determined by invoking
7689 * strong_options().
7690 *
7691 * Returns true iff any strong option was present in bs->options (and
7692 * thus copied to the target QDict) with the exception of "filename"
7693 * and "driver". The caller is expected to use this value to decide
7694 * whether the existence of strong options prevents the generation of
7695 * a plain filename.
7696 */
7697static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7698{
7699 bool found_any = false;
7700 const char *const *option_name = NULL;
7701
7702 if (!bs->drv) {
7703 return false;
7704 }
7705
7706 while ((option_name = strong_options(bs, option_name))) {
7707 bool option_given = false;
7708
7709 assert(strlen(*option_name) > 0);
7710 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7711 QObject *entry = qdict_get(bs->options, *option_name);
7712 if (!entry) {
7713 continue;
7714 }
7715
7716 qdict_put_obj(d, *option_name, qobject_ref(entry));
7717 option_given = true;
7718 } else {
7719 const QDictEntry *entry;
7720 for (entry = qdict_first(bs->options); entry;
7721 entry = qdict_next(bs->options, entry))
7722 {
7723 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7724 qdict_put_obj(d, qdict_entry_key(entry),
7725 qobject_ref(qdict_entry_value(entry)));
7726 option_given = true;
7727 }
7728 }
7729 }
7730
7731 /* While "driver" and "filename" need to be included in a JSON filename,
7732 * their existence does not prohibit generation of a plain filename. */
7733 if (!found_any && option_given &&
7734 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7735 {
7736 found_any = true;
7737 }
7738 }
7739
Max Reitz62a01a272019-02-01 20:29:34 +01007740 if (!qdict_haskey(d, "driver")) {
7741 /* Drivers created with bdrv_new_open_driver() may not have a
7742 * @driver option. Add it here. */
7743 qdict_put_str(d, "driver", bs->drv->format_name);
7744 }
7745
Max Reitz97e2f022019-02-01 20:29:27 +01007746 return found_any;
7747}
7748
Max Reitz90993622019-02-01 20:29:09 +01007749/* Note: This function may return false positives; it may return true
7750 * even if opening the backing file specified by bs's image header
7751 * would result in exactly bs->backing. */
Emanuele Giuseppe Espositofa8fc1d2021-12-15 07:11:38 -05007752static bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007753{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05007754 GLOBAL_STATE_CODE();
Max Reitz90993622019-02-01 20:29:09 +01007755 if (bs->backing) {
7756 return strcmp(bs->auto_backing_file,
7757 bs->backing->bs->filename);
7758 } else {
7759 /* No backing BDS, so if the image header reports any backing
7760 * file, it must have been suppressed */
7761 return bs->auto_backing_file[0] != '\0';
7762 }
7763}
7764
Max Reitz91af7012014-07-18 20:24:56 +02007765/* Updates the following BDS fields:
7766 * - exact_filename: A filename which may be used for opening a block device
7767 * which (mostly) equals the given BDS (even without any
7768 * other options; so reading and writing must return the same
7769 * results, but caching etc. may be different)
7770 * - full_open_options: Options which, when given when opening a block device
7771 * (without a filename), result in a BDS (mostly)
7772 * equalling the given one
7773 * - filename: If exact_filename is set, it is copied here. Otherwise,
7774 * full_open_options is converted to a JSON object, prefixed with
7775 * "json:" (for use through the JSON pseudo protocol) and put here.
7776 */
7777void bdrv_refresh_filename(BlockDriverState *bs)
7778{
7779 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007780 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007781 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007782 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007783 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007784 bool generate_json_filename; /* Whether our default implementation should
7785 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007786
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007787 GLOBAL_STATE_CODE();
7788
Max Reitz91af7012014-07-18 20:24:56 +02007789 if (!drv) {
7790 return;
7791 }
7792
Max Reitze24518e2019-02-01 20:29:06 +01007793 /* This BDS's file name may depend on any of its children's file names, so
7794 * refresh those first */
7795 QLIST_FOREACH(child, &bs->children, next) {
7796 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007797 }
7798
Max Reitzbb808d52019-02-01 20:29:07 +01007799 if (bs->implicit) {
7800 /* For implicit nodes, just copy everything from the single child */
7801 child = QLIST_FIRST(&bs->children);
7802 assert(QLIST_NEXT(child, next) == NULL);
7803
7804 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7805 child->bs->exact_filename);
7806 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7807
Pan Nengyuancb895612020-01-16 16:56:00 +08007808 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007809 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7810
7811 return;
7812 }
7813
Max Reitz90993622019-02-01 20:29:09 +01007814 backing_overridden = bdrv_backing_overridden(bs);
7815
7816 if (bs->open_flags & BDRV_O_NO_IO) {
7817 /* Without I/O, the backing file does not change anything.
7818 * Therefore, in such a case (primarily qemu-img), we can
7819 * pretend the backing file has not been overridden even if
7820 * it technically has been. */
7821 backing_overridden = false;
7822 }
7823
Max Reitz97e2f022019-02-01 20:29:27 +01007824 /* Gather the options QDict */
7825 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007826 generate_json_filename = append_strong_runtime_options(opts, bs);
7827 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007828
7829 if (drv->bdrv_gather_child_options) {
7830 /* Some block drivers may not want to present all of their children's
7831 * options, or name them differently from BdrvChild.name */
7832 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7833 } else {
7834 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007835 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007836 /* We can skip the backing BDS if it has not been overridden */
7837 continue;
7838 }
7839
7840 qdict_put(opts, child->name,
7841 qobject_ref(child->bs->full_open_options));
7842 }
7843
7844 if (backing_overridden && !bs->backing) {
7845 /* Force no backing file */
7846 qdict_put_null(opts, "backing");
7847 }
7848 }
7849
7850 qobject_unref(bs->full_open_options);
7851 bs->full_open_options = opts;
7852
Max Reitz52f72d62019-06-12 17:43:03 +02007853 primary_child_bs = bdrv_primary_bs(bs);
7854
Max Reitz998b3a12019-02-01 20:29:28 +01007855 if (drv->bdrv_refresh_filename) {
7856 /* Obsolete information is of no use here, so drop the old file name
7857 * information before refreshing it */
7858 bs->exact_filename[0] = '\0';
7859
7860 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007861 } else if (primary_child_bs) {
7862 /*
7863 * Try to reconstruct valid information from the underlying
7864 * file -- this only works for format nodes (filter nodes
7865 * cannot be probed and as such must be selected by the user
7866 * either through an options dict, or through a special
7867 * filename which the filter driver must construct in its
7868 * .bdrv_refresh_filename() implementation).
7869 */
Max Reitz998b3a12019-02-01 20:29:28 +01007870
7871 bs->exact_filename[0] = '\0';
7872
Max Reitzfb695c72019-02-01 20:29:29 +01007873 /*
7874 * We can use the underlying file's filename if:
7875 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007876 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007877 * - the file is a protocol BDS, and
7878 * - opening that file (as this BDS's format) will automatically create
7879 * the BDS tree we have right now, that is:
7880 * - the user did not significantly change this BDS's behavior with
7881 * some explicit (strong) options
7882 * - no non-file child of this BDS has been overridden by the user
7883 * Both of these conditions are represented by generate_json_filename.
7884 */
Max Reitz52f72d62019-06-12 17:43:03 +02007885 if (primary_child_bs->exact_filename[0] &&
7886 primary_child_bs->drv->bdrv_file_open &&
7887 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007888 {
Max Reitz52f72d62019-06-12 17:43:03 +02007889 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007890 }
7891 }
7892
Max Reitz91af7012014-07-18 20:24:56 +02007893 if (bs->exact_filename[0]) {
7894 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007895 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007896 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007897 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007898 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007899 /* Give user a hint if we truncated things. */
7900 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7901 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007902 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007903 }
7904}
Wen Congyange06018a2016-05-10 15:36:37 +08007905
Max Reitz1e89d0f2019-02-01 20:29:18 +01007906char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7907{
7908 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007909 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007910
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007911 GLOBAL_STATE_CODE();
7912
Max Reitz1e89d0f2019-02-01 20:29:18 +01007913 if (!drv) {
7914 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7915 return NULL;
7916 }
7917
7918 if (drv->bdrv_dirname) {
7919 return drv->bdrv_dirname(bs, errp);
7920 }
7921
Max Reitz52f72d62019-06-12 17:43:03 +02007922 child_bs = bdrv_primary_bs(bs);
7923 if (child_bs) {
7924 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007925 }
7926
7927 bdrv_refresh_filename(bs);
7928 if (bs->exact_filename[0] != '\0') {
7929 return path_combine(bs->exact_filename, "");
7930 }
7931
7932 error_setg(errp, "Cannot generate a base directory for %s nodes",
7933 drv->format_name);
7934 return NULL;
7935}
7936
Wen Congyange06018a2016-05-10 15:36:37 +08007937/*
7938 * Hot add/remove a BDS's child. So the user can take a child offline when
7939 * it is broken and take a new child online
7940 */
7941void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7942 Error **errp)
7943{
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007944 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007945 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7946 error_setg(errp, "The node %s does not support adding a child",
7947 bdrv_get_device_or_node_name(parent_bs));
7948 return;
7949 }
7950
7951 if (!QLIST_EMPTY(&child_bs->parents)) {
7952 error_setg(errp, "The node %s already has a parent",
7953 child_bs->node_name);
7954 return;
7955 }
7956
7957 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7958}
7959
7960void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7961{
7962 BdrvChild *tmp;
7963
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007964 GLOBAL_STATE_CODE();
Wen Congyange06018a2016-05-10 15:36:37 +08007965 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7966 error_setg(errp, "The node %s does not support removing a child",
7967 bdrv_get_device_or_node_name(parent_bs));
7968 return;
7969 }
7970
7971 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7972 if (tmp == child) {
7973 break;
7974 }
7975 }
7976
7977 if (!tmp) {
7978 error_setg(errp, "The node %s does not have a child named %s",
7979 bdrv_get_device_or_node_name(parent_bs),
7980 bdrv_get_device_or_node_name(child->bs));
7981 return;
7982 }
7983
7984 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7985}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007986
7987int bdrv_make_empty(BdrvChild *c, Error **errp)
7988{
7989 BlockDriver *drv = c->bs->drv;
7990 int ret;
7991
Emanuele Giuseppe Espositof791bf72022-03-03 10:15:49 -05007992 GLOBAL_STATE_CODE();
Max Reitz6f7a3b52020-04-29 16:11:23 +02007993 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7994
7995 if (!drv->bdrv_make_empty) {
7996 error_setg(errp, "%s does not support emptying nodes",
7997 drv->format_name);
7998 return -ENOTSUP;
7999 }
8000
8001 ret = drv->bdrv_make_empty(c->bs);
8002 if (ret < 0) {
8003 error_setg_errno(errp, -ret, "Failed to empty %s",
8004 c->bs->filename);
8005 return ret;
8006 }
8007
8008 return 0;
8009}
Max Reitz9a6fc882019-05-31 15:23:11 +02008010
8011/*
8012 * Return the child that @bs acts as an overlay for, and from which data may be
8013 * copied in COW or COR operations. Usually this is the backing file.
8014 */
8015BdrvChild *bdrv_cow_child(BlockDriverState *bs)
8016{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008017 IO_CODE();
8018
Max Reitz9a6fc882019-05-31 15:23:11 +02008019 if (!bs || !bs->drv) {
8020 return NULL;
8021 }
8022
8023 if (bs->drv->is_filter) {
8024 return NULL;
8025 }
8026
8027 if (!bs->backing) {
8028 return NULL;
8029 }
8030
8031 assert(bs->backing->role & BDRV_CHILD_COW);
8032 return bs->backing;
8033}
8034
8035/*
8036 * If @bs acts as a filter for exactly one of its children, return
8037 * that child.
8038 */
8039BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8040{
8041 BdrvChild *c;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008042 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008043
8044 if (!bs || !bs->drv) {
8045 return NULL;
8046 }
8047
8048 if (!bs->drv->is_filter) {
8049 return NULL;
8050 }
8051
8052 /* Only one of @backing or @file may be used */
8053 assert(!(bs->backing && bs->file));
8054
8055 c = bs->backing ?: bs->file;
8056 if (!c) {
8057 return NULL;
8058 }
8059
8060 assert(c->role & BDRV_CHILD_FILTERED);
8061 return c;
8062}
8063
8064/*
8065 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8066 * whichever is non-NULL.
8067 *
8068 * Return NULL if both are NULL.
8069 */
8070BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8071{
8072 BdrvChild *cow_child = bdrv_cow_child(bs);
8073 BdrvChild *filter_child = bdrv_filter_child(bs);
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008074 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008075
8076 /* Filter nodes cannot have COW backing files */
8077 assert(!(cow_child && filter_child));
8078
8079 return cow_child ?: filter_child;
8080}
8081
8082/*
8083 * Return the primary child of this node: For filters, that is the
8084 * filtered child. For other nodes, that is usually the child storing
8085 * metadata.
8086 * (A generally more helpful description is that this is (usually) the
8087 * child that has the same filename as @bs.)
8088 *
8089 * Drivers do not necessarily have a primary child; for example quorum
8090 * does not.
8091 */
8092BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8093{
8094 BdrvChild *c, *found = NULL;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008095 IO_CODE();
Max Reitz9a6fc882019-05-31 15:23:11 +02008096
8097 QLIST_FOREACH(c, &bs->children, next) {
8098 if (c->role & BDRV_CHILD_PRIMARY) {
8099 assert(!found);
8100 found = c;
8101 }
8102 }
8103
8104 return found;
8105}
Max Reitzd38d7eb2019-06-12 15:06:37 +02008106
8107static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8108 bool stop_on_explicit_filter)
8109{
8110 BdrvChild *c;
8111
8112 if (!bs) {
8113 return NULL;
8114 }
8115
8116 while (!(stop_on_explicit_filter && !bs->implicit)) {
8117 c = bdrv_filter_child(bs);
8118 if (!c) {
8119 /*
8120 * A filter that is embedded in a working block graph must
8121 * have a child. Assert this here so this function does
8122 * not return a filter node that is not expected by the
8123 * caller.
8124 */
8125 assert(!bs->drv || !bs->drv->is_filter);
8126 break;
8127 }
8128 bs = c->bs;
8129 }
8130 /*
8131 * Note that this treats nodes with bs->drv == NULL as not being
8132 * filters (bs->drv == NULL should be replaced by something else
8133 * anyway).
8134 * The advantage of this behavior is that this function will thus
8135 * always return a non-NULL value (given a non-NULL @bs).
8136 */
8137
8138 return bs;
8139}
8140
8141/*
8142 * Return the first BDS that has not been added implicitly or that
8143 * does not have a filtered child down the chain starting from @bs
8144 * (including @bs itself).
8145 */
8146BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8147{
Emanuele Giuseppe Espositob4ad82a2022-03-03 10:15:57 -05008148 GLOBAL_STATE_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008149 return bdrv_do_skip_filters(bs, true);
8150}
8151
8152/*
8153 * Return the first BDS that does not have a filtered child down the
8154 * chain starting from @bs (including @bs itself).
8155 */
8156BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8157{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008158 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008159 return bdrv_do_skip_filters(bs, false);
8160}
8161
8162/*
8163 * For a backing chain, return the first non-filter backing image of
8164 * the first non-filter image.
8165 */
8166BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8167{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008168 IO_CODE();
Max Reitzd38d7eb2019-06-12 15:06:37 +02008169 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8170}
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008171
8172/**
8173 * Check whether [offset, offset + bytes) overlaps with the cached
8174 * block-status data region.
8175 *
8176 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8177 * which is what bdrv_bsc_is_data()'s interface needs.
8178 * Otherwise, *pnum is not touched.
8179 */
8180static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8181 int64_t offset, int64_t bytes,
8182 int64_t *pnum)
8183{
8184 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8185 bool overlaps;
8186
8187 overlaps =
8188 qatomic_read(&bsc->valid) &&
8189 ranges_overlap(offset, bytes, bsc->data_start,
8190 bsc->data_end - bsc->data_start);
8191
8192 if (overlaps && pnum) {
8193 *pnum = bsc->data_end - offset;
8194 }
8195
8196 return overlaps;
8197}
8198
8199/**
8200 * See block_int.h for this function's documentation.
8201 */
8202bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8203{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008204 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008205 RCU_READ_LOCK_GUARD();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008206 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8207}
8208
8209/**
8210 * See block_int.h for this function's documentation.
8211 */
8212void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8213 int64_t offset, int64_t bytes)
8214{
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008215 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008216 RCU_READ_LOCK_GUARD();
8217
8218 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8219 qatomic_set(&bs->block_status_cache->valid, false);
8220 }
8221}
8222
8223/**
8224 * See block_int.h for this function's documentation.
8225 */
8226void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8227{
8228 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8229 BdrvBlockStatusCache *old_bsc;
Emanuele Giuseppe Esposito967d7902022-03-03 10:15:58 -05008230 IO_CODE();
Hanna Reitz0bc329f2021-08-12 10:41:44 +02008231
8232 *new_bsc = (BdrvBlockStatusCache) {
8233 .valid = true,
8234 .data_start = offset,
8235 .data_end = offset + bytes,
8236 };
8237
8238 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8239
8240 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8241 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8242 if (old_bsc) {
8243 g_free_rcu(old_bsc, rcu);
8244 }
8245}