blob: ca11078cd22f0832df5d9e80e2445ec161822a0e [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"
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +030052#include "block/coroutines.h"
bellardfc01f7e2003-06-30 10:03:06 +000053
Juan Quintela71e72a12009-07-27 16:12:56 +020054#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000055#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000056#include <sys/queue.h>
Joelle van Dynefeccdce2021-03-15 11:03:39 -070057#if defined(HAVE_SYS_DISK_H)
bellard7674e7b2005-04-26 21:59:26 +000058#include <sys/disk.h>
59#endif
blueswir1c5e97232009-03-07 20:06:23 +000060#endif
bellard7674e7b2005-04-26 21:59:26 +000061
aliguori49dc7682009-03-08 16:26:59 +000062#ifdef _WIN32
63#include <windows.h>
64#endif
65
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010066#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
67
Benoît Canetdc364f42014-01-23 21:31:32 +010068static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
69 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
70
Max Reitz2c1d04e2016-01-29 16:36:11 +010071static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
72 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
73
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010074static QLIST_HEAD(, BlockDriver) bdrv_drivers =
75 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000076
Max Reitz5b363932016-05-17 16:41:31 +020077static BlockDriverState *bdrv_open_inherit(const char *filename,
78 const char *reference,
79 QDict *options, int flags,
80 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +020081 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +020082 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +020083 Error **errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +020084
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +030085static void bdrv_replace_child_noperm(BdrvChild *child,
86 BlockDriverState *new_bs);
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +030087static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
88 BdrvChild *child,
89 Transaction *tran);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +030090static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
91 Transaction *tran);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +030092
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +030093static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
94 BlockReopenQueue *queue,
95 Transaction *set_backings_tran, Error **errp);
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +030096static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
97static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
98
Markus Armbrustereb852012009-10-27 18:41:44 +010099/* If non-zero, use only whitelisted block drivers */
100static int use_bdrv_whitelist;
101
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000102#ifdef _WIN32
103static int is_windows_drive_prefix(const char *filename)
104{
105 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
106 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
107 filename[1] == ':');
108}
109
110int is_windows_drive(const char *filename)
111{
112 if (is_windows_drive_prefix(filename) &&
113 filename[2] == '\0')
114 return 1;
115 if (strstart(filename, "\\\\.\\", NULL) ||
116 strstart(filename, "//./", NULL))
117 return 1;
118 return 0;
119}
120#endif
121
Kevin Wolf339064d2013-11-28 10:23:32 +0100122size_t bdrv_opt_mem_align(BlockDriverState *bs)
123{
124 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300125 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800126 return MAX(4096, qemu_real_host_page_size);
Kevin Wolf339064d2013-11-28 10:23:32 +0100127 }
128
129 return bs->bl.opt_mem_alignment;
130}
131
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300132size_t bdrv_min_mem_align(BlockDriverState *bs)
133{
134 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300135 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800136 return MAX(4096, qemu_real_host_page_size);
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300137 }
138
139 return bs->bl.min_mem_alignment;
140}
141
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000142/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100143int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000144{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200145 const char *p;
146
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000147#ifdef _WIN32
148 if (is_windows_drive(path) ||
149 is_windows_drive_prefix(path)) {
150 return 0;
151 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200152 p = path + strcspn(path, ":/\\");
153#else
154 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000155#endif
156
Paolo Bonzini947995c2012-05-08 16:51:48 +0200157 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000158}
159
bellard83f64092006-08-01 16:21:11 +0000160int path_is_absolute(const char *path)
161{
bellard21664422007-01-07 18:22:37 +0000162#ifdef _WIN32
163 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200164 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000165 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200166 }
167 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000168#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200169 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000170#endif
bellard83f64092006-08-01 16:21:11 +0000171}
172
Max Reitz009b03a2019-02-01 20:29:13 +0100173/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000174 path to it by considering it is relative to base_path. URL are
175 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100176char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000177{
Max Reitz009b03a2019-02-01 20:29:13 +0100178 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000179 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100180 char *result;
bellard83f64092006-08-01 16:21:11 +0000181 int len;
182
bellard83f64092006-08-01 16:21:11 +0000183 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100184 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000185 }
Max Reitz009b03a2019-02-01 20:29:13 +0100186
187 if (path_has_protocol(base_path)) {
188 protocol_stripped = strchr(base_path, ':');
189 if (protocol_stripped) {
190 protocol_stripped++;
191 }
192 }
193 p = protocol_stripped ?: base_path;
194
195 p1 = strrchr(base_path, '/');
196#ifdef _WIN32
197 {
198 const char *p2;
199 p2 = strrchr(base_path, '\\');
200 if (!p1 || p2 > p1) {
201 p1 = p2;
202 }
203 }
204#endif
205 if (p1) {
206 p1++;
207 } else {
208 p1 = base_path;
209 }
210 if (p1 > p) {
211 p = p1;
212 }
213 len = p - base_path;
214
215 result = g_malloc(len + strlen(filename) + 1);
216 memcpy(result, base_path, len);
217 strcpy(result + len, filename);
218
219 return result;
220}
221
Max Reitz03c320d2017-05-22 21:52:16 +0200222/*
223 * Helper function for bdrv_parse_filename() implementations to remove optional
224 * protocol prefixes (especially "file:") from a filename and for putting the
225 * stripped filename into the options QDict if there is such a prefix.
226 */
227void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
228 QDict *options)
229{
230 if (strstart(filename, prefix, &filename)) {
231 /* Stripping the explicit protocol prefix may result in a protocol
232 * prefix being (wrongly) detected (if the filename contains a colon) */
233 if (path_has_protocol(filename)) {
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100234 GString *fat_filename;
Max Reitz03c320d2017-05-22 21:52:16 +0200235
236 /* This means there is some colon before the first slash; therefore,
237 * this cannot be an absolute path */
238 assert(!path_is_absolute(filename));
239
240 /* And we can thus fix the protocol detection issue by prefixing it
241 * by "./" */
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100242 fat_filename = g_string_new("./");
243 g_string_append(fat_filename, filename);
Max Reitz03c320d2017-05-22 21:52:16 +0200244
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100245 assert(!path_has_protocol(fat_filename->str));
Max Reitz03c320d2017-05-22 21:52:16 +0200246
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100247 qdict_put(options, "filename",
248 qstring_from_gstring(fat_filename));
Max Reitz03c320d2017-05-22 21:52:16 +0200249 } else {
250 /* If no protocol prefix was detected, we can use the shortened
251 * filename as-is */
252 qdict_put_str(options, "filename", filename);
253 }
254 }
255}
256
257
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200258/* Returns whether the image file is opened as read-only. Note that this can
259 * return false and writing to the image file is still not possible because the
260 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400261bool bdrv_is_read_only(BlockDriverState *bs)
262{
Vladimir Sementsov-Ogievskiy975da072021-05-27 18:40:55 +0300263 return !(bs->open_flags & BDRV_O_RDWR);
Jeff Cody93ed5242017-04-07 16:55:28 -0400264}
265
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200266int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
267 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400268{
Jeff Codye2b82472017-04-07 16:55:26 -0400269 /* Do not set read_only if copy_on_read is enabled */
270 if (bs->copy_on_read && read_only) {
271 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
272 bdrv_get_device_or_node_name(bs));
273 return -EINVAL;
274 }
275
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400276 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200277 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
278 !ignore_allow_rdw)
279 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400280 error_setg(errp, "Node '%s' is read only",
281 bdrv_get_device_or_node_name(bs));
282 return -EPERM;
283 }
284
Jeff Cody45803a02017-04-07 16:55:29 -0400285 return 0;
286}
287
Kevin Wolfeaa24102018-10-12 11:27:41 +0200288/*
289 * Called by a driver that can only provide a read-only image.
290 *
291 * Returns 0 if the node is already read-only or it could switch the node to
292 * read-only because BDRV_O_AUTO_RDONLY is set.
293 *
294 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
295 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
296 * is not NULL, it is used as the error message for the Error object.
297 */
298int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
299 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400300{
301 int ret = 0;
302
Kevin Wolfeaa24102018-10-12 11:27:41 +0200303 if (!(bs->open_flags & BDRV_O_RDWR)) {
304 return 0;
305 }
306 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
307 goto fail;
308 }
309
310 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400311 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200312 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400313 }
314
Kevin Wolfeaa24102018-10-12 11:27:41 +0200315 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200316
Jeff Codye2b82472017-04-07 16:55:26 -0400317 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200318
319fail:
320 error_setg(errp, "%s", errmsg ?: "Image is read-only");
321 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400322}
323
Max Reitz645ae7d2019-02-01 20:29:14 +0100324/*
325 * If @backing is empty, this function returns NULL without setting
326 * @errp. In all other cases, NULL will only be returned with @errp
327 * set.
328 *
329 * Therefore, a return value of NULL without @errp set means that
330 * there is no backing file; if @errp is set, there is one but its
331 * absolute filename cannot be generated.
332 */
333char *bdrv_get_full_backing_filename_from_filename(const char *backed,
334 const char *backing,
335 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100336{
Max Reitz645ae7d2019-02-01 20:29:14 +0100337 if (backing[0] == '\0') {
338 return NULL;
339 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
340 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100341 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
342 error_setg(errp, "Cannot use relative backing file names for '%s'",
343 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100344 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100345 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100346 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100347 }
348}
349
Max Reitz9f4793d2019-02-01 20:29:16 +0100350/*
351 * If @filename is empty or NULL, this function returns NULL without
352 * setting @errp. In all other cases, NULL will only be returned with
353 * @errp set.
354 */
355static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
356 const char *filename, Error **errp)
357{
Max Reitz8df68612019-02-01 20:29:23 +0100358 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100359
Max Reitz8df68612019-02-01 20:29:23 +0100360 if (!filename || filename[0] == '\0') {
361 return NULL;
362 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
363 return g_strdup(filename);
364 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100365
Max Reitz8df68612019-02-01 20:29:23 +0100366 dir = bdrv_dirname(relative_to, errp);
367 if (!dir) {
368 return NULL;
369 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100370
Max Reitz8df68612019-02-01 20:29:23 +0100371 full_name = g_strconcat(dir, filename, NULL);
372 g_free(dir);
373 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100374}
375
Max Reitz6b6833c2019-02-01 20:29:15 +0100376char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200377{
Max Reitz9f4793d2019-02-01 20:29:16 +0100378 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200379}
380
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100381void bdrv_register(BlockDriver *bdrv)
382{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100383 assert(bdrv->format_name);
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100384 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000385}
bellardb3380822004-03-14 21:38:54 +0000386
Markus Armbrustere4e99862014-10-07 13:59:03 +0200387BlockDriverState *bdrv_new(void)
388{
389 BlockDriverState *bs;
390 int i;
391
Markus Armbruster5839e532014-08-19 10:31:08 +0200392 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800393 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800394 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
395 QLIST_INIT(&bs->op_blockers[i]);
396 }
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200397 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200398 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800399 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200400 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200401
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300402 qemu_co_queue_init(&bs->flush_queue);
403
Kevin Wolf0f122642018-03-28 18:29:18 +0200404 for (i = 0; i < bdrv_drain_all_count; i++) {
405 bdrv_drained_begin(bs);
406 }
407
Max Reitz2c1d04e2016-01-29 16:36:11 +0100408 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
409
bellardb3380822004-03-14 21:38:54 +0000410 return bs;
411}
412
Marc Mari88d88792016-08-12 09:27:03 -0400413static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000414{
415 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400416
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100417 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
418 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000419 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100420 }
bellardea2384d2004-08-01 21:59:26 +0000421 }
Marc Mari88d88792016-08-12 09:27:03 -0400422
bellardea2384d2004-08-01 21:59:26 +0000423 return NULL;
424}
425
Marc Mari88d88792016-08-12 09:27:03 -0400426BlockDriver *bdrv_find_format(const char *format_name)
427{
428 BlockDriver *drv1;
429 int i;
430
431 drv1 = bdrv_do_find_format(format_name);
432 if (drv1) {
433 return drv1;
434 }
435
436 /* The driver isn't registered, maybe we need to load a module */
437 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
438 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
439 block_module_load_one(block_driver_modules[i].library_name);
440 break;
441 }
442 }
443
444 return bdrv_do_find_format(format_name);
445}
446
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300447static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100448{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800449 static const char *whitelist_rw[] = {
450 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200451 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800452 };
453 static const char *whitelist_ro[] = {
454 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200455 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100456 };
457 const char **p;
458
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800459 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100460 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800461 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100462
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800463 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300464 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100465 return 1;
466 }
467 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800468 if (read_only) {
469 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300470 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800471 return 1;
472 }
473 }
474 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100475 return 0;
476}
477
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300478int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
479{
480 return bdrv_format_is_whitelisted(drv->format_name, read_only);
481}
482
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000483bool bdrv_uses_whitelist(void)
484{
485 return use_bdrv_whitelist;
486}
487
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800488typedef struct CreateCo {
489 BlockDriver *drv;
490 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800491 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800492 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200493 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800494} CreateCo;
495
496static void coroutine_fn bdrv_create_co_entry(void *opaque)
497{
Max Reitzcc84d902013-09-06 17:14:26 +0200498 Error *local_err = NULL;
499 int ret;
500
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800501 CreateCo *cco = opaque;
502 assert(cco->drv);
503
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200504 ret = cco->drv->bdrv_co_create_opts(cco->drv,
505 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300506 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200507 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800508}
509
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200510int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800511 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000512{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800513 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200514
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800515 Coroutine *co;
516 CreateCo cco = {
517 .drv = drv,
518 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800519 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800520 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200521 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800522 };
523
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100524 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200525 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300526 ret = -ENOTSUP;
527 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800528 }
529
530 if (qemu_in_coroutine()) {
531 /* Fast-path if already in coroutine context */
532 bdrv_create_co_entry(&cco);
533 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200534 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
535 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800536 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200537 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800538 }
539 }
540
541 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200542 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100543 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200544 error_propagate(errp, cco.err);
545 } else {
546 error_setg_errno(errp, -ret, "Could not create image");
547 }
548 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800549
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300550out:
551 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800552 return ret;
bellardea2384d2004-08-01 21:59:26 +0000553}
554
Max Reitzfd171462020-01-22 17:45:29 +0100555/**
556 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
557 * least the given @minimum_size.
558 *
559 * On success, return @blk's actual length.
560 * Otherwise, return -errno.
561 */
562static int64_t create_file_fallback_truncate(BlockBackend *blk,
563 int64_t minimum_size, Error **errp)
564{
565 Error *local_err = NULL;
566 int64_t size;
567 int ret;
568
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200569 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
570 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100571 if (ret < 0 && ret != -ENOTSUP) {
572 error_propagate(errp, local_err);
573 return ret;
574 }
575
576 size = blk_getlength(blk);
577 if (size < 0) {
578 error_free(local_err);
579 error_setg_errno(errp, -size,
580 "Failed to inquire the new image file's length");
581 return size;
582 }
583
584 if (size < minimum_size) {
585 /* Need to grow the image, but we failed to do that */
586 error_propagate(errp, local_err);
587 return -ENOTSUP;
588 }
589
590 error_free(local_err);
591 local_err = NULL;
592
593 return size;
594}
595
596/**
597 * Helper function for bdrv_create_file_fallback(): Zero the first
598 * sector to remove any potentially pre-existing image header.
599 */
600static int create_file_fallback_zero_first_sector(BlockBackend *blk,
601 int64_t current_size,
602 Error **errp)
603{
604 int64_t bytes_to_clear;
605 int ret;
606
607 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
608 if (bytes_to_clear) {
609 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
610 if (ret < 0) {
611 error_setg_errno(errp, -ret,
612 "Failed to clear the new image's first sector");
613 return ret;
614 }
615 }
616
617 return 0;
618}
619
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200620/**
621 * Simple implementation of bdrv_co_create_opts for protocol drivers
622 * which only support creation via opening a file
623 * (usually existing raw storage device)
624 */
625int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
626 const char *filename,
627 QemuOpts *opts,
628 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100629{
630 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100631 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100632 int64_t size = 0;
633 char *buf = NULL;
634 PreallocMode prealloc;
635 Error *local_err = NULL;
636 int ret;
637
638 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
639 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
640 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
641 PREALLOC_MODE_OFF, &local_err);
642 g_free(buf);
643 if (local_err) {
644 error_propagate(errp, local_err);
645 return -EINVAL;
646 }
647
648 if (prealloc != PREALLOC_MODE_OFF) {
649 error_setg(errp, "Unsupported preallocation mode '%s'",
650 PreallocMode_str(prealloc));
651 return -ENOTSUP;
652 }
653
Max Reitzeeea1fa2020-02-25 16:56:18 +0100654 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100655 qdict_put_str(options, "driver", drv->format_name);
656
657 blk = blk_new_open(filename, NULL, options,
658 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
659 if (!blk) {
660 error_prepend(errp, "Protocol driver '%s' does not support image "
661 "creation, and opening the image failed: ",
662 drv->format_name);
663 return -EINVAL;
664 }
665
666 size = create_file_fallback_truncate(blk, size, errp);
667 if (size < 0) {
668 ret = size;
669 goto out;
670 }
671
672 ret = create_file_fallback_zero_first_sector(blk, size, errp);
673 if (ret < 0) {
674 goto out;
675 }
676
677 ret = 0;
678out:
679 blk_unref(blk);
680 return ret;
681}
682
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800683int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200684{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100685 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200686 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100687 QDict *qdict;
688 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200689
Max Reitzb65a5e12015-02-05 13:58:12 -0500690 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200691 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000692 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200693 }
694
Stefano Garzarella729222a2021-03-08 17:12:32 +0100695 if (!drv->create_opts) {
696 error_setg(errp, "Driver '%s' does not support image creation",
697 drv->format_name);
698 return -ENOTSUP;
699 }
700
701 /*
702 * 'opts' contains a QemuOptsList with a combination of format and protocol
703 * default values.
704 *
705 * The format properly removes its options, but the default values remain
706 * in 'opts->list'. So if the protocol has options with the same name
707 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
708 * of the format, since for overlapping options, the format wins.
709 *
710 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
711 * only the set options, and then convert it back to QemuOpts, using the
712 * create_opts of the protocol. So the new QemuOpts, will contain only the
713 * protocol defaults.
714 */
715 qdict = qemu_opts_to_qdict(opts, NULL);
716 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
717 if (protocol_opts == NULL) {
718 ret = -EINVAL;
719 goto out;
720 }
721
722 ret = bdrv_create(drv, filename, protocol_opts, errp);
723out:
724 qemu_opts_del(protocol_opts);
725 qobject_unref(qdict);
726 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200727}
728
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300729int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
730{
731 Error *local_err = NULL;
732 int ret;
733
734 assert(bs != NULL);
735
736 if (!bs->drv) {
737 error_setg(errp, "Block node '%s' is not opened", bs->filename);
738 return -ENOMEDIUM;
739 }
740
741 if (!bs->drv->bdrv_co_delete_file) {
742 error_setg(errp, "Driver '%s' does not support image deletion",
743 bs->drv->format_name);
744 return -ENOTSUP;
745 }
746
747 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
748 if (ret < 0) {
749 error_propagate(errp, local_err);
750 }
751
752 return ret;
753}
754
Maxim Levitskya890f082020-12-17 19:09:03 +0200755void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
756{
757 Error *local_err = NULL;
758 int ret;
759
760 if (!bs) {
761 return;
762 }
763
764 ret = bdrv_co_delete_file(bs, &local_err);
765 /*
766 * ENOTSUP will happen if the block driver doesn't support
767 * the 'bdrv_co_delete_file' interface. This is a predictable
768 * scenario and shouldn't be reported back to the user.
769 */
770 if (ret == -ENOTSUP) {
771 error_free(local_err);
772 } else if (ret < 0) {
773 error_report_err(local_err);
774 }
775}
776
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100777/**
778 * Try to get @bs's logical and physical block size.
779 * On success, store them in @bsz struct and return 0.
780 * On failure return -errno.
781 * @bs must not be empty.
782 */
783int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
784{
785 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200786 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100787
788 if (drv && drv->bdrv_probe_blocksizes) {
789 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200790 } else if (filtered) {
791 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100792 }
793
794 return -ENOTSUP;
795}
796
797/**
798 * Try to get @bs's geometry (cyls, heads, sectors).
799 * On success, store them in @geo struct and return 0.
800 * On failure return -errno.
801 * @bs must not be empty.
802 */
803int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
804{
805 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200806 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100807
808 if (drv && drv->bdrv_probe_geometry) {
809 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200810 } else if (filtered) {
811 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100812 }
813
814 return -ENOTSUP;
815}
816
Jim Meyeringeba25052012-05-28 09:27:54 +0200817/*
818 * Create a uniquely-named empty temporary file.
819 * Return 0 upon success, otherwise a negative errno value.
820 */
821int get_tmp_filename(char *filename, int size)
822{
bellardd5249392004-08-03 21:14:23 +0000823#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000824 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200825 /* GetTempFileName requires that its output buffer (4th param)
826 have length MAX_PATH or greater. */
827 assert(size >= MAX_PATH);
828 return (GetTempPath(MAX_PATH, temp_dir)
829 && GetTempFileName(temp_dir, "qem", 0, filename)
830 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000831#else
bellardea2384d2004-08-01 21:59:26 +0000832 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000833 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000834 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530835 if (!tmpdir) {
836 tmpdir = "/var/tmp";
837 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200838 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
839 return -EOVERFLOW;
840 }
bellardea2384d2004-08-01 21:59:26 +0000841 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800842 if (fd < 0) {
843 return -errno;
844 }
845 if (close(fd) != 0) {
846 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200847 return -errno;
848 }
849 return 0;
bellardd5249392004-08-03 21:14:23 +0000850#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200851}
bellardea2384d2004-08-01 21:59:26 +0000852
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200853/*
854 * Detect host devices. By convention, /dev/cdrom[N] is always
855 * recognized as a host CDROM.
856 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200857static BlockDriver *find_hdev_driver(const char *filename)
858{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200859 int score_max = 0, score;
860 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200861
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100862 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200863 if (d->bdrv_probe_device) {
864 score = d->bdrv_probe_device(filename);
865 if (score > score_max) {
866 score_max = score;
867 drv = d;
868 }
869 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200870 }
871
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200872 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200873}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200874
Marc Mari88d88792016-08-12 09:27:03 -0400875static BlockDriver *bdrv_do_find_protocol(const char *protocol)
876{
877 BlockDriver *drv1;
878
879 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
880 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
881 return drv1;
882 }
883 }
884
885 return NULL;
886}
887
Kevin Wolf98289622013-07-10 15:47:39 +0200888BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500889 bool allow_protocol_prefix,
890 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200891{
892 BlockDriver *drv1;
893 char protocol[128];
894 int len;
895 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400896 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200897
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200898 /* TODO Drivers without bdrv_file_open must be specified explicitly */
899
Christoph Hellwig39508e72010-06-23 12:25:17 +0200900 /*
901 * XXX(hch): we really should not let host device detection
902 * override an explicit protocol specification, but moving this
903 * later breaks access to device names with colons in them.
904 * Thanks to the brain-dead persistent naming schemes on udev-
905 * based Linux systems those actually are quite common.
906 */
907 drv1 = find_hdev_driver(filename);
908 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200909 return drv1;
910 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200911
Kevin Wolf98289622013-07-10 15:47:39 +0200912 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100913 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200914 }
Kevin Wolf98289622013-07-10 15:47:39 +0200915
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000916 p = strchr(filename, ':');
917 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200918 len = p - filename;
919 if (len > sizeof(protocol) - 1)
920 len = sizeof(protocol) - 1;
921 memcpy(protocol, filename, len);
922 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400923
924 drv1 = bdrv_do_find_protocol(protocol);
925 if (drv1) {
926 return drv1;
927 }
928
929 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
930 if (block_driver_modules[i].protocol_name &&
931 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
932 block_module_load_one(block_driver_modules[i].library_name);
933 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200934 }
935 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500936
Marc Mari88d88792016-08-12 09:27:03 -0400937 drv1 = bdrv_do_find_protocol(protocol);
938 if (!drv1) {
939 error_setg(errp, "Unknown protocol '%s'", protocol);
940 }
941 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200942}
943
Markus Armbrusterc6684242014-11-20 16:27:10 +0100944/*
945 * Guess image format by probing its contents.
946 * This is not a good idea when your image is raw (CVE-2008-2004), but
947 * we do it anyway for backward compatibility.
948 *
949 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100950 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
951 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100952 * @filename is its filename.
953 *
954 * For all block drivers, call the bdrv_probe() method to get its
955 * probing score.
956 * Return the first block driver with the highest probing score.
957 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100958BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
959 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100960{
961 int score_max = 0, score;
962 BlockDriver *drv = NULL, *d;
963
964 QLIST_FOREACH(d, &bdrv_drivers, list) {
965 if (d->bdrv_probe) {
966 score = d->bdrv_probe(buf, buf_size, filename);
967 if (score > score_max) {
968 score_max = score;
969 drv = d;
970 }
971 }
972 }
973
974 return drv;
975}
976
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100977static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200978 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000979{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100980 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100981 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100982 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700983
Kevin Wolf08a00552010-06-01 18:37:31 +0200984 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100985 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100986 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200987 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700988 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700989
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100990 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +0000991 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200992 error_setg_errno(errp, -ret, "Could not read image for determining its "
993 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +0200994 *pdrv = NULL;
995 return ret;
bellard83f64092006-08-01 16:21:11 +0000996 }
997
Markus Armbrusterc6684242014-11-20 16:27:10 +0100998 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +0200999 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001000 error_setg(errp, "Could not determine image format: No compatible "
1001 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +02001002 ret = -ENOENT;
1003 }
1004 *pdrv = drv;
1005 return ret;
bellardea2384d2004-08-01 21:59:26 +00001006}
1007
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001008/**
1009 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001010 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001011 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001012int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001013{
1014 BlockDriver *drv = bs->drv;
1015
Max Reitzd470ad42017-11-10 21:31:09 +01001016 if (!drv) {
1017 return -ENOMEDIUM;
1018 }
1019
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001020 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001021 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001022 return 0;
1023
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001024 /* query actual device if possible, otherwise just trust the hint */
1025 if (drv->bdrv_getlength) {
1026 int64_t length = drv->bdrv_getlength(bs);
1027 if (length < 0) {
1028 return length;
1029 }
Fam Zheng7e382002013-11-06 19:48:06 +08001030 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001031 }
1032
1033 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001034
1035 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1036 return -EFBIG;
1037 }
1038
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001039 return 0;
1040}
1041
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001042/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001043 * Combines a QDict of new block driver @options with any missing options taken
1044 * from @old_options, so that leaving out an option defaults to its old value.
1045 */
1046static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1047 QDict *old_options)
1048{
1049 if (bs->drv && bs->drv->bdrv_join_options) {
1050 bs->drv->bdrv_join_options(options, old_options);
1051 } else {
1052 qdict_join(options, old_options, false);
1053 }
1054}
1055
Alberto Garcia543770b2018-09-06 12:37:09 +03001056static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1057 int open_flags,
1058 Error **errp)
1059{
1060 Error *local_err = NULL;
1061 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1062 BlockdevDetectZeroesOptions detect_zeroes =
1063 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1064 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1065 g_free(value);
1066 if (local_err) {
1067 error_propagate(errp, local_err);
1068 return detect_zeroes;
1069 }
1070
1071 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1072 !(open_flags & BDRV_O_UNMAP))
1073 {
1074 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1075 "without setting discard operation to unmap");
1076 }
1077
1078 return detect_zeroes;
1079}
1080
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001081/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001082 * Set open flags for aio engine
1083 *
1084 * Return 0 on success, -1 if the engine specified is invalid
1085 */
1086int bdrv_parse_aio(const char *mode, int *flags)
1087{
1088 if (!strcmp(mode, "threads")) {
1089 /* do nothing, default */
1090 } else if (!strcmp(mode, "native")) {
1091 *flags |= BDRV_O_NATIVE_AIO;
1092#ifdef CONFIG_LINUX_IO_URING
1093 } else if (!strcmp(mode, "io_uring")) {
1094 *flags |= BDRV_O_IO_URING;
1095#endif
1096 } else {
1097 return -1;
1098 }
1099
1100 return 0;
1101}
1102
1103/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001104 * Set open flags for a given discard mode
1105 *
1106 * Return 0 on success, -1 if the discard mode was invalid.
1107 */
1108int bdrv_parse_discard_flags(const char *mode, int *flags)
1109{
1110 *flags &= ~BDRV_O_UNMAP;
1111
1112 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1113 /* do nothing */
1114 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1115 *flags |= BDRV_O_UNMAP;
1116 } else {
1117 return -1;
1118 }
1119
1120 return 0;
1121}
1122
1123/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001124 * Set open flags for a given cache mode
1125 *
1126 * Return 0 on success, -1 if the cache mode was invalid.
1127 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001128int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001129{
1130 *flags &= ~BDRV_O_CACHE_MASK;
1131
1132 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001133 *writethrough = false;
1134 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001135 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001136 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001137 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001138 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001139 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001140 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001141 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001142 *flags |= BDRV_O_NO_FLUSH;
1143 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001144 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001145 } else {
1146 return -1;
1147 }
1148
1149 return 0;
1150}
1151
Kevin Wolfb5411552017-01-17 15:56:16 +01001152static char *bdrv_child_get_parent_desc(BdrvChild *c)
1153{
1154 BlockDriverState *parent = c->opaque;
Vladimir Sementsov-Ogievskiy2c0a3ac2021-06-01 10:52:15 +03001155 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
Kevin Wolfb5411552017-01-17 15:56:16 +01001156}
1157
Kevin Wolf20018e12016-05-23 18:46:59 +02001158static void bdrv_child_cb_drained_begin(BdrvChild *child)
1159{
1160 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001161 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001162}
1163
Kevin Wolf89bd0302018-03-22 14:11:20 +01001164static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1165{
1166 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001167 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001168}
1169
Max Reitze037c092019-07-19 11:26:14 +02001170static void bdrv_child_cb_drained_end(BdrvChild *child,
1171 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001172{
1173 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001174 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001175}
1176
Kevin Wolf38701b62017-05-04 18:52:39 +02001177static int bdrv_child_cb_inactivate(BdrvChild *child)
1178{
1179 BlockDriverState *bs = child->opaque;
1180 assert(bs->open_flags & BDRV_O_INACTIVE);
1181 return 0;
1182}
1183
Kevin Wolf5d231842019-05-06 19:17:56 +02001184static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1185 GSList **ignore, Error **errp)
1186{
1187 BlockDriverState *bs = child->opaque;
1188 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1189}
1190
Kevin Wolf53a7d042019-05-06 19:17:59 +02001191static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1192 GSList **ignore)
1193{
1194 BlockDriverState *bs = child->opaque;
1195 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1196}
1197
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001198/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001199 * Returns the options and flags that a temporary snapshot should get, based on
1200 * the originally requested flags (the originally requested image will have
1201 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001202 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001203static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1204 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001205{
Kevin Wolf73176be2016-03-07 13:02:15 +01001206 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1207
1208 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001209 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1210 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001211
Kevin Wolf3f486862019-04-04 17:04:43 +02001212 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001213 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001214 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001215
Kevin Wolf41869042016-06-16 12:59:30 +02001216 /* aio=native doesn't work for cache.direct=off, so disable it for the
1217 * temporary snapshot */
1218 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001219}
1220
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001221static void bdrv_backing_attach(BdrvChild *c)
1222{
1223 BlockDriverState *parent = c->opaque;
1224 BlockDriverState *backing_hd = c->bs;
1225
1226 assert(!parent->backing_blocker);
1227 error_setg(&parent->backing_blocker,
1228 "node is used as backing hd of '%s'",
1229 bdrv_get_device_or_node_name(parent));
1230
Max Reitzf30c66b2019-02-01 20:29:05 +01001231 bdrv_refresh_filename(backing_hd);
1232
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001233 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001234
1235 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1236 /* Otherwise we won't be able to commit or stream */
1237 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1238 parent->backing_blocker);
1239 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1240 parent->backing_blocker);
1241 /*
1242 * We do backup in 3 ways:
1243 * 1. drive backup
1244 * The target bs is new opened, and the source is top BDS
1245 * 2. blockdev backup
1246 * Both the source and the target are top BDSes.
1247 * 3. internal backup(used for block replication)
1248 * Both the source and the target are backing file
1249 *
1250 * In case 1 and 2, neither the source nor the target is the backing file.
1251 * In case 3, we will block the top BDS, so there is only one block job
1252 * for the top BDS and its backing chain.
1253 */
1254 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1255 parent->backing_blocker);
1256 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1257 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001258}
Kevin Wolfd736f112017-12-18 16:05:48 +01001259
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001260static void bdrv_backing_detach(BdrvChild *c)
1261{
1262 BlockDriverState *parent = c->opaque;
1263
1264 assert(parent->backing_blocker);
1265 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1266 error_free(parent->backing_blocker);
1267 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001268}
Kevin Wolfd736f112017-12-18 16:05:48 +01001269
Kevin Wolf6858eba2017-06-29 19:32:21 +02001270static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1271 const char *filename, Error **errp)
1272{
1273 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001274 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001275 int ret;
1276
Alberto Garciae94d3db2018-11-12 16:00:34 +02001277 if (read_only) {
1278 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001279 if (ret < 0) {
1280 return ret;
1281 }
1282 }
1283
Kevin Wolf6858eba2017-06-29 19:32:21 +02001284 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001285 base->drv ? base->drv->format_name : "",
1286 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001287 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001288 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001289 }
1290
Alberto Garciae94d3db2018-11-12 16:00:34 +02001291 if (read_only) {
1292 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001293 }
1294
Kevin Wolf6858eba2017-06-29 19:32:21 +02001295 return ret;
1296}
1297
Max Reitzfae8bd32020-05-13 13:05:20 +02001298/*
1299 * Returns the options and flags that a generic child of a BDS should
1300 * get, based on the given options and flags for the parent BDS.
1301 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001302static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1303 int *child_flags, QDict *child_options,
1304 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001305{
1306 int flags = parent_flags;
1307
1308 /*
1309 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1310 * Generally, the question to answer is: Should this child be
1311 * format-probed by default?
1312 */
1313
1314 /*
1315 * Pure and non-filtered data children of non-format nodes should
1316 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1317 * set). This only affects a very limited set of drivers (namely
1318 * quorum and blkverify when this comment was written).
1319 * Force-clear BDRV_O_PROTOCOL then.
1320 */
1321 if (!parent_is_format &&
1322 (role & BDRV_CHILD_DATA) &&
1323 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1324 {
1325 flags &= ~BDRV_O_PROTOCOL;
1326 }
1327
1328 /*
1329 * All children of format nodes (except for COW children) and all
1330 * metadata children in general should never be format-probed.
1331 * Force-set BDRV_O_PROTOCOL then.
1332 */
1333 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1334 (role & BDRV_CHILD_METADATA))
1335 {
1336 flags |= BDRV_O_PROTOCOL;
1337 }
1338
1339 /*
1340 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1341 * the parent.
1342 */
1343 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1344 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1345 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1346
1347 if (role & BDRV_CHILD_COW) {
1348 /* backing files are opened read-only by default */
1349 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1350 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1351 } else {
1352 /* Inherit the read-only option from the parent if it's not set */
1353 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1354 qdict_copy_default(child_options, parent_options,
1355 BDRV_OPT_AUTO_READ_ONLY);
1356 }
1357
1358 /*
1359 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1360 * can default to enable it on lower layers regardless of the
1361 * parent option.
1362 */
1363 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1364
1365 /* Clear flags that only apply to the top layer */
1366 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1367
1368 if (role & BDRV_CHILD_METADATA) {
1369 flags &= ~BDRV_O_NO_IO;
1370 }
1371 if (role & BDRV_CHILD_COW) {
1372 flags &= ~BDRV_O_TEMPORARY;
1373 }
1374
1375 *child_flags = flags;
1376}
1377
Max Reitzca2f1232020-05-13 13:05:22 +02001378static void bdrv_child_cb_attach(BdrvChild *child)
1379{
1380 BlockDriverState *bs = child->opaque;
1381
1382 if (child->role & BDRV_CHILD_COW) {
1383 bdrv_backing_attach(child);
1384 }
1385
1386 bdrv_apply_subtree_drain(child, bs);
1387}
1388
Max Reitz48e08282020-05-13 13:05:23 +02001389static void bdrv_child_cb_detach(BdrvChild *child)
1390{
1391 BlockDriverState *bs = child->opaque;
1392
1393 if (child->role & BDRV_CHILD_COW) {
1394 bdrv_backing_detach(child);
1395 }
1396
1397 bdrv_unapply_subtree_drain(child, bs);
1398}
1399
Max Reitz43483552020-05-13 13:05:24 +02001400static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1401 const char *filename, Error **errp)
1402{
1403 if (c->role & BDRV_CHILD_COW) {
1404 return bdrv_backing_update_filename(c, base, filename, errp);
1405 }
1406 return 0;
1407}
1408
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001409AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001410{
1411 BlockDriverState *bs = c->opaque;
1412
1413 return bdrv_get_aio_context(bs);
1414}
1415
Max Reitz43483552020-05-13 13:05:24 +02001416const BdrvChildClass child_of_bds = {
1417 .parent_is_bds = true,
1418 .get_parent_desc = bdrv_child_get_parent_desc,
1419 .inherit_options = bdrv_inherited_options,
1420 .drained_begin = bdrv_child_cb_drained_begin,
1421 .drained_poll = bdrv_child_cb_drained_poll,
1422 .drained_end = bdrv_child_cb_drained_end,
1423 .attach = bdrv_child_cb_attach,
1424 .detach = bdrv_child_cb_detach,
1425 .inactivate = bdrv_child_cb_inactivate,
1426 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1427 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1428 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiyfb62b582021-05-24 13:12:56 +03001429 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001430};
1431
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001432AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1433{
1434 return c->klass->get_parent_aio_context(c);
1435}
1436
Kevin Wolf7b272452012-11-12 17:05:39 +01001437static int bdrv_open_flags(BlockDriverState *bs, int flags)
1438{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001439 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001440
1441 /*
1442 * Clear flags that are internal to the block layer before opening the
1443 * image.
1444 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001445 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001446
Kevin Wolf7b272452012-11-12 17:05:39 +01001447 return open_flags;
1448}
1449
Kevin Wolf91a097e2015-05-08 17:49:53 +02001450static void update_flags_from_options(int *flags, QemuOpts *opts)
1451{
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001452 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001453
Alberto Garcia57f9db92018-09-06 12:37:06 +03001454 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001455 *flags |= BDRV_O_NO_FLUSH;
1456 }
1457
Alberto Garcia57f9db92018-09-06 12:37:06 +03001458 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001459 *flags |= BDRV_O_NOCACHE;
1460 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001461
Alberto Garcia57f9db92018-09-06 12:37:06 +03001462 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001463 *flags |= BDRV_O_RDWR;
1464 }
1465
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001466 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1467 *flags |= BDRV_O_AUTO_RDONLY;
1468 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001469}
1470
1471static void update_options_from_flags(QDict *options, int flags)
1472{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001473 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001474 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001475 }
1476 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001477 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1478 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001479 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001480 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001481 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001482 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001483 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1484 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1485 flags & BDRV_O_AUTO_RDONLY);
1486 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001487}
1488
Kevin Wolf636ea372014-01-24 14:11:52 +01001489static void bdrv_assign_node_name(BlockDriverState *bs,
1490 const char *node_name,
1491 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001492{
Jeff Cody15489c72015-10-12 19:36:50 -04001493 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001494
Jeff Cody15489c72015-10-12 19:36:50 -04001495 if (!node_name) {
1496 node_name = gen_node_name = id_generate(ID_BLOCK);
1497 } else if (!id_wellformed(node_name)) {
1498 /*
1499 * Check for empty string or invalid characters, but not if it is
1500 * generated (generated names use characters not available to the user)
1501 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001502 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001503 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001504 }
1505
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001506 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001507 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001508 error_setg(errp, "node-name=%s is conflicting with a device id",
1509 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001510 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001511 }
1512
Benoît Canet6913c0c2014-01-23 21:31:33 +01001513 /* takes care of avoiding duplicates node names */
1514 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001515 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001516 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001517 }
1518
Kevin Wolf824808d2018-07-04 13:28:29 +02001519 /* Make sure that the node name isn't truncated */
1520 if (strlen(node_name) >= sizeof(bs->node_name)) {
1521 error_setg(errp, "Node name too long");
1522 goto out;
1523 }
1524
Benoît Canet6913c0c2014-01-23 21:31:33 +01001525 /* copy node name into the bs and insert it into the graph list */
1526 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1527 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001528out:
1529 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001530}
1531
Kevin Wolf01a56502017-01-18 15:51:56 +01001532static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1533 const char *node_name, QDict *options,
1534 int open_flags, Error **errp)
1535{
1536 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001537 int i, ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001538
1539 bdrv_assign_node_name(bs, node_name, &local_err);
1540 if (local_err) {
1541 error_propagate(errp, local_err);
1542 return -EINVAL;
1543 }
1544
1545 bs->drv = drv;
1546 bs->opaque = g_malloc0(drv->instance_size);
1547
1548 if (drv->bdrv_file_open) {
1549 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1550 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001551 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001552 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001553 } else {
1554 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001555 }
1556
1557 if (ret < 0) {
1558 if (local_err) {
1559 error_propagate(errp, local_err);
1560 } else if (bs->filename[0]) {
1561 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1562 } else {
1563 error_setg_errno(errp, -ret, "Could not open image");
1564 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001565 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001566 }
1567
1568 ret = refresh_total_sectors(bs, bs->total_sectors);
1569 if (ret < 0) {
1570 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001571 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001572 }
1573
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001574 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001575 if (local_err) {
1576 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001577 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001578 }
1579
1580 assert(bdrv_opt_mem_align(bs) != 0);
1581 assert(bdrv_min_mem_align(bs) != 0);
1582 assert(is_power_of_2(bs->bl.request_alignment));
1583
Kevin Wolf0f122642018-03-28 18:29:18 +02001584 for (i = 0; i < bs->quiesce_counter; i++) {
1585 if (drv->bdrv_co_drain_begin) {
1586 drv->bdrv_co_drain_begin(bs);
1587 }
1588 }
1589
Kevin Wolf01a56502017-01-18 15:51:56 +01001590 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001591open_failed:
1592 bs->drv = NULL;
1593 if (bs->file != NULL) {
1594 bdrv_unref_child(bs, bs->file);
1595 bs->file = NULL;
1596 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001597 g_free(bs->opaque);
1598 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001599 return ret;
1600}
1601
Kevin Wolf680c7f92017-01-18 17:16:41 +01001602BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1603 int flags, Error **errp)
1604{
1605 BlockDriverState *bs;
1606 int ret;
1607
1608 bs = bdrv_new();
1609 bs->open_flags = flags;
1610 bs->explicit_options = qdict_new();
1611 bs->options = qdict_new();
1612 bs->opaque = NULL;
1613
1614 update_options_from_flags(bs->options, flags);
1615
1616 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1617 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001618 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001619 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001620 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001621 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001622 bdrv_unref(bs);
1623 return NULL;
1624 }
1625
1626 return bs;
1627}
1628
Kevin Wolfc5f30142016-10-06 11:33:17 +02001629QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001630 .name = "bdrv_common",
1631 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1632 .desc = {
1633 {
1634 .name = "node-name",
1635 .type = QEMU_OPT_STRING,
1636 .help = "Node name of the block device node",
1637 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001638 {
1639 .name = "driver",
1640 .type = QEMU_OPT_STRING,
1641 .help = "Block driver to use for the node",
1642 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001643 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001644 .name = BDRV_OPT_CACHE_DIRECT,
1645 .type = QEMU_OPT_BOOL,
1646 .help = "Bypass software writeback cache on the host",
1647 },
1648 {
1649 .name = BDRV_OPT_CACHE_NO_FLUSH,
1650 .type = QEMU_OPT_BOOL,
1651 .help = "Ignore flush requests",
1652 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001653 {
1654 .name = BDRV_OPT_READ_ONLY,
1655 .type = QEMU_OPT_BOOL,
1656 .help = "Node is opened in read-only mode",
1657 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001658 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001659 .name = BDRV_OPT_AUTO_READ_ONLY,
1660 .type = QEMU_OPT_BOOL,
1661 .help = "Node can become read-only if opening read-write fails",
1662 },
1663 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001664 .name = "detect-zeroes",
1665 .type = QEMU_OPT_STRING,
1666 .help = "try to optimize zero writes (off, on, unmap)",
1667 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001668 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001669 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001670 .type = QEMU_OPT_STRING,
1671 .help = "discard operation (ignore/off, unmap/on)",
1672 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001673 {
1674 .name = BDRV_OPT_FORCE_SHARE,
1675 .type = QEMU_OPT_BOOL,
1676 .help = "always accept other writers (default: off)",
1677 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001678 { /* end of list */ }
1679 },
1680};
1681
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001682QemuOptsList bdrv_create_opts_simple = {
1683 .name = "simple-create-opts",
1684 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001685 .desc = {
1686 {
1687 .name = BLOCK_OPT_SIZE,
1688 .type = QEMU_OPT_SIZE,
1689 .help = "Virtual disk size"
1690 },
1691 {
1692 .name = BLOCK_OPT_PREALLOC,
1693 .type = QEMU_OPT_STRING,
1694 .help = "Preallocation mode (allowed values: off)"
1695 },
1696 { /* end of list */ }
1697 }
1698};
1699
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001700/*
Kevin Wolf57915332010-04-14 15:24:50 +02001701 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001702 *
1703 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001704 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001705static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001706 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001707{
1708 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001709 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001710 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001711 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001712 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001713 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001714 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001715 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001716 bool ro;
Kevin Wolf57915332010-04-14 15:24:50 +02001717
Paolo Bonzini64058752012-05-08 16:51:49 +02001718 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001719 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001720
Kevin Wolf62392eb2015-04-24 16:38:02 +02001721 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001722 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001723 ret = -EINVAL;
1724 goto fail_opts;
1725 }
1726
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001727 update_flags_from_options(&bs->open_flags, opts);
1728
Kevin Wolf62392eb2015-04-24 16:38:02 +02001729 driver_name = qemu_opt_get(opts, "driver");
1730 drv = bdrv_find_format(driver_name);
1731 assert(drv != NULL);
1732
Fam Zheng5a9347c2017-05-03 00:35:37 +08001733 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1734
1735 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1736 error_setg(errp,
1737 BDRV_OPT_FORCE_SHARE
1738 "=on can only be used with read-only images");
1739 ret = -EINVAL;
1740 goto fail_opts;
1741 }
1742
Kevin Wolf45673672013-04-22 17:48:40 +02001743 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001744 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001745 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001746 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001747 /*
1748 * Caution: while qdict_get_try_str() is fine, getting
1749 * non-string types would require more care. When @options
1750 * come from -blockdev or blockdev_add, its members are typed
1751 * according to the QAPI schema, but when they come from
1752 * -drive, they're all QString.
1753 */
Kevin Wolf45673672013-04-22 17:48:40 +02001754 filename = qdict_get_try_str(options, "filename");
1755 }
1756
Max Reitz4a008242017-04-13 18:06:24 +02001757 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001758 error_setg(errp, "The '%s' block driver requires a file name",
1759 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001760 ret = -EINVAL;
1761 goto fail_opts;
1762 }
1763
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001764 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1765 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001766
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001767 ro = bdrv_is_read_only(bs);
1768
1769 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1770 if (!ro && bdrv_is_whitelisted(drv, true)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001771 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1772 } else {
1773 ret = -ENOTSUP;
1774 }
1775 if (ret < 0) {
1776 error_setg(errp,
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001777 !ro && bdrv_is_whitelisted(drv, true)
Kevin Wolf8be25de2019-01-22 13:15:31 +01001778 ? "Driver '%s' can only be used for read-only devices"
1779 : "Driver '%s' is not whitelisted",
1780 drv->format_name);
1781 goto fail_opts;
1782 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001783 }
Kevin Wolf57915332010-04-14 15:24:50 +02001784
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001785 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001786 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001787
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001788 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Vladimir Sementsov-Ogievskiy307261b2021-05-27 18:40:54 +03001789 if (!ro) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001790 bdrv_enable_copy_on_read(bs);
1791 } else {
1792 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001793 ret = -EINVAL;
1794 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001795 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001796 }
1797
Alberto Garcia415bbca2018-10-03 13:23:13 +03001798 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001799 if (discard != NULL) {
1800 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1801 error_setg(errp, "Invalid discard option");
1802 ret = -EINVAL;
1803 goto fail_opts;
1804 }
1805 }
1806
Alberto Garcia543770b2018-09-06 12:37:09 +03001807 bs->detect_zeroes =
1808 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1809 if (local_err) {
1810 error_propagate(errp, local_err);
1811 ret = -EINVAL;
1812 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001813 }
1814
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001815 if (filename != NULL) {
1816 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1817 } else {
1818 bs->filename[0] = '\0';
1819 }
Max Reitz91af7012014-07-18 20:24:56 +02001820 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001821
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001822 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001823 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001824 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001825
Kevin Wolf01a56502017-01-18 15:51:56 +01001826 assert(!drv->bdrv_file_open || file == NULL);
1827 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001828 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001829 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001830 }
1831
Kevin Wolf18edf282015-04-07 17:12:56 +02001832 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001833 return 0;
1834
Kevin Wolf18edf282015-04-07 17:12:56 +02001835fail_opts:
1836 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001837 return ret;
1838}
1839
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001840static QDict *parse_json_filename(const char *filename, Error **errp)
1841{
1842 QObject *options_obj;
1843 QDict *options;
1844 int ret;
1845
1846 ret = strstart(filename, "json:", &filename);
1847 assert(ret);
1848
Markus Armbruster5577fff2017-02-28 22:26:59 +01001849 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001850 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001851 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001852 return NULL;
1853 }
1854
Max Reitz7dc847e2018-02-24 16:40:29 +01001855 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001856 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001857 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001858 error_setg(errp, "Invalid JSON object given");
1859 return NULL;
1860 }
1861
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001862 qdict_flatten(options);
1863
1864 return options;
1865}
1866
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001867static void parse_json_protocol(QDict *options, const char **pfilename,
1868 Error **errp)
1869{
1870 QDict *json_options;
1871 Error *local_err = NULL;
1872
1873 /* Parse json: pseudo-protocol */
1874 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1875 return;
1876 }
1877
1878 json_options = parse_json_filename(*pfilename, &local_err);
1879 if (local_err) {
1880 error_propagate(errp, local_err);
1881 return;
1882 }
1883
1884 /* Options given in the filename have lower priority than options
1885 * specified directly */
1886 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001887 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001888 *pfilename = NULL;
1889}
1890
Kevin Wolf57915332010-04-14 15:24:50 +02001891/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001892 * Fills in default options for opening images and converts the legacy
1893 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001894 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1895 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001896 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001897static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001898 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001899{
1900 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001901 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001902 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001903 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001904 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001905
Markus Armbruster129c7d12017-03-30 19:43:12 +02001906 /*
1907 * Caution: while qdict_get_try_str() is fine, getting non-string
1908 * types would require more care. When @options come from
1909 * -blockdev or blockdev_add, its members are typed according to
1910 * the QAPI schema, but when they come from -drive, they're all
1911 * QString.
1912 */
Max Reitz53a29512015-03-19 14:53:16 -04001913 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001914 if (drvname) {
1915 drv = bdrv_find_format(drvname);
1916 if (!drv) {
1917 error_setg(errp, "Unknown driver '%s'", drvname);
1918 return -ENOENT;
1919 }
1920 /* If the user has explicitly specified the driver, this choice should
1921 * override the BDRV_O_PROTOCOL flag */
1922 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001923 }
1924
1925 if (protocol) {
1926 *flags |= BDRV_O_PROTOCOL;
1927 } else {
1928 *flags &= ~BDRV_O_PROTOCOL;
1929 }
1930
Kevin Wolf91a097e2015-05-08 17:49:53 +02001931 /* Translate cache options from flags into options */
1932 update_options_from_flags(*options, *flags);
1933
Kevin Wolff54120f2014-05-26 11:09:59 +02001934 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001935 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001936 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001937 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001938 parse_filename = true;
1939 } else {
1940 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1941 "the same time");
1942 return -EINVAL;
1943 }
1944 }
1945
1946 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001947 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001948 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001949
Max Reitz053e1572015-08-26 19:47:51 +02001950 if (!drvname && protocol) {
1951 if (filename) {
1952 drv = bdrv_find_protocol(filename, parse_filename, errp);
1953 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001954 return -EINVAL;
1955 }
Max Reitz053e1572015-08-26 19:47:51 +02001956
1957 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05001958 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02001959 } else {
1960 error_setg(errp, "Must specify either driver or file");
1961 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001962 }
1963 }
1964
Kevin Wolf17b005f2014-05-27 10:50:29 +02001965 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001966
1967 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001968 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001969 drv->bdrv_parse_filename(filename, *options, &local_err);
1970 if (local_err) {
1971 error_propagate(errp, local_err);
1972 return -EINVAL;
1973 }
1974
1975 if (!drv->bdrv_needs_filename) {
1976 qdict_del(*options, "filename");
1977 }
1978 }
1979
1980 return 0;
1981}
1982
Kevin Wolf148eb132017-09-14 14:32:04 +02001983typedef struct BlockReopenQueueEntry {
1984 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01001985 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02001986 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03001987 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02001988} BlockReopenQueueEntry;
1989
1990/*
1991 * Return the flags that @bs will have after the reopens in @q have
1992 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1993 * return the current flags.
1994 */
1995static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1996{
1997 BlockReopenQueueEntry *entry;
1998
1999 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002000 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002001 if (entry->state.bs == bs) {
2002 return entry->state.flags;
2003 }
2004 }
2005 }
2006
2007 return bs->open_flags;
2008}
2009
2010/* Returns whether the image file can be written to after the reopen queue @q
2011 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002012static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2013 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002014{
2015 int flags = bdrv_reopen_get_flags(q, bs);
2016
2017 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2018}
2019
Max Reitzcc022142018-06-06 21:37:00 +02002020/*
2021 * Return whether the BDS can be written to. This is not necessarily
2022 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2023 * be written to but do not count as read-only images.
2024 */
2025bool bdrv_is_writable(BlockDriverState *bs)
2026{
2027 return bdrv_is_writable_after_reopen(bs, NULL);
2028}
2029
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002030static char *bdrv_child_user_desc(BdrvChild *c)
2031{
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002032 return c->klass->get_parent_desc(c);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002033}
2034
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002035/*
2036 * Check that @a allows everything that @b needs. @a and @b must reference same
2037 * child node.
2038 */
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002039static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2040{
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002041 const char *child_bs_name;
2042 g_autofree char *a_user = NULL;
2043 g_autofree char *b_user = NULL;
2044 g_autofree char *perms = NULL;
2045
2046 assert(a->bs);
2047 assert(a->bs == b->bs);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002048
2049 if ((b->perm & a->shared_perm) == b->perm) {
2050 return true;
2051 }
2052
Vladimir Sementsov-Ogievskiy30ebb9a2021-06-01 10:52:18 +03002053 child_bs_name = bdrv_get_node_name(b->bs);
2054 a_user = bdrv_child_user_desc(a);
2055 b_user = bdrv_child_user_desc(b);
2056 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2057
2058 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2059 "both required by %s (uses node '%s' as '%s' child) and "
2060 "unshared by %s (uses node '%s' as '%s' child).",
2061 child_bs_name, perms,
2062 b_user, child_bs_name, b->name,
2063 a_user, child_bs_name, a->name);
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002064
2065 return false;
2066}
2067
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002068static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002069{
2070 BdrvChild *a, *b;
2071
2072 /*
2073 * During the loop we'll look at each pair twice. That's correct because
2074 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2075 * directions.
2076 */
2077 QLIST_FOREACH(a, &bs->parents, next_parent) {
2078 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002079 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002080 continue;
2081 }
2082
2083 if (!bdrv_a_allow_b(a, b, errp)) {
2084 return true;
2085 }
2086 }
2087 }
2088
2089 return false;
2090}
2091
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002092static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002093 BdrvChild *c, BdrvChildRole role,
2094 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002095 uint64_t parent_perm, uint64_t parent_shared,
2096 uint64_t *nperm, uint64_t *nshared)
2097{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002098 assert(bs->drv && bs->drv->bdrv_child_perm);
Max Reitze5d8a402020-05-13 13:05:44 +02002099 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002100 parent_perm, parent_shared,
2101 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002102 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002103 if (child_bs && child_bs->force_share) {
2104 *nshared = BLK_PERM_ALL;
2105 }
2106}
2107
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002108/*
2109 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2110 * nodes that are already in the @list, of course) so that final list is
2111 * topologically sorted. Return the result (GSList @list object is updated, so
2112 * don't use old reference after function call).
2113 *
2114 * On function start @list must be already topologically sorted and for any node
2115 * in the @list the whole subtree of the node must be in the @list as well. The
2116 * simplest way to satisfy this criteria: use only result of
2117 * bdrv_topological_dfs() or NULL as @list parameter.
2118 */
2119static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2120 BlockDriverState *bs)
2121{
2122 BdrvChild *child;
2123 g_autoptr(GHashTable) local_found = NULL;
2124
2125 if (!found) {
2126 assert(!list);
2127 found = local_found = g_hash_table_new(NULL, NULL);
2128 }
2129
2130 if (g_hash_table_contains(found, bs)) {
2131 return list;
2132 }
2133 g_hash_table_add(found, bs);
2134
2135 QLIST_FOREACH(child, &bs->children, next) {
2136 list = bdrv_topological_dfs(list, found, child->bs);
2137 }
2138
2139 return g_slist_prepend(list, bs);
2140}
2141
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002142typedef struct BdrvChildSetPermState {
2143 BdrvChild *child;
2144 uint64_t old_perm;
2145 uint64_t old_shared_perm;
2146} BdrvChildSetPermState;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002147
2148static void bdrv_child_set_perm_abort(void *opaque)
2149{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002150 BdrvChildSetPermState *s = opaque;
2151
2152 s->child->perm = s->old_perm;
2153 s->child->shared_perm = s->old_shared_perm;
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002154}
2155
2156static TransactionActionDrv bdrv_child_set_pem_drv = {
2157 .abort = bdrv_child_set_perm_abort,
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002158 .clean = g_free,
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002159};
2160
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002161static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2162 uint64_t shared, Transaction *tran)
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002163{
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002164 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2165
2166 *s = (BdrvChildSetPermState) {
2167 .child = c,
2168 .old_perm = c->perm,
2169 .old_shared_perm = c->shared_perm,
2170 };
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002171
2172 c->perm = perm;
2173 c->shared_perm = shared;
2174
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002175 tran_add(tran, &bdrv_child_set_pem_drv, s);
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002176}
2177
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002178static void bdrv_drv_set_perm_commit(void *opaque)
2179{
2180 BlockDriverState *bs = opaque;
2181 uint64_t cumulative_perms, cumulative_shared_perms;
2182
2183 if (bs->drv->bdrv_set_perm) {
2184 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2185 &cumulative_shared_perms);
2186 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2187 }
2188}
2189
2190static void bdrv_drv_set_perm_abort(void *opaque)
2191{
2192 BlockDriverState *bs = opaque;
2193
2194 if (bs->drv->bdrv_abort_perm_update) {
2195 bs->drv->bdrv_abort_perm_update(bs);
2196 }
2197}
2198
2199TransactionActionDrv bdrv_drv_set_perm_drv = {
2200 .abort = bdrv_drv_set_perm_abort,
2201 .commit = bdrv_drv_set_perm_commit,
2202};
2203
2204static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2205 uint64_t shared_perm, Transaction *tran,
2206 Error **errp)
2207{
2208 if (!bs->drv) {
2209 return 0;
2210 }
2211
2212 if (bs->drv->bdrv_check_perm) {
2213 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2214 if (ret < 0) {
2215 return ret;
2216 }
2217 }
2218
2219 if (tran) {
2220 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2221 }
2222
2223 return 0;
2224}
2225
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002226typedef struct BdrvReplaceChildState {
2227 BdrvChild *child;
2228 BlockDriverState *old_bs;
2229} BdrvReplaceChildState;
2230
2231static void bdrv_replace_child_commit(void *opaque)
2232{
2233 BdrvReplaceChildState *s = opaque;
2234
2235 bdrv_unref(s->old_bs);
2236}
2237
2238static void bdrv_replace_child_abort(void *opaque)
2239{
2240 BdrvReplaceChildState *s = opaque;
2241 BlockDriverState *new_bs = s->child->bs;
2242
2243 /* old_bs reference is transparently moved from @s to @s->child */
2244 bdrv_replace_child_noperm(s->child, s->old_bs);
2245 bdrv_unref(new_bs);
2246}
2247
2248static TransactionActionDrv bdrv_replace_child_drv = {
2249 .commit = bdrv_replace_child_commit,
2250 .abort = bdrv_replace_child_abort,
2251 .clean = g_free,
2252};
2253
2254/*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002255 * bdrv_replace_child_tran
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002256 *
2257 * Note: real unref of old_bs is done only on commit.
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002258 *
2259 * The function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002260 */
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03002261static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2262 Transaction *tran)
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002263{
2264 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2265 *s = (BdrvReplaceChildState) {
2266 .child = child,
2267 .old_bs = child->bs,
2268 };
2269 tran_add(tran, &bdrv_replace_child_drv, s);
2270
2271 if (new_bs) {
2272 bdrv_ref(new_bs);
2273 }
2274 bdrv_replace_child_noperm(child, new_bs);
2275 /* old_bs reference is transparently moved from @child to @s */
2276}
2277
Kevin Wolf33a610c2016-12-15 13:04:20 +01002278/*
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002279 * Refresh permissions in @bs subtree. The function is intended to be called
2280 * after some graph modification that was done without permission update.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002281 */
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002282static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2283 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002284{
2285 BlockDriver *drv = bs->drv;
2286 BdrvChild *c;
2287 int ret;
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002288 uint64_t cumulative_perms, cumulative_shared_perms;
2289
2290 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002291
2292 /* Write permissions never work with read-only images */
2293 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002294 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002295 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002296 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2297 error_setg(errp, "Block node is read-only");
2298 } else {
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002299 error_setg(errp, "Read-only block node '%s' cannot support "
2300 "read-write users", bdrv_get_node_name(bs));
Max Reitz481e0ee2019-05-15 22:15:00 +02002301 }
2302
Kevin Wolf33a610c2016-12-15 13:04:20 +01002303 return -EPERM;
2304 }
2305
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002306 /*
2307 * Unaligned requests will automatically be aligned to bl.request_alignment
2308 * and without RESIZE we can't extend requests to write to space beyond the
2309 * end of the image, so it's required that the image size is aligned.
2310 */
2311 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2312 !(cumulative_perms & BLK_PERM_RESIZE))
2313 {
2314 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2315 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2316 "Image size is not a multiple of request "
2317 "alignment");
2318 return -EPERM;
2319 }
2320 }
2321
Kevin Wolf33a610c2016-12-15 13:04:20 +01002322 /* Check this node */
2323 if (!drv) {
2324 return 0;
2325 }
2326
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002327 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002328 errp);
2329 if (ret < 0) {
2330 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002331 }
2332
Kevin Wolf78e421c2016-12-20 23:25:12 +01002333 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002334 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002335 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002336 return 0;
2337 }
2338
2339 /* Check all children */
2340 QLIST_FOREACH(c, &bs->children, next) {
2341 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002342
Max Reitze5d8a402020-05-13 13:05:44 +02002343 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002344 cumulative_perms, cumulative_shared_perms,
2345 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002346 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002347 }
2348
2349 return 0;
2350}
2351
Vladimir Sementsov-Ogievskiy25409802021-04-28 18:18:00 +03002352static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2353 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002354{
2355 int ret;
2356 BlockDriverState *bs;
2357
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002358 for ( ; list; list = list->next) {
2359 bs = list->data;
2360
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002361 if (bdrv_parent_perms_conflict(bs, errp)) {
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002362 return -EINVAL;
2363 }
2364
Vladimir Sementsov-Ogievskiyc20555e2021-04-28 18:18:04 +03002365 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002366 if (ret < 0) {
2367 return ret;
2368 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002369 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002370
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002371 return 0;
2372}
2373
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002374void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2375 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002376{
2377 BdrvChild *c;
2378 uint64_t cumulative_perms = 0;
2379 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2380
2381 QLIST_FOREACH(c, &bs->parents, next_parent) {
2382 cumulative_perms |= c->perm;
2383 cumulative_shared_perms &= c->shared_perm;
2384 }
2385
2386 *perm = cumulative_perms;
2387 *shared_perm = cumulative_shared_perms;
2388}
2389
Fam Zheng51761962017-05-03 00:35:36 +08002390char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002391{
2392 struct perm_name {
2393 uint64_t perm;
2394 const char *name;
2395 } permissions[] = {
2396 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2397 { BLK_PERM_WRITE, "write" },
2398 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2399 { BLK_PERM_RESIZE, "resize" },
2400 { BLK_PERM_GRAPH_MOD, "change children" },
2401 { 0, NULL }
2402 };
2403
Alberto Garciae2a74232020-01-10 18:15:18 +01002404 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002405 struct perm_name *p;
2406
2407 for (p = permissions; p->name; p++) {
2408 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002409 if (result->len > 0) {
2410 g_string_append(result, ", ");
2411 }
2412 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002413 }
2414 }
2415
Alberto Garciae2a74232020-01-10 18:15:18 +01002416 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002417}
2418
Kevin Wolf33a610c2016-12-15 13:04:20 +01002419
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002420static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002421{
2422 int ret;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002423 Transaction *tran = tran_new();
2424 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002425
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002426 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2427 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002428
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002429 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002430}
2431
Kevin Wolf33a610c2016-12-15 13:04:20 +01002432int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2433 Error **errp)
2434{
Max Reitz10467792019-05-22 19:03:51 +02002435 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002436 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002437 int ret;
2438
Vladimir Sementsov-Ogievskiyecb776b2021-04-28 18:18:02 +03002439 bdrv_child_set_perm(c, perm, shared, tran);
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002440
2441 ret = bdrv_refresh_perms(c->bs, &local_err);
2442
2443 tran_finalize(tran, ret);
2444
Kevin Wolf33a610c2016-12-15 13:04:20 +01002445 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002446 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2447 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002448 error_propagate(errp, local_err);
2449 } else {
2450 /*
2451 * Our caller may intend to only loosen restrictions and
2452 * does not expect this function to fail. Errors are not
2453 * fatal in such a case, so we can just hide them from our
2454 * caller.
2455 */
2456 error_free(local_err);
2457 ret = 0;
2458 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002459 }
2460
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002461 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002462}
2463
Max Reitzc1087f12019-05-22 19:03:46 +02002464int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2465{
2466 uint64_t parent_perms, parent_shared;
2467 uint64_t perms, shared;
2468
2469 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002470 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002471 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002472
2473 return bdrv_child_try_set_perm(c, perms, shared, errp);
2474}
2475
Max Reitz87278af2020-05-13 13:05:40 +02002476/*
2477 * Default implementation for .bdrv_child_perm() for block filters:
2478 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2479 * filtered child.
2480 */
2481static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002482 BdrvChildRole role,
2483 BlockReopenQueue *reopen_queue,
2484 uint64_t perm, uint64_t shared,
2485 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002486{
Kevin Wolfe444fa82019-08-02 15:59:41 +02002487 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2488 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002489}
2490
Max Reitz70082db2020-05-13 13:05:26 +02002491static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002492 BdrvChildRole role,
2493 BlockReopenQueue *reopen_queue,
2494 uint64_t perm, uint64_t shared,
2495 uint64_t *nperm, uint64_t *nshared)
2496{
Max Reitze5d8a402020-05-13 13:05:44 +02002497 assert(role & BDRV_CHILD_COW);
Max Reitz70082db2020-05-13 13:05:26 +02002498
2499 /*
2500 * We want consistent read from backing files if the parent needs it.
2501 * No other operations are performed on backing files.
2502 */
2503 perm &= BLK_PERM_CONSISTENT_READ;
2504
2505 /*
2506 * If the parent can deal with changing data, we're okay with a
2507 * writable and resizable backing file.
2508 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2509 */
2510 if (shared & BLK_PERM_WRITE) {
2511 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2512 } else {
2513 shared = 0;
2514 }
2515
2516 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2517 BLK_PERM_WRITE_UNCHANGED;
2518
2519 if (bs->open_flags & BDRV_O_INACTIVE) {
2520 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2521 }
2522
2523 *nperm = perm;
2524 *nshared = shared;
2525}
2526
Max Reitz6f838a42020-05-13 13:05:27 +02002527static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002528 BdrvChildRole role,
2529 BlockReopenQueue *reopen_queue,
2530 uint64_t perm, uint64_t shared,
2531 uint64_t *nperm, uint64_t *nshared)
2532{
2533 int flags;
2534
Max Reitze5d8a402020-05-13 13:05:44 +02002535 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002536
2537 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2538
2539 /*
2540 * Apart from the modifications below, the same permissions are
2541 * forwarded and left alone as for filters
2542 */
Max Reitze5d8a402020-05-13 13:05:44 +02002543 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002544 perm, shared, &perm, &shared);
2545
Max Reitzf8890542020-05-13 13:05:28 +02002546 if (role & BDRV_CHILD_METADATA) {
2547 /* Format drivers may touch metadata even if the guest doesn't write */
2548 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2549 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2550 }
2551
2552 /*
2553 * bs->file always needs to be consistent because of the
2554 * metadata. We can never allow other users to resize or write
2555 * to it.
2556 */
2557 if (!(flags & BDRV_O_NO_IO)) {
2558 perm |= BLK_PERM_CONSISTENT_READ;
2559 }
2560 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002561 }
2562
Max Reitzf8890542020-05-13 13:05:28 +02002563 if (role & BDRV_CHILD_DATA) {
2564 /*
2565 * Technically, everything in this block is a subset of the
2566 * BDRV_CHILD_METADATA path taken above, and so this could
2567 * be an "else if" branch. However, that is not obvious, and
2568 * this function is not performance critical, therefore we let
2569 * this be an independent "if".
2570 */
2571
2572 /*
2573 * We cannot allow other users to resize the file because the
2574 * format driver might have some assumptions about the size
2575 * (e.g. because it is stored in metadata, or because the file
2576 * is split into fixed-size data files).
2577 */
2578 shared &= ~BLK_PERM_RESIZE;
2579
2580 /*
2581 * WRITE_UNCHANGED often cannot be performed as such on the
2582 * data file. For example, the qcow2 driver may still need to
2583 * write copied clusters on copy-on-read.
2584 */
2585 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2586 perm |= BLK_PERM_WRITE;
2587 }
2588
2589 /*
2590 * If the data file is written to, the format driver may
2591 * expect to be able to resize it by writing beyond the EOF.
2592 */
2593 if (perm & BLK_PERM_WRITE) {
2594 perm |= BLK_PERM_RESIZE;
2595 }
Max Reitz6f838a42020-05-13 13:05:27 +02002596 }
Max Reitz6f838a42020-05-13 13:05:27 +02002597
2598 if (bs->open_flags & BDRV_O_INACTIVE) {
2599 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2600 }
2601
2602 *nperm = perm;
2603 *nshared = shared;
2604}
2605
Max Reitz2519f542020-05-13 13:05:29 +02002606void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002607 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002608 uint64_t perm, uint64_t shared,
2609 uint64_t *nperm, uint64_t *nshared)
2610{
Max Reitz2519f542020-05-13 13:05:29 +02002611 if (role & BDRV_CHILD_FILTERED) {
2612 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2613 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002614 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002615 perm, shared, nperm, nshared);
2616 } else if (role & BDRV_CHILD_COW) {
2617 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002618 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002619 perm, shared, nperm, nshared);
2620 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002621 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002622 perm, shared, nperm, nshared);
2623 } else {
2624 g_assert_not_reached();
2625 }
2626}
2627
Max Reitz7b1d9c42019-11-08 13:34:51 +01002628uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2629{
2630 static const uint64_t permissions[] = {
2631 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2632 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2633 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2634 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2635 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2636 };
2637
2638 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2639 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2640
2641 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2642
2643 return permissions[qapi_perm];
2644}
2645
Kevin Wolf8ee03992017-03-06 13:45:28 +01002646static void bdrv_replace_child_noperm(BdrvChild *child,
2647 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002648{
2649 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002650 int new_bs_quiesce_counter;
2651 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002652
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002653 assert(!child->frozen);
2654
Fam Zhengbb2614e2017-04-07 14:54:10 +08002655 if (old_bs && new_bs) {
2656 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2657 }
Max Reitzdebc2922019-07-22 15:33:44 +02002658
2659 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2660 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2661
2662 /*
2663 * If the new child node is drained but the old one was not, flush
2664 * all outstanding requests to the old child node.
2665 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002666 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002667 bdrv_parent_drained_begin_single(child, true);
2668 drain_saldo--;
2669 }
2670
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002671 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002672 /* Detach first so that the recursive drain sections coming from @child
2673 * are already gone and we only end the drain sections that came from
2674 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002675 if (child->klass->detach) {
2676 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002677 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002678 QLIST_REMOVE(child, next_parent);
2679 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002680
2681 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002682
2683 if (new_bs) {
2684 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002685
2686 /*
2687 * Detaching the old node may have led to the new node's
2688 * quiesce_counter having been decreased. Not a problem, we
2689 * just need to recognize this here and then invoke
2690 * drained_end appropriately more often.
2691 */
2692 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2693 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002694
Kevin Wolfd736f112017-12-18 16:05:48 +01002695 /* Attach only after starting new drained sections, so that recursive
2696 * drain sections coming from @child don't get an extra .drained_begin
2697 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002698 if (child->klass->attach) {
2699 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002700 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002701 }
Max Reitzdebc2922019-07-22 15:33:44 +02002702
2703 /*
2704 * If the old child node was drained but the new one is not, allow
2705 * requests to come in only after the new node has been attached.
2706 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002707 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002708 bdrv_parent_drained_end_single(child);
2709 drain_saldo++;
2710 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002711}
2712
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03002713static void bdrv_child_free(void *opaque)
2714{
2715 BdrvChild *c = opaque;
2716
2717 g_free(c->name);
2718 g_free(c);
2719}
2720
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002721static void bdrv_remove_empty_child(BdrvChild *child)
2722{
2723 assert(!child->bs);
2724 QLIST_SAFE_REMOVE(child, next);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03002725 bdrv_child_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002726}
2727
2728typedef struct BdrvAttachChildCommonState {
2729 BdrvChild **child;
2730 AioContext *old_parent_ctx;
2731 AioContext *old_child_ctx;
2732} BdrvAttachChildCommonState;
2733
2734static void bdrv_attach_child_common_abort(void *opaque)
2735{
2736 BdrvAttachChildCommonState *s = opaque;
2737 BdrvChild *child = *s->child;
2738 BlockDriverState *bs = child->bs;
2739
2740 bdrv_replace_child_noperm(child, NULL);
2741
2742 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2743 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2744 }
2745
2746 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
2747 GSList *ignore = g_slist_prepend(NULL, child);
2748
2749 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2750 &error_abort);
2751 g_slist_free(ignore);
2752 ignore = g_slist_prepend(NULL, child);
2753 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
2754
2755 g_slist_free(ignore);
2756 }
2757
2758 bdrv_unref(bs);
2759 bdrv_remove_empty_child(child);
2760 *s->child = NULL;
2761}
2762
2763static TransactionActionDrv bdrv_attach_child_common_drv = {
2764 .abort = bdrv_attach_child_common_abort,
2765 .clean = g_free,
2766};
2767
2768/*
2769 * Common part of attaching bdrv child to bs or to blk or to job
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002770 *
2771 * Resulting new child is returned through @child.
2772 * At start *@child must be NULL.
2773 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2774 * NULL on abort(). So referenced variable must live at least until transaction
2775 * end.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002776 *
2777 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002778 */
2779static int bdrv_attach_child_common(BlockDriverState *child_bs,
2780 const char *child_name,
2781 const BdrvChildClass *child_class,
2782 BdrvChildRole child_role,
2783 uint64_t perm, uint64_t shared_perm,
2784 void *opaque, BdrvChild **child,
2785 Transaction *tran, Error **errp)
2786{
2787 BdrvChild *new_child;
2788 AioContext *parent_ctx;
2789 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2790
2791 assert(child);
2792 assert(*child == NULL);
Vladimir Sementsov-Ogievskiyda261b62021-06-01 10:52:17 +03002793 assert(child_class->get_parent_desc);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002794
2795 new_child = g_new(BdrvChild, 1);
2796 *new_child = (BdrvChild) {
2797 .bs = NULL,
2798 .name = g_strdup(child_name),
2799 .klass = child_class,
2800 .role = child_role,
2801 .perm = perm,
2802 .shared_perm = shared_perm,
2803 .opaque = opaque,
2804 };
2805
2806 /*
2807 * If the AioContexts don't match, first try to move the subtree of
2808 * child_bs into the AioContext of the new parent. If this doesn't work,
2809 * try moving the parent into the AioContext of child_bs instead.
2810 */
2811 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2812 if (child_ctx != parent_ctx) {
2813 Error *local_err = NULL;
2814 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2815
2816 if (ret < 0 && child_class->can_set_aio_ctx) {
2817 GSList *ignore = g_slist_prepend(NULL, new_child);
2818 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2819 NULL))
2820 {
2821 error_free(local_err);
2822 ret = 0;
2823 g_slist_free(ignore);
2824 ignore = g_slist_prepend(NULL, new_child);
2825 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2826 }
2827 g_slist_free(ignore);
2828 }
2829
2830 if (ret < 0) {
2831 error_propagate(errp, local_err);
2832 bdrv_remove_empty_child(new_child);
2833 return ret;
2834 }
2835 }
2836
2837 bdrv_ref(child_bs);
2838 bdrv_replace_child_noperm(new_child, child_bs);
2839
2840 *child = new_child;
2841
2842 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
2843 *s = (BdrvAttachChildCommonState) {
2844 .child = child,
2845 .old_parent_ctx = parent_ctx,
2846 .old_child_ctx = child_ctx,
2847 };
2848 tran_add(tran, &bdrv_attach_child_common_drv, s);
2849
2850 return 0;
2851}
2852
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002853/*
2854 * Variable referenced by @child must live at least until transaction end.
2855 * (see bdrv_attach_child_common() doc for details)
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03002856 *
2857 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002858 */
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002859static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
2860 BlockDriverState *child_bs,
2861 const char *child_name,
2862 const BdrvChildClass *child_class,
2863 BdrvChildRole child_role,
2864 BdrvChild **child,
2865 Transaction *tran,
2866 Error **errp)
2867{
2868 int ret;
2869 uint64_t perm, shared_perm;
2870
2871 assert(parent_bs->drv);
2872
2873 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2874 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2875 perm, shared_perm, &perm, &shared_perm);
2876
2877 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
2878 child_role, perm, shared_perm, parent_bs,
2879 child, tran, errp);
2880 if (ret < 0) {
2881 return ret;
2882 }
2883
2884 QLIST_INSERT_HEAD(&parent_bs->children, *child, next);
2885 /*
2886 * child is removed in bdrv_attach_child_common_abort(), so don't care to
2887 * abort this change separately.
2888 */
2889
2890 return 0;
2891}
2892
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002893static void bdrv_detach_child(BdrvChild *child)
2894{
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03002895 BlockDriverState *old_bs = child->bs;
2896
2897 bdrv_replace_child_noperm(child, NULL);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002898 bdrv_remove_empty_child(child);
Vladimir Sementsov-Ogievskiy4954aac2021-04-28 18:18:01 +03002899
2900 if (old_bs) {
2901 /*
2902 * Update permissions for old node. We're just taking a parent away, so
2903 * we're loosening restrictions. Errors of permission update are not
2904 * fatal in this case, ignore them.
2905 */
2906 bdrv_refresh_perms(old_bs, NULL);
2907
2908 /*
2909 * When the parent requiring a non-default AioContext is removed, the
2910 * node moves back to the main AioContext
2911 */
2912 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
2913 }
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002914}
2915
Alberto Garciab441dc72019-05-13 16:46:18 +03002916/*
2917 * This function steals the reference to child_bs from the caller.
2918 * That reference is later dropped by bdrv_root_unref_child().
2919 *
2920 * On failure NULL is returned, errp is set and the reference to
2921 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02002922 *
2923 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2924 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03002925 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01002926BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2927 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02002928 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002929 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002930 uint64_t perm, uint64_t shared_perm,
2931 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02002932{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002933 int ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002934 BdrvChild *child = NULL;
2935 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002936
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002937 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
2938 child_role, perm, shared_perm, opaque,
2939 &child, tran, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002940 if (ret < 0) {
Kevin Wolfe878bb12021-05-03 13:05:54 +02002941 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002942 }
2943
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002944 ret = bdrv_refresh_perms(child_bs, errp);
Kevin Wolfdf581792015-06-15 11:53:47 +02002945
Kevin Wolfe878bb12021-05-03 13:05:54 +02002946out:
2947 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002948 /* child is unset on failure by bdrv_attach_child_common_abort() */
2949 assert((ret < 0) == !child);
2950
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002951 bdrv_unref(child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02002952 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02002953}
2954
Alberto Garciab441dc72019-05-13 16:46:18 +03002955/*
2956 * This function transfers the reference to child_bs from the caller
2957 * to parent_bs. That reference is later dropped by parent_bs on
2958 * bdrv_close() or if someone calls bdrv_unref_child().
2959 *
2960 * On failure NULL is returned, errp is set and the reference to
2961 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02002962 *
2963 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2964 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03002965 */
Wen Congyang98292c62016-05-10 15:36:38 +08002966BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2967 BlockDriverState *child_bs,
2968 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02002969 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002970 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002971 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01002972{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002973 int ret;
2974 BdrvChild *child = NULL;
2975 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002976
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002977 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
2978 child_role, &child, tran, errp);
2979 if (ret < 0) {
2980 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002981 }
2982
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002983 ret = bdrv_refresh_perms(parent_bs, errp);
2984 if (ret < 0) {
2985 goto out;
2986 }
2987
2988out:
2989 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiyf8d2ad72021-06-01 10:52:13 +03002990 /* child is unset on failure by bdrv_attach_child_common_abort() */
2991 assert((ret < 0) == !child);
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002992
2993 bdrv_unref(child_bs);
2994
Kevin Wolff21d96d2016-03-08 13:47:46 +01002995 return child;
2996}
2997
Max Reitz7b99a262019-06-12 16:07:11 +02002998/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01002999void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003000{
Kevin Wolf779020c2015-10-13 14:09:44 +02003001 BlockDriverState *child_bs;
3002
Kevin Wolff21d96d2016-03-08 13:47:46 +01003003 child_bs = child->bs;
3004 bdrv_detach_child(child);
3005 bdrv_unref(child_bs);
3006}
3007
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003008typedef struct BdrvSetInheritsFrom {
3009 BlockDriverState *bs;
3010 BlockDriverState *old_inherits_from;
3011} BdrvSetInheritsFrom;
3012
3013static void bdrv_set_inherits_from_abort(void *opaque)
3014{
3015 BdrvSetInheritsFrom *s = opaque;
3016
3017 s->bs->inherits_from = s->old_inherits_from;
3018}
3019
3020static TransactionActionDrv bdrv_set_inherits_from_drv = {
3021 .abort = bdrv_set_inherits_from_abort,
3022 .clean = g_free,
3023};
3024
3025/* @tran is allowed to be NULL. In this case no rollback is possible */
3026static void bdrv_set_inherits_from(BlockDriverState *bs,
3027 BlockDriverState *new_inherits_from,
3028 Transaction *tran)
3029{
3030 if (tran) {
3031 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3032
3033 *s = (BdrvSetInheritsFrom) {
3034 .bs = bs,
3035 .old_inherits_from = bs->inherits_from,
3036 };
3037
3038 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3039 }
3040
3041 bs->inherits_from = new_inherits_from;
3042}
3043
Max Reitz3cf746b2019-07-03 19:28:07 +02003044/**
3045 * Clear all inherits_from pointers from children and grandchildren of
3046 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003047 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003048 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003049static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3050 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003051{
Max Reitz3cf746b2019-07-03 19:28:07 +02003052 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003053
Max Reitz3cf746b2019-07-03 19:28:07 +02003054 if (child->bs->inherits_from == root) {
3055 /*
3056 * Remove inherits_from only when the last reference between root and
3057 * child->bs goes away.
3058 */
3059 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003060 if (c != child && c->bs == child->bs) {
3061 break;
3062 }
3063 }
3064 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003065 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003066 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003067 }
3068
Max Reitz3cf746b2019-07-03 19:28:07 +02003069 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003070 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003071 }
3072}
3073
Max Reitz7b99a262019-06-12 16:07:11 +02003074/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003075void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3076{
3077 if (child == NULL) {
3078 return;
3079 }
3080
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003081 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003082 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003083}
3084
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003085
3086static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3087{
3088 BdrvChild *c;
3089 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003090 if (c->klass->change_media) {
3091 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003092 }
3093 }
3094}
3095
Alberto Garcia0065c452018-10-31 18:16:37 +02003096/* Return true if you can reach parent going through child->inherits_from
3097 * recursively. If parent or child are NULL, return false */
3098static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3099 BlockDriverState *parent)
3100{
3101 while (child && child != parent) {
3102 child = child->inherits_from;
3103 }
3104
3105 return child != NULL;
3106}
3107
Kevin Wolf5db15a52015-09-14 15:33:33 +02003108/*
Max Reitz25191e52020-05-13 13:05:33 +02003109 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3110 * mostly used for COW backing children (role = COW), but also for
3111 * filtered children (role = FILTERED | PRIMARY).
3112 */
3113static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3114{
3115 if (bs->drv && bs->drv->is_filter) {
3116 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3117 } else {
3118 return BDRV_CHILD_COW;
3119 }
3120}
3121
3122/*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003123 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3124 * callers which don't need their own reference any more must call bdrv_unref().
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03003125 *
3126 * Function doesn't update permissions, caller is responsible for this.
Kevin Wolf5db15a52015-09-14 15:33:33 +02003127 */
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003128static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3129 BlockDriverState *child_bs,
3130 bool is_backing,
3131 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003132{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003133 int ret = 0;
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003134 bool update_inherits_from =
3135 bdrv_inherits_from_recursive(child_bs, parent_bs);
3136 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3137 BdrvChildRole role;
Alberto Garcia0065c452018-10-31 18:16:37 +02003138
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003139 if (!parent_bs->drv) {
3140 /*
3141 * Node without drv is an object without a class :/. TODO: finally fix
3142 * qcow2 driver to never clear bs->drv and implement format corruption
3143 * handling in other way.
3144 */
3145 error_setg(errp, "Node corrupted");
3146 return -EINVAL;
3147 }
3148
3149 if (child && child->frozen) {
3150 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3151 child->name, parent_bs->node_name, child->bs->node_name);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003152 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003153 }
3154
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03003155 if (is_backing && !parent_bs->drv->is_filter &&
3156 !parent_bs->drv->supports_backing)
3157 {
3158 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3159 "files", parent_bs->drv->format_name, parent_bs->node_name);
3160 return -EINVAL;
3161 }
3162
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003163 if (parent_bs->drv->is_filter) {
3164 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3165 } else if (is_backing) {
3166 role = BDRV_CHILD_COW;
3167 } else {
3168 /*
3169 * We only can use same role as it is in existing child. We don't have
3170 * infrastructure to determine role of file child in generic way
3171 */
3172 if (!child) {
3173 error_setg(errp, "Cannot set file child to format node without "
3174 "file child");
3175 return -EINVAL;
3176 }
3177 role = child->role;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003178 }
3179
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003180 if (child) {
3181 bdrv_unset_inherits_from(parent_bs, child, tran);
3182 bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3183 }
3184
3185 if (!child_bs) {
Fam Zheng8d24cce2014-05-23 21:29:45 +08003186 goto out;
3187 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003188
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003189 ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3190 is_backing ? "backing" : "file",
3191 &child_of_bds, role,
3192 is_backing ? &parent_bs->backing :
3193 &parent_bs->file,
3194 tran, errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003195 if (ret < 0) {
3196 return ret;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003197 }
3198
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003199
3200 /*
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003201 * If inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003202 * point directly to bs (else it will become NULL).
3203 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003204 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003205 bdrv_set_inherits_from(child_bs, parent_bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003206 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003207
Fam Zheng8d24cce2014-05-23 21:29:45 +08003208out:
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003209 bdrv_refresh_limits(parent_bs, tran, NULL);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003210
3211 return 0;
3212}
3213
Vladimir Sementsov-Ogievskiye9238272021-06-10 15:05:30 +03003214static int bdrv_set_backing_noperm(BlockDriverState *bs,
3215 BlockDriverState *backing_hd,
3216 Transaction *tran, Error **errp)
3217{
3218 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3219}
3220
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003221int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3222 Error **errp)
3223{
3224 int ret;
3225 Transaction *tran = tran_new();
3226
3227 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3228 if (ret < 0) {
3229 goto out;
3230 }
3231
3232 ret = bdrv_refresh_perms(bs, errp);
3233out:
3234 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003235
3236 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003237}
3238
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003239/*
3240 * Opens the backing file for a BlockDriverState if not yet open
3241 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003242 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3243 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3244 * itself, all options starting with "${bdref_key}." are considered part of the
3245 * BlockdevRef.
3246 *
3247 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003248 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003249int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3250 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003251{
Max Reitz6b6833c2019-02-01 20:29:15 +01003252 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003253 char *bdref_key_dot;
3254 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003255 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003256 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003257 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003258 QDict *options;
3259 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003260 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003261
Kevin Wolf760e0062015-06-17 14:55:21 +02003262 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003263 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003264 }
3265
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003266 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003267 if (parent_options == NULL) {
3268 tmp_parent_options = qdict_new();
3269 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003270 }
3271
Paolo Bonzini9156df12012-10-18 16:49:17 +02003272 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003273
3274 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3275 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3276 g_free(bdref_key_dot);
3277
Markus Armbruster129c7d12017-03-30 19:43:12 +02003278 /*
3279 * Caution: while qdict_get_try_str() is fine, getting non-string
3280 * types would require more care. When @parent_options come from
3281 * -blockdev or blockdev_add, its members are typed according to
3282 * the QAPI schema, but when they come from -drive, they're all
3283 * QString.
3284 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003285 reference = qdict_get_try_str(parent_options, bdref_key);
3286 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003287 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003288 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003289 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003290 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003291 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003292 if (qdict_size(options) == 0) {
3293 /* If the user specifies options that do not modify the
3294 * backing file's behavior, we might still consider it the
3295 * implicit backing file. But it's easier this way, and
3296 * just specifying some of the backing BDS's options is
3297 * only possible with -drive anyway (otherwise the QAPI
3298 * schema forces the user to specify everything). */
3299 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3300 }
3301
Max Reitz6b6833c2019-02-01 20:29:15 +01003302 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003303 if (local_err) {
3304 ret = -EINVAL;
3305 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003306 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003307 goto free_exit;
3308 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003309 }
3310
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003311 if (!bs->drv || !bs->drv->supports_backing) {
3312 ret = -EINVAL;
3313 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003314 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003315 goto free_exit;
3316 }
3317
Peter Krempa6bff5972017-10-12 16:14:10 +02003318 if (!reference &&
3319 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003320 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003321 }
3322
Max Reitz6b6833c2019-02-01 20:29:15 +01003323 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003324 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003325 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003326 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003327 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003328 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003329 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003330 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003331
Max Reitz998c2012019-02-01 20:29:08 +01003332 if (implicit_backing) {
3333 bdrv_refresh_filename(backing_hd);
3334 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3335 backing_hd->filename);
3336 }
3337
Kevin Wolf5db15a52015-09-14 15:33:33 +02003338 /* Hook up the backing file link; drop our reference, bs owns the
3339 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003340 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003341 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003342 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003343 goto free_exit;
3344 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003345
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003346 qdict_del(parent_options, bdref_key);
3347
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003348free_exit:
3349 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003350 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003351 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003352}
3353
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003354static BlockDriverState *
3355bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003356 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003357 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003358{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003359 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003360 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003361 char *bdref_key_dot;
3362 const char *reference;
3363
Max Reitzbd86fb92020-05-13 13:05:13 +02003364 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003365
Max Reitzda557aa2013-12-20 19:28:11 +01003366 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3367 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3368 g_free(bdref_key_dot);
3369
Markus Armbruster129c7d12017-03-30 19:43:12 +02003370 /*
3371 * Caution: while qdict_get_try_str() is fine, getting non-string
3372 * types would require more care. When @options come from
3373 * -blockdev or blockdev_add, its members are typed according to
3374 * the QAPI schema, but when they come from -drive, they're all
3375 * QString.
3376 */
Max Reitzda557aa2013-12-20 19:28:11 +01003377 reference = qdict_get_try_str(options, bdref_key);
3378 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003379 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003380 error_setg(errp, "A block device must be specified for \"%s\"",
3381 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003382 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003383 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003384 goto done;
3385 }
3386
Max Reitz5b363932016-05-17 16:41:31 +02003387 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003388 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003389 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003390 goto done;
3391 }
3392
Max Reitzda557aa2013-12-20 19:28:11 +01003393done:
3394 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003395 return bs;
3396}
3397
3398/*
3399 * Opens a disk image whose options are given as BlockdevRef in another block
3400 * device's options.
3401 *
3402 * If allow_none is true, no image will be opened if filename is false and no
3403 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3404 *
3405 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3406 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3407 * itself, all options starting with "${bdref_key}." are considered part of the
3408 * BlockdevRef.
3409 *
3410 * The BlockdevRef will be removed from the options QDict.
3411 */
3412BdrvChild *bdrv_open_child(const char *filename,
3413 QDict *options, const char *bdref_key,
3414 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003415 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003416 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003417 bool allow_none, Error **errp)
3418{
3419 BlockDriverState *bs;
3420
Max Reitzbd86fb92020-05-13 13:05:13 +02003421 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003422 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003423 if (bs == NULL) {
3424 return NULL;
3425 }
3426
Max Reitz258b7762020-05-13 13:05:15 +02003427 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3428 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003429}
3430
Max Reitzbd86fb92020-05-13 13:05:13 +02003431/*
3432 * TODO Future callers may need to specify parent/child_class in order for
3433 * option inheritance to work. Existing callers use it for the root node.
3434 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003435BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3436{
3437 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003438 QObject *obj = NULL;
3439 QDict *qdict = NULL;
3440 const char *reference = NULL;
3441 Visitor *v = NULL;
3442
3443 if (ref->type == QTYPE_QSTRING) {
3444 reference = ref->u.reference;
3445 } else {
3446 BlockdevOptions *options = &ref->u.definition;
3447 assert(ref->type == QTYPE_QDICT);
3448
3449 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003450 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003451 visit_complete(v, &obj);
3452
Max Reitz7dc847e2018-02-24 16:40:29 +01003453 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003454 qdict_flatten(qdict);
3455
3456 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3457 * compatibility with other callers) rather than what we want as the
3458 * real defaults. Apply the defaults here instead. */
3459 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3460 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3461 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003462 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3463
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003464 }
3465
Max Reitz272c02e2020-05-13 13:05:17 +02003466 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003467 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003468 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003469 visit_free(v);
3470 return bs;
3471}
3472
Max Reitz66836182016-05-17 16:41:27 +02003473static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3474 int flags,
3475 QDict *snapshot_options,
3476 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003477{
3478 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003479 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003480 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003481 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003482 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003483 int ret;
3484
3485 /* if snapshot, we create a temporary backing file and open it
3486 instead of opening 'filename' directly */
3487
3488 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003489 total_size = bdrv_getlength(bs);
3490 if (total_size < 0) {
3491 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003492 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003493 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003494
3495 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003496 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003497 if (ret < 0) {
3498 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003499 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003500 }
3501
Max Reitzef810432014-12-02 18:32:42 +01003502 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003503 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003504 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003505 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003506 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003507 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003508 error_prepend(errp, "Could not create temporary overlay '%s': ",
3509 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003510 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003511 }
3512
Kevin Wolf73176be2016-03-07 13:02:15 +01003513 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003514 qdict_put_str(snapshot_options, "file.driver", "file");
3515 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3516 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003517
Max Reitz5b363932016-05-17 16:41:31 +02003518 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003519 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003520 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003521 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003522 }
3523
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003524 ret = bdrv_append(bs_snapshot, bs, errp);
3525 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003526 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003527 goto out;
3528 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003529
3530out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003531 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003532 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003533 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003534}
3535
Max Reitzda557aa2013-12-20 19:28:11 +01003536/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003537 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003538 *
3539 * options is a QDict of options to pass to the block drivers, or NULL for an
3540 * empty set of options. The reference to the QDict belongs to the block layer
3541 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003542 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003543 *
3544 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3545 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003546 *
3547 * The reference parameter may be used to specify an existing block device which
3548 * should be opened. If specified, neither options nor a filename may be given,
3549 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003550 */
Max Reitz5b363932016-05-17 16:41:31 +02003551static BlockDriverState *bdrv_open_inherit(const char *filename,
3552 const char *reference,
3553 QDict *options, int flags,
3554 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003555 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003556 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003557 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003558{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003559 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003560 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003561 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003562 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003563 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003564 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003565 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003566 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003567 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003568 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003569
Max Reitzbd86fb92020-05-13 13:05:13 +02003570 assert(!child_class || !flags);
3571 assert(!child_class == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01003572
Max Reitzddf56362014-02-18 18:33:06 +01003573 if (reference) {
3574 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003575 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003576
Max Reitzddf56362014-02-18 18:33:06 +01003577 if (filename || options_non_empty) {
3578 error_setg(errp, "Cannot reference an existing block device with "
3579 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003580 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003581 }
3582
3583 bs = bdrv_lookup_bs(reference, reference, errp);
3584 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003585 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003586 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003587
Max Reitzddf56362014-02-18 18:33:06 +01003588 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003589 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003590 }
3591
Max Reitz5b363932016-05-17 16:41:31 +02003592 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003593
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003594 /* NULL means an empty set of options */
3595 if (options == NULL) {
3596 options = qdict_new();
3597 }
3598
Kevin Wolf145f5982015-05-08 16:15:03 +02003599 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003600 parse_json_protocol(options, &filename, &local_err);
3601 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003602 goto fail;
3603 }
3604
Kevin Wolf145f5982015-05-08 16:15:03 +02003605 bs->explicit_options = qdict_clone_shallow(options);
3606
Max Reitzbd86fb92020-05-13 13:05:13 +02003607 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003608 bool parent_is_format;
3609
3610 if (parent->drv) {
3611 parent_is_format = parent->drv->is_format;
3612 } else {
3613 /*
3614 * parent->drv is not set yet because this node is opened for
3615 * (potential) format probing. That means that @parent is going
3616 * to be a format node.
3617 */
3618 parent_is_format = true;
3619 }
3620
Kevin Wolfbddcec32015-04-09 18:47:50 +02003621 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003622 child_class->inherit_options(child_role, parent_is_format,
3623 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003624 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003625 }
3626
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003627 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003628 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003629 goto fail;
3630 }
3631
Markus Armbruster129c7d12017-03-30 19:43:12 +02003632 /*
3633 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3634 * Caution: getting a boolean member of @options requires care.
3635 * When @options come from -blockdev or blockdev_add, members are
3636 * typed according to the QAPI schema, but when they come from
3637 * -drive, they're all QString.
3638 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003639 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3640 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3641 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3642 } else {
3643 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003644 }
3645
3646 if (flags & BDRV_O_SNAPSHOT) {
3647 snapshot_options = qdict_new();
3648 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3649 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003650 /* Let bdrv_backing_options() override "read-only" */
3651 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003652 bdrv_inherited_options(BDRV_CHILD_COW, true,
3653 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003654 }
3655
Kevin Wolf62392eb2015-04-24 16:38:02 +02003656 bs->open_flags = flags;
3657 bs->options = options;
3658 options = qdict_clone_shallow(options);
3659
Kevin Wolf76c591b2014-06-04 14:19:44 +02003660 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003661 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003662 drvname = qdict_get_try_str(options, "driver");
3663 if (drvname) {
3664 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003665 if (!drv) {
3666 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003667 goto fail;
3668 }
3669 }
3670
3671 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003672
Markus Armbruster129c7d12017-03-30 19:43:12 +02003673 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003674 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003675 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3676 (backing && *backing == '\0'))
3677 {
Max Reitz4f7be282018-02-24 16:40:33 +01003678 if (backing) {
3679 warn_report("Use of \"backing\": \"\" is deprecated; "
3680 "use \"backing\": null instead");
3681 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003682 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003683 qdict_del(bs->explicit_options, "backing");
3684 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003685 qdict_del(options, "backing");
3686 }
3687
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003688 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003689 * probing, the block drivers will do their own bdrv_open_child() for the
3690 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003691 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003692 BlockDriverState *file_bs;
3693
3694 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003695 &child_of_bds, BDRV_CHILD_IMAGE,
3696 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003697 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003698 goto fail;
3699 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003700 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003701 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3702 * looking at the header to guess the image format. This works even
3703 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003704 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003705 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003706 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003707 if (local_err) {
3708 goto fail;
3709 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003710
Eric Blake46f5ac22017-04-27 16:58:17 -05003711 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003712 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003713 }
3714
Kevin Wolf76c591b2014-06-04 14:19:44 +02003715 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003716 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003717 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003718 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003719 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003720 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003721 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003722 /*
3723 * This option update would logically belong in bdrv_fill_options(),
3724 * but we first need to open bs->file for the probing to work, while
3725 * opening bs->file already requires the (mostly) final set of options
3726 * so that cache mode etc. can be inherited.
3727 *
3728 * Adding the driver later is somewhat ugly, but it's not an option
3729 * that would ever be inherited, so it's correct. We just need to make
3730 * sure to update both bs->options (which has the full effective
3731 * options for bs) and options (which has file.* already removed).
3732 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003733 qdict_put_str(bs->options, "driver", drv->format_name);
3734 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003735 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003736 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003737 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003738 }
3739
Max Reitz53a29512015-03-19 14:53:16 -04003740 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3741 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3742 /* file must be NULL if a protocol BDS is about to be created
3743 * (the inverse results in an error message from bdrv_open_common()) */
3744 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3745
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003746 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003747 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003748 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003749 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003750 }
3751
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003752 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003753 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003754 file = NULL;
3755 }
3756
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003757 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003758 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003759 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003760 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003761 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003762 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003763 }
3764
Alberto Garcia50196d72018-09-06 12:37:03 +03003765 /* Remove all children options and references
3766 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003767 QLIST_FOREACH(child, &bs->children, next) {
3768 char *child_key_dot;
3769 child_key_dot = g_strdup_printf("%s.", child->name);
3770 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3771 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003772 qdict_del(bs->explicit_options, child->name);
3773 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003774 g_free(child_key_dot);
3775 }
3776
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003777 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003778 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003779 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003780 if (flags & BDRV_O_PROTOCOL) {
3781 error_setg(errp, "Block protocol '%s' doesn't support the option "
3782 "'%s'", drv->format_name, entry->key);
3783 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003784 error_setg(errp,
3785 "Block format '%s' does not support the option '%s'",
3786 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003787 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003788
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003789 goto close_and_fail;
3790 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003791
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003792 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003793
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003794 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003795 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003796
3797 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3798 * temporary snapshot afterwards. */
3799 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003800 BlockDriverState *snapshot_bs;
3801 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3802 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003803 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003804 if (local_err) {
3805 goto close_and_fail;
3806 }
Max Reitz5b363932016-05-17 16:41:31 +02003807 /* We are not going to return bs but the overlay on top of it
3808 * (snapshot_bs); thus, we have to drop the strong reference to bs
3809 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3810 * though, because the overlay still has a reference to it. */
3811 bdrv_unref(bs);
3812 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003813 }
3814
Max Reitz5b363932016-05-17 16:41:31 +02003815 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003816
Kevin Wolf8bfea152014-04-11 19:16:36 +02003817fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003818 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003819 qobject_unref(snapshot_options);
3820 qobject_unref(bs->explicit_options);
3821 qobject_unref(bs->options);
3822 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003823 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003824 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003825 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003826 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003827 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003828
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003829close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02003830 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003831 qobject_unref(snapshot_options);
3832 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003833 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003834 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003835}
3836
Max Reitz5b363932016-05-17 16:41:31 +02003837BlockDriverState *bdrv_open(const char *filename, const char *reference,
3838 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02003839{
Max Reitz5b363932016-05-17 16:41:31 +02003840 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02003841 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003842}
3843
Alberto Garciafaf116b2019-03-12 18:48:49 +02003844/* Return true if the NULL-terminated @list contains @str */
3845static bool is_str_in_list(const char *str, const char *const *list)
3846{
3847 if (str && list) {
3848 int i;
3849 for (i = 0; list[i] != NULL; i++) {
3850 if (!strcmp(str, list[i])) {
3851 return true;
3852 }
3853 }
3854 }
3855 return false;
3856}
3857
3858/*
3859 * Check that every option set in @bs->options is also set in
3860 * @new_opts.
3861 *
3862 * Options listed in the common_options list and in
3863 * @bs->drv->mutable_opts are skipped.
3864 *
3865 * Return 0 on success, otherwise return -EINVAL and set @errp.
3866 */
3867static int bdrv_reset_options_allowed(BlockDriverState *bs,
3868 const QDict *new_opts, Error **errp)
3869{
3870 const QDictEntry *e;
3871 /* These options are common to all block drivers and are handled
3872 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3873 const char *const common_options[] = {
3874 "node-name", "discard", "cache.direct", "cache.no-flush",
3875 "read-only", "auto-read-only", "detect-zeroes", NULL
3876 };
3877
3878 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3879 if (!qdict_haskey(new_opts, e->key) &&
3880 !is_str_in_list(e->key, common_options) &&
3881 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3882 error_setg(errp, "Option '%s' cannot be reset "
3883 "to its default value", e->key);
3884 return -EINVAL;
3885 }
3886 }
3887
3888 return 0;
3889}
3890
Jeff Codye971aa12012-09-20 15:13:19 -04003891/*
Alberto Garciacb828c32019-03-12 18:48:47 +02003892 * Returns true if @child can be reached recursively from @bs
3893 */
3894static bool bdrv_recurse_has_child(BlockDriverState *bs,
3895 BlockDriverState *child)
3896{
3897 BdrvChild *c;
3898
3899 if (bs == child) {
3900 return true;
3901 }
3902
3903 QLIST_FOREACH(c, &bs->children, next) {
3904 if (bdrv_recurse_has_child(c->bs, child)) {
3905 return true;
3906 }
3907 }
3908
3909 return false;
3910}
3911
3912/*
Jeff Codye971aa12012-09-20 15:13:19 -04003913 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3914 * reopen of multiple devices.
3915 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003916 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04003917 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3918 * be created and initialized. This newly created BlockReopenQueue should be
3919 * passed back in for subsequent calls that are intended to be of the same
3920 * atomic 'set'.
3921 *
3922 * bs is the BlockDriverState to add to the reopen queue.
3923 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003924 * options contains the changed options for the associated bs
3925 * (the BlockReopenQueue takes ownership)
3926 *
Jeff Codye971aa12012-09-20 15:13:19 -04003927 * flags contains the open flags for the associated bs
3928 *
3929 * returns a pointer to bs_queue, which is either the newly allocated
3930 * bs_queue, or the existing bs_queue being used.
3931 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01003932 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04003933 */
Kevin Wolf28518102015-05-08 17:07:31 +02003934static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3935 BlockDriverState *bs,
3936 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003937 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02003938 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02003939 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02003940 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02003941 int parent_flags,
3942 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04003943{
3944 assert(bs != NULL);
3945
3946 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02003947 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003948 QDict *old_options, *explicit_options, *options_copy;
3949 int flags;
3950 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02003951
Kevin Wolf1a63a902017-12-06 20:24:44 +01003952 /* Make sure that the caller remembered to use a drained section. This is
3953 * important to avoid graph changes between the recursive queuing here and
3954 * bdrv_reopen_multiple(). */
3955 assert(bs->quiesce_counter > 0);
3956
Jeff Codye971aa12012-09-20 15:13:19 -04003957 if (bs_queue == NULL) {
3958 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003959 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04003960 }
3961
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003962 if (!options) {
3963 options = qdict_new();
3964 }
3965
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003966 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003967 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003968 if (bs == bs_entry->state.bs) {
3969 break;
3970 }
3971 }
3972
Kevin Wolf28518102015-05-08 17:07:31 +02003973 /*
3974 * Precedence of options:
3975 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003976 * 2. Retained from explicitly set options of bs
3977 * 3. Inherited from parent node
3978 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02003979 */
3980
Kevin Wolf145f5982015-05-08 16:15:03 +02003981 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02003982 if (bs_entry || keep_old_opts) {
3983 old_options = qdict_clone_shallow(bs_entry ?
3984 bs_entry->state.explicit_options :
3985 bs->explicit_options);
3986 bdrv_join_options(bs, options, old_options);
3987 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003988 }
Kevin Wolf145f5982015-05-08 16:15:03 +02003989
3990 explicit_options = qdict_clone_shallow(options);
3991
Kevin Wolf28518102015-05-08 17:07:31 +02003992 /* Inherit from parent node */
3993 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003994 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003995 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02003996 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003997 } else {
3998 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02003999 }
4000
Alberto Garcia077e8e22019-03-12 18:48:44 +02004001 if (keep_old_opts) {
4002 /* Old values are used for options that aren't set yet */
4003 old_options = qdict_clone_shallow(bs->options);
4004 bdrv_join_options(bs, options, old_options);
4005 qobject_unref(old_options);
4006 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004007
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004008 /* We have the final set of options so let's update the flags */
4009 options_copy = qdict_clone_shallow(options);
4010 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4011 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4012 update_flags_from_options(&flags, opts);
4013 qemu_opts_del(opts);
4014 qobject_unref(options_copy);
4015
Kevin Wolffd452022017-08-03 17:02:59 +02004016 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004017 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004018 if (flags & BDRV_O_RDWR) {
4019 flags |= BDRV_O_ALLOW_RDWR;
4020 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004021
Kevin Wolf1857c972017-09-14 14:53:46 +02004022 if (!bs_entry) {
4023 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004024 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004025 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004026 qobject_unref(bs_entry->state.options);
4027 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004028 }
4029
4030 bs_entry->state.bs = bs;
4031 bs_entry->state.options = options;
4032 bs_entry->state.explicit_options = explicit_options;
4033 bs_entry->state.flags = flags;
4034
Alberto Garcia85466322019-03-12 18:48:45 +02004035 /*
4036 * If keep_old_opts is false then it means that unspecified
4037 * options must be reset to their original value. We don't allow
4038 * resetting 'backing' but we need to know if the option is
4039 * missing in order to decide if we have to return an error.
4040 */
4041 if (!keep_old_opts) {
4042 bs_entry->state.backing_missing =
4043 !qdict_haskey(options, "backing") &&
4044 !qdict_haskey(options, "backing.driver");
4045 }
4046
Kevin Wolf67251a32015-04-09 18:54:04 +02004047 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004048 QDict *new_child_options = NULL;
4049 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004050
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004051 /* reopen can only change the options of block devices that were
4052 * implicitly created and inherited options. For other (referenced)
4053 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004054 if (child->bs->inherits_from != bs) {
4055 continue;
4056 }
4057
Alberto Garcia85466322019-03-12 18:48:45 +02004058 /* Check if the options contain a child reference */
4059 if (qdict_haskey(options, child->name)) {
4060 const char *childref = qdict_get_try_str(options, child->name);
4061 /*
4062 * The current child must not be reopened if the child
4063 * reference is null or points to a different node.
4064 */
4065 if (g_strcmp0(childref, child->bs->node_name)) {
4066 continue;
4067 }
4068 /*
4069 * If the child reference points to the current child then
4070 * reopen it with its existing set of options (note that
4071 * it can still inherit new options from the parent).
4072 */
4073 child_keep_old = true;
4074 } else {
4075 /* Extract child options ("child-name.*") */
4076 char *child_key_dot = g_strdup_printf("%s.", child->name);
4077 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4078 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4079 g_free(child_key_dot);
4080 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004081
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004082 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004083 child->klass, child->role, bs->drv->is_format,
4084 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004085 }
4086
Jeff Codye971aa12012-09-20 15:13:19 -04004087 return bs_queue;
4088}
4089
Kevin Wolf28518102015-05-08 17:07:31 +02004090BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4091 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004092 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004093{
Max Reitz3cdc69d2020-05-13 13:05:18 +02004094 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4095 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004096}
4097
Jeff Codye971aa12012-09-20 15:13:19 -04004098/*
4099 * Reopen multiple BlockDriverStates atomically & transactionally.
4100 *
4101 * The queue passed in (bs_queue) must have been built up previous
4102 * via bdrv_reopen_queue().
4103 *
4104 * Reopens all BDS specified in the queue, with the appropriate
4105 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004106 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004107 * data cleaned up.
4108 *
4109 * If all devices prepare successfully, then the changes are committed
4110 * to all devices.
4111 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004112 * All affected nodes must be drained between bdrv_reopen_queue() and
4113 * bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004114 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004115int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004116{
4117 int ret = -1;
4118 BlockReopenQueueEntry *bs_entry, *next;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004119 Transaction *tran = tran_new();
4120 g_autoptr(GHashTable) found = NULL;
4121 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004122
4123 assert(bs_queue != NULL);
4124
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004125 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004126 ret = bdrv_flush(bs_entry->state.bs);
4127 if (ret < 0) {
4128 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004129 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004130 }
4131 }
4132
4133 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004134 assert(bs_entry->state.bs->quiesce_counter > 0);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004135 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4136 if (ret < 0) {
4137 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004138 }
4139 bs_entry->prepared = true;
4140 }
4141
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004142 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004143 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004144 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004145
4146 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4147 if (state->old_backing_bs) {
4148 refresh_list = bdrv_topological_dfs(refresh_list, found,
4149 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004150 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004151 }
4152
4153 /*
4154 * Note that file-posix driver rely on permission update done during reopen
4155 * (even if no permission changed), because it wants "new" permissions for
4156 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4157 * in raw_reopen_prepare() which is called with "old" permissions.
4158 */
4159 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4160 if (ret < 0) {
4161 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004162 }
4163
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004164 /*
4165 * If we reach this point, we have success and just need to apply the
4166 * changes.
4167 *
4168 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4169 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4170 * children are usually goes after parents in reopen-queue, so go from last
4171 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004172 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004173 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Jeff Codye971aa12012-09-20 15:13:19 -04004174 bdrv_reopen_commit(&bs_entry->state);
4175 }
4176
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004177 tran_commit(tran);
4178
4179 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4180 BlockDriverState *bs = bs_entry->state.bs;
4181
4182 if (bs->drv->bdrv_reopen_commit_post) {
4183 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4184 }
4185 }
4186
Jeff Codye971aa12012-09-20 15:13:19 -04004187 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004188 goto cleanup;
4189
4190abort:
4191 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004192 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004193 if (bs_entry->prepared) {
4194 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004195 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004196 qobject_unref(bs_entry->state.explicit_options);
4197 qobject_unref(bs_entry->state.options);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004198 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004199
Jeff Codye971aa12012-09-20 15:13:19 -04004200cleanup:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004201 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Jeff Codye971aa12012-09-20 15:13:19 -04004202 g_free(bs_entry);
4203 }
4204 g_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004205
Jeff Codye971aa12012-09-20 15:13:19 -04004206 return ret;
4207}
4208
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004209int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4210 Error **errp)
4211{
4212 int ret;
4213 BlockReopenQueue *queue;
4214 QDict *opts = qdict_new();
4215
4216 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4217
4218 bdrv_subtree_drained_begin(bs);
Alberto Garcia077e8e22019-03-12 18:48:44 +02004219 queue = bdrv_reopen_queue(NULL, bs, opts, true);
Alberto Garcia5019aec2019-03-12 18:48:50 +02004220 ret = bdrv_reopen_multiple(queue, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004221 bdrv_subtree_drained_end(bs);
4222
4223 return ret;
4224}
4225
Jeff Codye971aa12012-09-20 15:13:19 -04004226/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004227 * Take a BDRVReopenState and check if the value of 'backing' in the
4228 * reopen_state->options QDict is valid or not.
4229 *
4230 * If 'backing' is missing from the QDict then return 0.
4231 *
4232 * If 'backing' contains the node name of the backing file of
4233 * reopen_state->bs then return 0.
4234 *
4235 * If 'backing' contains a different node name (or is null) then check
4236 * whether the current backing file can be replaced with the new one.
4237 * If that's the case then reopen_state->replace_backing_bs is set to
4238 * true and reopen_state->new_backing_bs contains a pointer to the new
4239 * backing BlockDriverState (or NULL).
4240 *
4241 * Return 0 on success, otherwise return < 0 and set @errp.
4242 */
4243static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004244 Transaction *set_backings_tran,
Alberto Garciacb828c32019-03-12 18:48:47 +02004245 Error **errp)
4246{
4247 BlockDriverState *bs = reopen_state->bs;
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004248 BlockDriverState *new_backing_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004249 QObject *value;
4250 const char *str;
4251
4252 value = qdict_get(reopen_state->options, "backing");
4253 if (value == NULL) {
4254 return 0;
4255 }
4256
4257 switch (qobject_type(value)) {
4258 case QTYPE_QNULL:
4259 new_backing_bs = NULL;
4260 break;
4261 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004262 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciacb828c32019-03-12 18:48:47 +02004263 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4264 if (new_backing_bs == NULL) {
4265 return -EINVAL;
4266 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4267 error_setg(errp, "Making '%s' a backing file of '%s' "
4268 "would create a cycle", str, bs->node_name);
4269 return -EINVAL;
4270 }
4271 break;
4272 default:
4273 /* 'backing' does not allow any other data type */
4274 g_assert_not_reached();
4275 }
4276
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004277 if (bs->backing) {
4278 if (bdrv_skip_implicit_filters(bs->backing->bs) == new_backing_bs) {
4279 return 0;
4280 }
4281
4282 if (bs->backing->bs->implicit) {
4283 error_setg(errp, "Cannot change backing link if '%s' has "
4284 "an implicit backing file", bs->node_name);
4285 return -EPERM;
4286 }
4287 }
4288
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004289 if (bs->drv->is_filter && !bs->backing) {
4290 /*
4291 * Filters always have a file or a backing child, so we are trying to
4292 * change wrong child
4293 */
4294 error_setg(errp, "'%s' is a %s filter node that does not support a "
4295 "backing child", bs->node_name, bs->drv->format_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004296 return -EINVAL;
4297 }
4298
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004299 reopen_state->old_backing_bs = bs->backing ? bs->backing->bs : NULL;
4300 return bdrv_set_backing_noperm(bs, new_backing_bs, set_backings_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004301}
4302
4303/*
Jeff Codye971aa12012-09-20 15:13:19 -04004304 * Prepares a BlockDriverState for reopen. All changes are staged in the
4305 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4306 * the block driver layer .bdrv_reopen_prepare()
4307 *
4308 * bs is the BlockDriverState to reopen
4309 * flags are the new open flags
4310 * queue is the reopen queue
4311 *
4312 * Returns 0 on success, non-zero on error. On error errp will be set
4313 * as well.
4314 *
4315 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4316 * It is the responsibility of the caller to then call the abort() or
4317 * commit() for any other BDS that have been left in a prepare() state
4318 *
4319 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004320static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004321 BlockReopenQueue *queue,
4322 Transaction *set_backings_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004323{
4324 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004325 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004326 Error *local_err = NULL;
4327 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004328 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004329 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004330 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004331 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004332 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004333
4334 assert(reopen_state != NULL);
4335 assert(reopen_state->bs->drv != NULL);
4336 drv = reopen_state->bs->drv;
4337
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004338 /* This function and each driver's bdrv_reopen_prepare() remove
4339 * entries from reopen_state->options as they are processed, so
4340 * we need to make a copy of the original QDict. */
4341 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4342
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004343 /* Process generic block layer options */
4344 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004345 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004346 ret = -EINVAL;
4347 goto error;
4348 }
4349
Alberto Garciae6d79c42018-11-12 16:00:47 +02004350 /* This was already called in bdrv_reopen_queue_child() so the flags
4351 * are up-to-date. This time we simply want to remove the options from
4352 * QemuOpts in order to indicate that they have been processed. */
4353 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004354 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004355 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004356
Alberto Garcia415bbca2018-10-03 13:23:13 +03004357 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004358 if (discard != NULL) {
4359 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4360 error_setg(errp, "Invalid discard option");
4361 ret = -EINVAL;
4362 goto error;
4363 }
4364 }
4365
Alberto Garcia543770b2018-09-06 12:37:09 +03004366 reopen_state->detect_zeroes =
4367 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4368 if (local_err) {
4369 error_propagate(errp, local_err);
4370 ret = -EINVAL;
4371 goto error;
4372 }
4373
Alberto Garcia57f9db92018-09-06 12:37:06 +03004374 /* All other options (including node-name and driver) must be unchanged.
4375 * Put them back into the QDict, so that they are checked at the end
4376 * of this function. */
4377 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004378
Jeff Cody3d8ce172017-04-07 16:55:30 -04004379 /* If we are to stay read-only, do not allow permission change
4380 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4381 * not set, or if the BDS still has copy_on_read enabled */
4382 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004383 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004384 if (local_err) {
4385 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004386 goto error;
4387 }
4388
Jeff Codye971aa12012-09-20 15:13:19 -04004389 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004390 /*
4391 * If a driver-specific option is missing, it means that we
4392 * should reset it to its default value.
4393 * But not all options allow that, so we need to check it first.
4394 */
4395 ret = bdrv_reset_options_allowed(reopen_state->bs,
4396 reopen_state->options, errp);
4397 if (ret) {
4398 goto error;
4399 }
4400
Jeff Codye971aa12012-09-20 15:13:19 -04004401 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4402 if (ret) {
4403 if (local_err != NULL) {
4404 error_propagate(errp, local_err);
4405 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004406 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004407 error_setg(errp, "failed while preparing to reopen image '%s'",
4408 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004409 }
4410 goto error;
4411 }
4412 } else {
4413 /* It is currently mandatory to have a bdrv_reopen_prepare()
4414 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004415 error_setg(errp, "Block format '%s' used by node '%s' "
4416 "does not support reopening files", drv->format_name,
4417 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004418 ret = -1;
4419 goto error;
4420 }
4421
Max Reitz9ad08c42018-11-16 17:45:24 +01004422 drv_prepared = true;
4423
Alberto Garciabacd9b82019-03-12 18:48:46 +02004424 /*
4425 * We must provide the 'backing' option if the BDS has a backing
4426 * file or if the image file has a backing file name as part of
4427 * its metadata. Otherwise the 'backing' option can be omitted.
4428 */
4429 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004430 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004431 error_setg(errp, "backing is missing for '%s'",
4432 reopen_state->bs->node_name);
4433 ret = -EINVAL;
4434 goto error;
4435 }
4436
Alberto Garciacb828c32019-03-12 18:48:47 +02004437 /*
4438 * Allow changing the 'backing' option. The new value can be
4439 * either a reference to an existing node (using its node name)
4440 * or NULL to simply detach the current backing file.
4441 */
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004442 ret = bdrv_reopen_parse_backing(reopen_state, set_backings_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004443 if (ret < 0) {
4444 goto error;
4445 }
4446 qdict_del(reopen_state->options, "backing");
4447
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004448 /* Options that are not handled are only okay if they are unchanged
4449 * compared to the old state. It is expected that some options are only
4450 * used for the initial open, but not reopen (e.g. filename) */
4451 if (qdict_size(reopen_state->options)) {
4452 const QDictEntry *entry = qdict_first(reopen_state->options);
4453
4454 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004455 QObject *new = entry->value;
4456 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004457
Alberto Garciadb905282018-09-06 12:37:05 +03004458 /* Allow child references (child_name=node_name) as long as they
4459 * point to the current child (i.e. everything stays the same). */
4460 if (qobject_type(new) == QTYPE_QSTRING) {
4461 BdrvChild *child;
4462 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4463 if (!strcmp(child->name, entry->key)) {
4464 break;
4465 }
4466 }
4467
4468 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004469 if (!strcmp(child->bs->node_name,
4470 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004471 continue; /* Found child with this name, skip option */
4472 }
4473 }
4474 }
4475
Max Reitz54fd1b02017-11-14 19:01:26 +01004476 /*
4477 * TODO: When using -drive to specify blockdev options, all values
4478 * will be strings; however, when using -blockdev, blockdev-add or
4479 * filenames using the json:{} pseudo-protocol, they will be
4480 * correctly typed.
4481 * In contrast, reopening options are (currently) always strings
4482 * (because you can only specify them through qemu-io; all other
4483 * callers do not specify any options).
4484 * Therefore, when using anything other than -drive to create a BDS,
4485 * this cannot detect non-string options as unchanged, because
4486 * qobject_is_equal() always returns false for objects of different
4487 * type. In the future, this should be remedied by correctly typing
4488 * all options. For now, this is not too big of an issue because
4489 * the user can simply omit options which cannot be changed anyway,
4490 * so they will stay unchanged.
4491 */
4492 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004493 error_setg(errp, "Cannot change the option '%s'", entry->key);
4494 ret = -EINVAL;
4495 goto error;
4496 }
4497 } while ((entry = qdict_next(reopen_state->options, entry)));
4498 }
4499
Jeff Codye971aa12012-09-20 15:13:19 -04004500 ret = 0;
4501
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004502 /* Restore the original reopen_state->options QDict */
4503 qobject_unref(reopen_state->options);
4504 reopen_state->options = qobject_ref(orig_reopen_opts);
4505
Jeff Codye971aa12012-09-20 15:13:19 -04004506error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004507 if (ret < 0 && drv_prepared) {
4508 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4509 * call drv->bdrv_reopen_abort() before signaling an error
4510 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4511 * when the respective bdrv_reopen_prepare() has failed) */
4512 if (drv->bdrv_reopen_abort) {
4513 drv->bdrv_reopen_abort(reopen_state);
4514 }
4515 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004516 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004517 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004518 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004519 return ret;
4520}
4521
4522/*
4523 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4524 * makes them final by swapping the staging BlockDriverState contents into
4525 * the active BlockDriverState contents.
4526 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004527static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004528{
4529 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004530 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004531 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004532
4533 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004534 bs = reopen_state->bs;
4535 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004536 assert(drv != NULL);
4537
4538 /* If there are any driver level actions to take */
4539 if (drv->bdrv_reopen_commit) {
4540 drv->bdrv_reopen_commit(reopen_state);
4541 }
4542
4543 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004544 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004545 qobject_unref(bs->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004546
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004547 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004548 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004549 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004550 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004551
Alberto Garcia50196d72018-09-06 12:37:03 +03004552 /* Remove child references from bs->options and bs->explicit_options.
4553 * Child options were already removed in bdrv_reopen_queue_child() */
4554 QLIST_FOREACH(child, &bs->children, next) {
4555 qdict_del(bs->explicit_options, child->name);
4556 qdict_del(bs->options, child->name);
4557 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004558 /* backing is probably removed, so it's not handled by previous loop */
4559 qdict_del(bs->explicit_options, "backing");
4560 qdict_del(bs->options, "backing");
4561
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004562 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004563}
4564
4565/*
4566 * Abort the reopen, and delete and free the staged changes in
4567 * reopen_state
4568 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004569static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004570{
4571 BlockDriver *drv;
4572
4573 assert(reopen_state != NULL);
4574 drv = reopen_state->bs->drv;
4575 assert(drv != NULL);
4576
4577 if (drv->bdrv_reopen_abort) {
4578 drv->bdrv_reopen_abort(reopen_state);
4579 }
4580}
4581
4582
Max Reitz64dff522016-01-29 16:36:10 +01004583static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004584{
Max Reitz33384422014-06-20 21:57:33 +02004585 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004586 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004587
Max Reitz30f55fb2016-05-17 16:41:32 +02004588 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004589
Paolo Bonzinifc272912015-12-23 11:48:24 +01004590 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004591 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004592 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004593
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004594 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004595 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004596 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004597 bs->drv->bdrv_close(bs);
4598 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004599 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004600 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004601
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004602 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004603 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004604 }
4605
Alberto Garciadd4118c2019-05-13 16:46:17 +03004606 bs->backing = NULL;
4607 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004608 g_free(bs->opaque);
4609 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004610 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004611 bs->backing_file[0] = '\0';
4612 bs->backing_format[0] = '\0';
4613 bs->total_sectors = 0;
4614 bs->encrypted = false;
4615 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004616 qobject_unref(bs->options);
4617 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004618 bs->options = NULL;
4619 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004620 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004621 bs->full_open_options = NULL;
4622
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004623 bdrv_release_named_dirty_bitmaps(bs);
4624 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4625
Max Reitz33384422014-06-20 21:57:33 +02004626 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4627 g_free(ban);
4628 }
4629 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004630 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004631
4632 /*
4633 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4634 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4635 * gets called.
4636 */
4637 if (bs->quiesce_counter) {
4638 bdrv_drain_all_end_quiesce(bs);
4639 }
bellardb3380822004-03-14 21:38:54 +00004640}
4641
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004642void bdrv_close_all(void)
4643{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004644 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004645
Max Reitzca9bd242016-01-29 16:36:14 +01004646 /* Drop references from requests still in flight, such as canceled block
4647 * jobs whose AIO context has not been polled yet */
4648 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004649
Max Reitzca9bd242016-01-29 16:36:14 +01004650 blk_remove_all_bs();
4651 blockdev_close_all_bdrv_states();
4652
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004653 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004654}
4655
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004656static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004657{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004658 GQueue *queue;
4659 GHashTable *found;
4660 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004661
Max Reitzbd86fb92020-05-13 13:05:13 +02004662 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004663 return false;
4664 }
4665
Max Reitzec9f10f2018-06-13 20:18:15 +02004666 /* If the child @c belongs to the BDS @to, replacing the current
4667 * c->bs by @to would mean to create a loop.
4668 *
4669 * Such a case occurs when appending a BDS to a backing chain.
4670 * For instance, imagine the following chain:
4671 *
4672 * guest device -> node A -> further backing chain...
4673 *
4674 * Now we create a new BDS B which we want to put on top of this
4675 * chain, so we first attach A as its backing node:
4676 *
4677 * node B
4678 * |
4679 * v
4680 * guest device -> node A -> further backing chain...
4681 *
4682 * Finally we want to replace A by B. When doing that, we want to
4683 * replace all pointers to A by pointers to B -- except for the
4684 * pointer from B because (1) that would create a loop, and (2)
4685 * that pointer should simply stay intact:
4686 *
4687 * guest device -> node B
4688 * |
4689 * v
4690 * node A -> further backing chain...
4691 *
4692 * In general, when replacing a node A (c->bs) by a node B (@to),
4693 * if A is a child of B, that means we cannot replace A by B there
4694 * because that would create a loop. Silently detaching A from B
4695 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004696 * place there is the most sensible choice.
4697 *
4698 * We would also create a loop in any cases where @c is only
4699 * indirectly referenced by @to. Prevent this by returning false
4700 * if @c is found (by breadth-first search) anywhere in the whole
4701 * subtree of @to.
4702 */
4703
4704 ret = true;
4705 found = g_hash_table_new(NULL, NULL);
4706 g_hash_table_add(found, to);
4707 queue = g_queue_new();
4708 g_queue_push_tail(queue, to);
4709
4710 while (!g_queue_is_empty(queue)) {
4711 BlockDriverState *v = g_queue_pop_head(queue);
4712 BdrvChild *c2;
4713
4714 QLIST_FOREACH(c2, &v->children, next) {
4715 if (c2 == c) {
4716 ret = false;
4717 break;
4718 }
4719
4720 if (g_hash_table_contains(found, c2->bs)) {
4721 continue;
4722 }
4723
4724 g_queue_push_tail(queue, c2->bs);
4725 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004726 }
4727 }
4728
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004729 g_queue_free(queue);
4730 g_hash_table_destroy(found);
4731
4732 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004733}
4734
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004735typedef struct BdrvRemoveFilterOrCowChild {
4736 BdrvChild *child;
4737 bool is_backing;
4738} BdrvRemoveFilterOrCowChild;
4739
4740static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
4741{
4742 BdrvRemoveFilterOrCowChild *s = opaque;
4743 BlockDriverState *parent_bs = s->child->opaque;
4744
4745 QLIST_INSERT_HEAD(&parent_bs->children, s->child, next);
4746 if (s->is_backing) {
4747 parent_bs->backing = s->child;
4748 } else {
4749 parent_bs->file = s->child;
4750 }
4751
4752 /*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004753 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004754 * because that function is transactionable and it registered own completion
4755 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
4756 * called automatically.
4757 */
4758}
4759
4760static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
4761{
4762 BdrvRemoveFilterOrCowChild *s = opaque;
4763
4764 bdrv_child_free(s->child);
4765}
4766
4767static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
4768 .abort = bdrv_remove_filter_or_cow_child_abort,
4769 .commit = bdrv_remove_filter_or_cow_child_commit,
4770 .clean = g_free,
4771};
4772
4773/*
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004774 * A function to remove backing or file child of @bs.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03004775 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004776 */
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004777static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
4778 BdrvChild *child,
4779 Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004780{
4781 BdrvRemoveFilterOrCowChild *s;
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004782
4783 assert(child == bs->backing || child == bs->file);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004784
4785 if (!child) {
4786 return;
4787 }
4788
4789 if (child->bs) {
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004790 bdrv_replace_child_tran(child, NULL, tran);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004791 }
4792
4793 s = g_new(BdrvRemoveFilterOrCowChild, 1);
4794 *s = (BdrvRemoveFilterOrCowChild) {
4795 .child = child,
4796 .is_backing = (child == bs->backing),
4797 };
4798 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
4799
4800 QLIST_SAFE_REMOVE(child, next);
4801 if (s->is_backing) {
4802 bs->backing = NULL;
4803 } else {
4804 bs->file = NULL;
4805 }
4806}
4807
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004808/*
4809 * A function to remove backing-chain child of @bs if exists: cow child for
4810 * format nodes (always .backing) and filter child for filters (may be .file or
4811 * .backing)
4812 */
4813static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
4814 Transaction *tran)
4815{
4816 bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
4817}
4818
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004819static int bdrv_replace_node_noperm(BlockDriverState *from,
4820 BlockDriverState *to,
4821 bool auto_skip, Transaction *tran,
4822 Error **errp)
4823{
4824 BdrvChild *c, *next;
4825
4826 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4827 assert(c->bs == from);
4828 if (!should_update_child(c, to)) {
4829 if (auto_skip) {
4830 continue;
4831 }
4832 error_setg(errp, "Should not change '%s' link to '%s'",
4833 c->name, from->node_name);
4834 return -EINVAL;
4835 }
4836 if (c->frozen) {
4837 error_setg(errp, "Cannot change '%s' link to '%s'",
4838 c->name, from->node_name);
4839 return -EPERM;
4840 }
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004841 bdrv_replace_child_tran(c, to, tran);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004842 }
4843
4844 return 0;
4845}
4846
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004847/*
4848 * With auto_skip=true bdrv_replace_node_common skips updating from parents
4849 * if it creates a parent-child relation loop or if parent is block-job.
4850 *
4851 * With auto_skip=false the error is returned if from has a parent which should
4852 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004853 *
4854 * With @detach_subchain=true @to must be in a backing chain of @from. In this
4855 * case backing link of the cow-parent of @to is removed.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004856 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004857static int bdrv_replace_node_common(BlockDriverState *from,
4858 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004859 bool auto_skip, bool detach_subchain,
4860 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004861{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004862 Transaction *tran = tran_new();
4863 g_autoptr(GHashTable) found = NULL;
4864 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04004865 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004866 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004867
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004868 if (detach_subchain) {
4869 assert(bdrv_chain_contains(from, to));
4870 assert(from != to);
4871 for (to_cow_parent = from;
4872 bdrv_filter_or_cow_bs(to_cow_parent) != to;
4873 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
4874 {
4875 ;
4876 }
4877 }
4878
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004879 /* Make sure that @from doesn't go away until we have successfully attached
4880 * all of its parents to @to. */
4881 bdrv_ref(from);
4882
Kevin Wolff871abd2019-05-21 19:00:25 +02004883 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01004884 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02004885 bdrv_drained_begin(from);
4886
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004887 /*
4888 * Do the replacement without permission update.
4889 * Replacement may influence the permissions, we should calculate new
4890 * permissions based on new graph. If we fail, we'll roll-back the
4891 * replacement.
4892 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004893 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
4894 if (ret < 0) {
4895 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004896 }
4897
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004898 if (detach_subchain) {
4899 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
4900 }
4901
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004902 found = g_hash_table_new(NULL, NULL);
4903
4904 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
4905 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
4906
4907 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004908 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004909 goto out;
4910 }
4911
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004912 ret = 0;
4913
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004914out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004915 tran_finalize(tran, ret);
4916
Kevin Wolff871abd2019-05-21 19:00:25 +02004917 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004918 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004919
4920 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004921}
4922
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004923int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4924 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004925{
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004926 return bdrv_replace_node_common(from, to, true, false, errp);
4927}
4928
4929int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
4930{
4931 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
4932 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004933}
4934
Jeff Cody8802d1f2012-02-28 15:54:06 -05004935/*
4936 * Add new bs contents at the top of an image chain while the chain is
4937 * live, while keeping required fields on the top layer.
4938 *
4939 * This will modify the BlockDriverState fields, and swap contents
4940 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4941 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03004942 * bs_new must not be attached to a BlockBackend and must not have backing
4943 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04004944 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05004945 * This function does not create any image files.
4946 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004947int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4948 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05004949{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03004950 int ret;
4951 Transaction *tran = tran_new();
4952
4953 assert(!bs_new->backing);
4954
4955 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
4956 &child_of_bds, bdrv_backing_role(bs_new),
4957 &bs_new->backing, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004958 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03004959 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01004960 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004961
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03004962 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004963 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03004964 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004965 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004966
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03004967 ret = bdrv_refresh_perms(bs_new, errp);
4968out:
4969 tran_finalize(tran, ret);
4970
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004971 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03004972
4973 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05004974}
4975
Fam Zheng4f6fd342013-08-23 09:14:47 +08004976static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00004977{
Fam Zheng3718d8a2014-05-23 21:29:43 +08004978 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08004979 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02004980
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01004981 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01004982 if (bs->node_name[0] != '\0') {
4983 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4984 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01004985 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4986
Anton Kuchin30c321f2019-05-07 11:12:56 +03004987 bdrv_close(bs);
4988
Anthony Liguori7267c092011-08-20 22:09:37 -05004989 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00004990}
4991
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03004992BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *node_options,
4993 int flags, Error **errp)
4994{
4995 BlockDriverState *new_node_bs;
4996 Error *local_err = NULL;
4997
4998 new_node_bs = bdrv_open(NULL, NULL, node_options, flags, errp);
4999 if (new_node_bs == NULL) {
5000 error_prepend(errp, "Could not create node: ");
5001 return NULL;
5002 }
5003
5004 bdrv_drained_begin(bs);
5005 bdrv_replace_node(bs, new_node_bs, &local_err);
5006 bdrv_drained_end(bs);
5007
5008 if (local_err) {
5009 bdrv_unref(new_node_bs);
5010 error_propagate(errp, local_err);
5011 return NULL;
5012 }
5013
5014 return new_node_bs;
5015}
5016
aliguorie97fc192009-04-21 23:11:50 +00005017/*
5018 * Run consistency checks on an image
5019 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005020 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005021 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005022 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005023 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005024int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5025 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005026{
Max Reitz908bcd52014-08-07 22:47:55 +02005027 if (bs->drv == NULL) {
5028 return -ENOMEDIUM;
5029 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005030 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005031 return -ENOTSUP;
5032 }
5033
Kevin Wolfe076f332010-06-29 11:43:13 +02005034 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005035 return bs->drv->bdrv_co_check(bs, res, fix);
5036}
5037
Kevin Wolf756e6732010-01-12 12:55:17 +01005038/*
5039 * Return values:
5040 * 0 - success
5041 * -EINVAL - backing format specified, but no file
5042 * -ENOSPC - can't update the backing file because no space is left in the
5043 * image file header
5044 * -ENOTSUP - format driver doesn't support changing the backing file
5045 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005046int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5047 const char *backing_fmt, bool warn)
Kevin Wolf756e6732010-01-12 12:55:17 +01005048{
5049 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005050 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005051
Max Reitzd470ad42017-11-10 21:31:09 +01005052 if (!drv) {
5053 return -ENOMEDIUM;
5054 }
5055
Paolo Bonzini5f377792012-04-12 14:01:01 +02005056 /* Backing file format doesn't make sense without a backing file */
5057 if (backing_fmt && !backing_file) {
5058 return -EINVAL;
5059 }
5060
Eric Blakee54ee1b2020-07-06 15:39:53 -05005061 if (warn && backing_file && !backing_fmt) {
5062 warn_report("Deprecated use of backing file without explicit "
5063 "backing format, use of this image requires "
5064 "potentially unsafe format probing");
5065 }
5066
Kevin Wolf756e6732010-01-12 12:55:17 +01005067 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005068 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005069 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005070 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005071 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005072
5073 if (ret == 0) {
5074 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5075 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005076 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5077 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005078 }
5079 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005080}
5081
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005082/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005083 * Finds the first non-filter node above bs in the chain between
5084 * active and bs. The returned node is either an immediate parent of
5085 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005086 *
5087 * Returns NULL if bs is not found in active's image chain,
5088 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005089 *
5090 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005091 */
5092BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5093 BlockDriverState *bs)
5094{
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005095 bs = bdrv_skip_filters(bs);
5096 active = bdrv_skip_filters(active);
5097
5098 while (active) {
5099 BlockDriverState *next = bdrv_backing_chain_next(active);
5100 if (bs == next) {
5101 return active;
5102 }
5103 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005104 }
5105
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005106 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005107}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005108
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005109/* Given a BDS, searches for the base layer. */
5110BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5111{
5112 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005113}
5114
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005115/*
Max Reitz7b99a262019-06-12 16:07:11 +02005116 * Return true if at least one of the COW (backing) and filter links
5117 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005118 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005119 */
5120bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5121 Error **errp)
5122{
5123 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005124 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005125
Max Reitz7b99a262019-06-12 16:07:11 +02005126 for (i = bs; i != base; i = child_bs(child)) {
5127 child = bdrv_filter_or_cow_child(i);
5128
5129 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005130 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005131 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005132 return true;
5133 }
5134 }
5135
5136 return false;
5137}
5138
5139/*
Max Reitz7b99a262019-06-12 16:07:11 +02005140 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005141 * If any of the links is already frozen the operation is aborted and
5142 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005143 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005144 * Returns 0 on success. On failure returns < 0 and sets @errp.
5145 */
5146int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5147 Error **errp)
5148{
5149 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005150 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005151
5152 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5153 return -EPERM;
5154 }
5155
Max Reitz7b99a262019-06-12 16:07:11 +02005156 for (i = bs; i != base; i = child_bs(child)) {
5157 child = bdrv_filter_or_cow_child(i);
5158 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005159 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005160 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005161 return -EPERM;
5162 }
5163 }
5164
Max Reitz7b99a262019-06-12 16:07:11 +02005165 for (i = bs; i != base; i = child_bs(child)) {
5166 child = bdrv_filter_or_cow_child(i);
5167 if (child) {
5168 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005169 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005170 }
5171
5172 return 0;
5173}
5174
5175/*
Max Reitz7b99a262019-06-12 16:07:11 +02005176 * Unfreeze all COW (backing) and filter links between @bs and @base.
5177 * The caller must ensure that all links are frozen before using this
5178 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005179 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005180 */
5181void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5182{
5183 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005184 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005185
Max Reitz7b99a262019-06-12 16:07:11 +02005186 for (i = bs; i != base; i = child_bs(child)) {
5187 child = bdrv_filter_or_cow_child(i);
5188 if (child) {
5189 assert(child->frozen);
5190 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005191 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005192 }
5193}
5194
5195/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005196 * Drops images above 'base' up to and including 'top', and sets the image
5197 * above 'top' to have base as its backing file.
5198 *
5199 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5200 * information in 'bs' can be properly updated.
5201 *
5202 * E.g., this will convert the following chain:
5203 * bottom <- base <- intermediate <- top <- active
5204 *
5205 * to
5206 *
5207 * bottom <- base <- active
5208 *
5209 * It is allowed for bottom==base, in which case it converts:
5210 *
5211 * base <- intermediate <- top <- active
5212 *
5213 * to
5214 *
5215 * base <- active
5216 *
Jeff Cody54e26902014-06-25 15:40:10 -04005217 * If backing_file_str is non-NULL, it will be used when modifying top's
5218 * overlay image metadata.
5219 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005220 * Error conditions:
5221 * if active == top, that is considered an error
5222 *
5223 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005224int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5225 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005226{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005227 BlockDriverState *explicit_top = top;
5228 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005229 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005230 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005231 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005232 g_autoptr(GSList) updated_children = NULL;
5233 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005234
Kevin Wolf6858eba2017-06-29 19:32:21 +02005235 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005236 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005237
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005238 if (!top->drv || !base->drv) {
5239 goto exit;
5240 }
5241
Kevin Wolf5db15a52015-09-14 15:33:33 +02005242 /* Make sure that base is in the backing chain of top */
5243 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005244 goto exit;
5245 }
5246
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005247 /* If 'base' recursively inherits from 'top' then we should set
5248 * base->inherits_from to top->inherits_from after 'top' and all
5249 * other intermediate nodes have been dropped.
5250 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5251 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005252 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005253 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5254
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005255 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolfbde70712017-06-27 20:36:18 +02005256 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
5257 * we've figured out how they should work. */
Max Reitzf30c66b2019-02-01 20:29:05 +01005258 if (!backing_file_str) {
5259 bdrv_refresh_filename(base);
5260 backing_file_str = base->filename;
5261 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005262
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005263 QLIST_FOREACH(c, &top->parents, next_parent) {
5264 updated_children = g_slist_prepend(updated_children, c);
5265 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005266
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005267 /*
5268 * It seems correct to pass detach_subchain=true here, but it triggers
5269 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5270 * another drained section, which modify the graph (for example, removing
5271 * the child, which we keep in updated_children list). So, it's a TODO.
5272 *
5273 * Note, bug triggered if pass detach_subchain=true here and run
5274 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5275 * That's a FIXME.
5276 */
5277 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005278 if (local_err) {
5279 error_report_err(local_err);
5280 goto exit;
5281 }
5282
5283 for (p = updated_children; p; p = p->next) {
5284 c = p->data;
5285
Max Reitzbd86fb92020-05-13 13:05:13 +02005286 if (c->klass->update_filename) {
5287 ret = c->klass->update_filename(c, base, backing_file_str,
5288 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005289 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005290 /*
5291 * TODO: Actually, we want to rollback all previous iterations
5292 * of this loop, and (which is almost impossible) previous
5293 * bdrv_replace_node()...
5294 *
5295 * Note, that c->klass->update_filename may lead to permission
5296 * update, so it's a bad idea to call it inside permission
5297 * update transaction of bdrv_replace_node.
5298 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005299 error_report_err(local_err);
5300 goto exit;
5301 }
5302 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005303 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005304
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005305 if (update_inherits_from) {
5306 base->inherits_from = explicit_top->inherits_from;
5307 }
5308
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005309 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005310exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005311 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005312 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005313 return ret;
5314}
5315
bellard83f64092006-08-01 16:21:11 +00005316/**
Max Reitz081e4652019-06-12 18:14:13 +02005317 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5318 * sums the size of all data-bearing children. (This excludes backing
5319 * children.)
5320 */
5321static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5322{
5323 BdrvChild *child;
5324 int64_t child_size, sum = 0;
5325
5326 QLIST_FOREACH(child, &bs->children, next) {
5327 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5328 BDRV_CHILD_FILTERED))
5329 {
5330 child_size = bdrv_get_allocated_file_size(child->bs);
5331 if (child_size < 0) {
5332 return child_size;
5333 }
5334 sum += child_size;
5335 }
5336 }
5337
5338 return sum;
5339}
5340
5341/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005342 * Length of a allocated file in bytes. Sparse files are counted by actual
5343 * allocated space. Return < 0 if error or unknown.
5344 */
5345int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5346{
5347 BlockDriver *drv = bs->drv;
5348 if (!drv) {
5349 return -ENOMEDIUM;
5350 }
5351 if (drv->bdrv_get_allocated_file_size) {
5352 return drv->bdrv_get_allocated_file_size(bs);
5353 }
Max Reitz081e4652019-06-12 18:14:13 +02005354
5355 if (drv->bdrv_file_open) {
5356 /*
5357 * Protocol drivers default to -ENOTSUP (most of their data is
5358 * not stored in any of their children (if they even have any),
5359 * so there is no generic way to figure it out).
5360 */
5361 return -ENOTSUP;
5362 } else if (drv->is_filter) {
5363 /* Filter drivers default to the size of their filtered child */
5364 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5365 } else {
5366 /* Other drivers default to summing their children's sizes */
5367 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005368 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005369}
5370
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005371/*
5372 * bdrv_measure:
5373 * @drv: Format driver
5374 * @opts: Creation options for new image
5375 * @in_bs: Existing image containing data for new image (may be NULL)
5376 * @errp: Error object
5377 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5378 * or NULL on error
5379 *
5380 * Calculate file size required to create a new image.
5381 *
5382 * If @in_bs is given then space for allocated clusters and zero clusters
5383 * from that image are included in the calculation. If @opts contains a
5384 * backing file that is shared by @in_bs then backing clusters may be omitted
5385 * from the calculation.
5386 *
5387 * If @in_bs is NULL then the calculation includes no allocated clusters
5388 * unless a preallocation option is given in @opts.
5389 *
5390 * Note that @in_bs may use a different BlockDriver from @drv.
5391 *
5392 * If an error occurs the @errp pointer is set.
5393 */
5394BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5395 BlockDriverState *in_bs, Error **errp)
5396{
5397 if (!drv->bdrv_measure) {
5398 error_setg(errp, "Block driver '%s' does not support size measurement",
5399 drv->format_name);
5400 return NULL;
5401 }
5402
5403 return drv->bdrv_measure(opts, in_bs, errp);
5404}
5405
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005406/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005407 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005408 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005409int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005410{
5411 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005412
bellard83f64092006-08-01 16:21:11 +00005413 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005414 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005415
Kevin Wolfb94a2612013-10-29 12:18:58 +01005416 if (drv->has_variable_length) {
5417 int ret = refresh_total_sectors(bs, bs->total_sectors);
5418 if (ret < 0) {
5419 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005420 }
bellard83f64092006-08-01 16:21:11 +00005421 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005422 return bs->total_sectors;
5423}
5424
5425/**
5426 * Return length in bytes on success, -errno on error.
5427 * The length is always a multiple of BDRV_SECTOR_SIZE.
5428 */
5429int64_t bdrv_getlength(BlockDriverState *bs)
5430{
5431 int64_t ret = bdrv_nb_sectors(bs);
5432
Eric Blake122860b2020-11-05 09:51:22 -06005433 if (ret < 0) {
5434 return ret;
5435 }
5436 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5437 return -EFBIG;
5438 }
5439 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005440}
5441
bellard19cb3732006-08-19 11:45:59 +00005442/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005443void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005444{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005445 int64_t nb_sectors = bdrv_nb_sectors(bs);
5446
5447 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005448}
bellardcf989512004-02-16 21:56:36 +00005449
Eric Blake54115412016-06-23 16:37:26 -06005450bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005451{
5452 return bs->sg;
5453}
5454
Max Reitzae23f782019-06-12 22:57:15 +02005455/**
5456 * Return whether the given node supports compressed writes.
5457 */
5458bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5459{
5460 BlockDriverState *filtered;
5461
5462 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5463 return false;
5464 }
5465
5466 filtered = bdrv_filter_bs(bs);
5467 if (filtered) {
5468 /*
5469 * Filters can only forward compressed writes, so we have to
5470 * check the child.
5471 */
5472 return bdrv_supports_compressed_writes(filtered);
5473 }
5474
5475 return true;
5476}
5477
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005478const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005479{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005480 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005481}
5482
Stefan Hajnocziada42402014-08-27 12:08:55 +01005483static int qsort_strcmp(const void *a, const void *b)
5484{
Max Reitzceff5bd2016-10-12 22:49:05 +02005485 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005486}
5487
ths5fafdf22007-09-16 21:08:06 +00005488void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005489 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005490{
5491 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005492 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005493 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005494 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005495
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005496 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005497 if (drv->format_name) {
5498 bool found = false;
5499 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005500
5501 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5502 continue;
5503 }
5504
Jeff Codye855e4f2014-04-28 18:29:54 -04005505 while (formats && i && !found) {
5506 found = !strcmp(formats[--i], drv->format_name);
5507 }
5508
5509 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005510 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005511 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005512 }
5513 }
bellardea2384d2004-08-01 21:59:26 +00005514 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005515
Max Reitzeb0df692016-10-12 22:49:06 +02005516 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5517 const char *format_name = block_driver_modules[i].format_name;
5518
5519 if (format_name) {
5520 bool found = false;
5521 int j = count;
5522
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005523 if (use_bdrv_whitelist &&
5524 !bdrv_format_is_whitelisted(format_name, read_only)) {
5525 continue;
5526 }
5527
Max Reitzeb0df692016-10-12 22:49:06 +02005528 while (formats && j && !found) {
5529 found = !strcmp(formats[--j], format_name);
5530 }
5531
5532 if (!found) {
5533 formats = g_renew(const char *, formats, count + 1);
5534 formats[count++] = format_name;
5535 }
5536 }
5537 }
5538
Stefan Hajnocziada42402014-08-27 12:08:55 +01005539 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5540
5541 for (i = 0; i < count; i++) {
5542 it(opaque, formats[i]);
5543 }
5544
Jeff Codye855e4f2014-04-28 18:29:54 -04005545 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005546}
5547
Benoît Canetdc364f42014-01-23 21:31:32 +01005548/* This function is to find a node in the bs graph */
5549BlockDriverState *bdrv_find_node(const char *node_name)
5550{
5551 BlockDriverState *bs;
5552
5553 assert(node_name);
5554
5555 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5556 if (!strcmp(node_name, bs->node_name)) {
5557 return bs;
5558 }
5559 }
5560 return NULL;
5561}
5562
Benoît Canetc13163f2014-01-23 21:31:34 +01005563/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005564BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5565 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005566{
Eric Blake9812e712020-10-27 00:05:47 -05005567 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005568 BlockDriverState *bs;
5569
5570 list = NULL;
5571 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005572 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005573 if (!info) {
5574 qapi_free_BlockDeviceInfoList(list);
5575 return NULL;
5576 }
Eric Blake9812e712020-10-27 00:05:47 -05005577 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005578 }
5579
5580 return list;
5581}
5582
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005583typedef struct XDbgBlockGraphConstructor {
5584 XDbgBlockGraph *graph;
5585 GHashTable *graph_nodes;
5586} XDbgBlockGraphConstructor;
5587
5588static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5589{
5590 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5591
5592 gr->graph = g_new0(XDbgBlockGraph, 1);
5593 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5594
5595 return gr;
5596}
5597
5598static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5599{
5600 XDbgBlockGraph *graph = gr->graph;
5601
5602 g_hash_table_destroy(gr->graph_nodes);
5603 g_free(gr);
5604
5605 return graph;
5606}
5607
5608static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5609{
5610 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5611
5612 if (ret != 0) {
5613 return ret;
5614 }
5615
5616 /*
5617 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5618 * answer of g_hash_table_lookup.
5619 */
5620 ret = g_hash_table_size(gr->graph_nodes) + 1;
5621 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5622
5623 return ret;
5624}
5625
5626static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5627 XDbgBlockGraphNodeType type, const char *name)
5628{
5629 XDbgBlockGraphNode *n;
5630
5631 n = g_new0(XDbgBlockGraphNode, 1);
5632
5633 n->id = xdbg_graph_node_num(gr, node);
5634 n->type = type;
5635 n->name = g_strdup(name);
5636
Eric Blake9812e712020-10-27 00:05:47 -05005637 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005638}
5639
5640static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5641 const BdrvChild *child)
5642{
Max Reitzcdb1cec2019-11-08 13:34:52 +01005643 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005644 XDbgBlockGraphEdge *edge;
5645
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005646 edge = g_new0(XDbgBlockGraphEdge, 1);
5647
5648 edge->parent = xdbg_graph_node_num(gr, parent);
5649 edge->child = xdbg_graph_node_num(gr, child->bs);
5650 edge->name = g_strdup(child->name);
5651
Max Reitzcdb1cec2019-11-08 13:34:52 +01005652 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5653 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5654
5655 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005656 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005657 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01005658 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005659 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005660 }
5661 }
5662
Eric Blake9812e712020-10-27 00:05:47 -05005663 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005664}
5665
5666
5667XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5668{
5669 BlockBackend *blk;
5670 BlockJob *job;
5671 BlockDriverState *bs;
5672 BdrvChild *child;
5673 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5674
5675 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5676 char *allocated_name = NULL;
5677 const char *name = blk_name(blk);
5678
5679 if (!*name) {
5680 name = allocated_name = blk_get_attached_dev_id(blk);
5681 }
5682 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5683 name);
5684 g_free(allocated_name);
5685 if (blk_root(blk)) {
5686 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5687 }
5688 }
5689
5690 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5691 GSList *el;
5692
5693 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5694 job->job.id);
5695 for (el = job->nodes; el; el = el->next) {
5696 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5697 }
5698 }
5699
5700 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5701 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5702 bs->node_name);
5703 QLIST_FOREACH(child, &bs->children, next) {
5704 xdbg_graph_add_edge(gr, bs, child);
5705 }
5706 }
5707
5708 return xdbg_graph_finalize(gr);
5709}
5710
Benoît Canet12d3ba82014-01-23 21:31:35 +01005711BlockDriverState *bdrv_lookup_bs(const char *device,
5712 const char *node_name,
5713 Error **errp)
5714{
Markus Armbruster7f06d472014-10-07 13:59:12 +02005715 BlockBackend *blk;
5716 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005717
Benoît Canet12d3ba82014-01-23 21:31:35 +01005718 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02005719 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005720
Markus Armbruster7f06d472014-10-07 13:59:12 +02005721 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005722 bs = blk_bs(blk);
5723 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02005724 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02005725 }
5726
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005727 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005728 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005729 }
5730
Benoît Canetdd67fa52014-02-12 17:15:06 +01005731 if (node_name) {
5732 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005733
Benoît Canetdd67fa52014-02-12 17:15:06 +01005734 if (bs) {
5735 return bs;
5736 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005737 }
5738
Connor Kuehl785ec4b2021-03-05 09:19:28 -06005739 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01005740 device ? device : "",
5741 node_name ? node_name : "");
5742 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005743}
5744
Jeff Cody5a6684d2014-06-25 15:40:09 -04005745/* If 'base' is in the same chain as 'top', return true. Otherwise,
5746 * return false. If either argument is NULL, return false. */
5747bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5748{
5749 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005750 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04005751 }
5752
5753 return top != NULL;
5754}
5755
Fam Zheng04df7652014-10-31 11:32:54 +08005756BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5757{
5758 if (!bs) {
5759 return QTAILQ_FIRST(&graph_bdrv_states);
5760 }
5761 return QTAILQ_NEXT(bs, node_list);
5762}
5763
Kevin Wolf0f122642018-03-28 18:29:18 +02005764BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5765{
5766 if (!bs) {
5767 return QTAILQ_FIRST(&all_bdrv_states);
5768 }
5769 return QTAILQ_NEXT(bs, bs_list);
5770}
5771
Fam Zheng20a9e772014-10-31 11:32:55 +08005772const char *bdrv_get_node_name(const BlockDriverState *bs)
5773{
5774 return bs->node_name;
5775}
5776
Kevin Wolf1f0c4612016-03-22 18:38:44 +01005777const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005778{
5779 BdrvChild *c;
5780 const char *name;
5781
5782 /* If multiple parents have a name, just pick the first one. */
5783 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005784 if (c->klass->get_name) {
5785 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005786 if (name && *name) {
5787 return name;
5788 }
5789 }
5790 }
5791
5792 return NULL;
5793}
5794
Markus Armbruster7f06d472014-10-07 13:59:12 +02005795/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02005796const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005797{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005798 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00005799}
5800
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005801/* This can be used to identify nodes that might not have a device
5802 * name associated. Since node and device names live in the same
5803 * namespace, the result is unambiguous. The exception is if both are
5804 * absent, then this returns an empty (non-null) string. */
5805const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5806{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005807 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005808}
5809
Markus Armbrusterc8433282012-06-05 16:49:24 +02005810int bdrv_get_flags(BlockDriverState *bs)
5811{
5812 return bs->open_flags;
5813}
5814
Peter Lieven3ac21622013-06-28 12:47:42 +02005815int bdrv_has_zero_init_1(BlockDriverState *bs)
5816{
5817 return 1;
5818}
5819
Kevin Wolff2feebb2010-04-14 17:30:35 +02005820int bdrv_has_zero_init(BlockDriverState *bs)
5821{
Max Reitz93393e62019-06-12 17:03:38 +02005822 BlockDriverState *filtered;
5823
Max Reitzd470ad42017-11-10 21:31:09 +01005824 if (!bs->drv) {
5825 return 0;
5826 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005827
Paolo Bonzini11212d82013-09-04 19:00:27 +02005828 /* If BS is a copy on write image, it is initialized to
5829 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02005830 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02005831 return 0;
5832 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02005833 if (bs->drv->bdrv_has_zero_init) {
5834 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02005835 }
Max Reitz93393e62019-06-12 17:03:38 +02005836
5837 filtered = bdrv_filter_bs(bs);
5838 if (filtered) {
5839 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005840 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005841
Peter Lieven3ac21622013-06-28 12:47:42 +02005842 /* safe default */
5843 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02005844}
5845
Peter Lieven4ce78692013-10-24 12:06:54 +02005846bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5847{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03005848 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02005849 return false;
5850 }
5851
Eric Blakee24d8132018-01-26 13:34:39 -06005852 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02005853}
5854
ths5fafdf22007-09-16 21:08:06 +00005855void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00005856 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00005857{
Kevin Wolf3574c602011-10-26 11:02:11 +02005858 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00005859}
5860
bellardfaea38e2006-08-05 21:31:00 +00005861int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5862{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005863 int ret;
bellardfaea38e2006-08-05 21:31:00 +00005864 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005865 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5866 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00005867 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005868 }
5869 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02005870 BlockDriverState *filtered = bdrv_filter_bs(bs);
5871 if (filtered) {
5872 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005873 }
bellardfaea38e2006-08-05 21:31:00 +00005874 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005875 }
bellardfaea38e2006-08-05 21:31:00 +00005876 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005877 ret = drv->bdrv_get_info(bs, bdi);
5878 if (ret < 0) {
5879 return ret;
5880 }
5881
5882 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
5883 return -EINVAL;
5884 }
5885
5886 return 0;
bellardfaea38e2006-08-05 21:31:00 +00005887}
5888
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005889ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5890 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02005891{
5892 BlockDriver *drv = bs->drv;
5893 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005894 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02005895 }
5896 return NULL;
5897}
5898
Anton Nefedovd9245592019-09-23 15:17:37 +03005899BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5900{
5901 BlockDriver *drv = bs->drv;
5902 if (!drv || !drv->bdrv_get_specific_stats) {
5903 return NULL;
5904 }
5905 return drv->bdrv_get_specific_stats(bs);
5906}
5907
Eric Blakea31939e2015-11-18 01:52:54 -07005908void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005909{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005910 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005911 return;
5912 }
5913
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005914 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005915}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005916
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005917static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01005918{
5919 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02005920 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005921 }
5922
5923 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005924 assert(bs->drv->bdrv_debug_remove_breakpoint);
5925 return bs;
5926 }
5927
5928 return NULL;
5929}
5930
5931int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5932 const char *tag)
5933{
5934 bs = bdrv_find_debug_node(bs);
5935 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01005936 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5937 }
5938
5939 return -ENOTSUP;
5940}
5941
Fam Zheng4cc70e92013-11-20 10:01:54 +08005942int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5943{
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005944 bs = bdrv_find_debug_node(bs);
5945 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08005946 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5947 }
5948
5949 return -ENOTSUP;
5950}
5951
Kevin Wolf41c695c2012-12-06 14:32:58 +01005952int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5953{
Max Reitz938789e2014-03-10 23:44:08 +01005954 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02005955 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005956 }
5957
5958 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5959 return bs->drv->bdrv_debug_resume(bs, tag);
5960 }
5961
5962 return -ENOTSUP;
5963}
5964
5965bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5966{
5967 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02005968 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005969 }
5970
5971 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5972 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5973 }
5974
5975 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005976}
5977
Jeff Codyb1b1d782012-10-16 15:49:09 -04005978/* backing_file can either be relative, or absolute, or a protocol. If it is
5979 * relative, it must be relative to the chain. So, passing in bs->filename
5980 * from a BDS as backing_file should not be done, as that may be relative to
5981 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005982BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5983 const char *backing_file)
5984{
Jeff Codyb1b1d782012-10-16 15:49:09 -04005985 char *filename_full = NULL;
5986 char *backing_file_full = NULL;
5987 char *filename_tmp = NULL;
5988 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02005989 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005990 BlockDriverState *curr_bs = NULL;
5991 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005992 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005993
5994 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005995 return NULL;
5996 }
5997
Jeff Codyb1b1d782012-10-16 15:49:09 -04005998 filename_full = g_malloc(PATH_MAX);
5999 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006000
6001 is_protocol = path_has_protocol(backing_file);
6002
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006003 /*
6004 * Being largely a legacy function, skip any filters here
6005 * (because filters do not have normal filenames, so they cannot
6006 * match anyway; and allowing json:{} filenames is a bit out of
6007 * scope).
6008 */
6009 for (curr_bs = bdrv_skip_filters(bs);
6010 bdrv_cow_child(curr_bs) != NULL;
6011 curr_bs = bs_below)
6012 {
6013 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006014
Max Reitz0b877d02018-08-01 20:34:11 +02006015 if (bdrv_backing_overridden(curr_bs)) {
6016 /*
6017 * If the backing file was overridden, we can only compare
6018 * directly against the backing node's filename.
6019 */
6020
6021 if (!filenames_refreshed) {
6022 /*
6023 * This will automatically refresh all of the
6024 * filenames in the rest of the backing chain, so we
6025 * only need to do this once.
6026 */
6027 bdrv_refresh_filename(bs_below);
6028 filenames_refreshed = true;
6029 }
6030
6031 if (strcmp(backing_file, bs_below->filename) == 0) {
6032 retval = bs_below;
6033 break;
6034 }
6035 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6036 /*
6037 * If either of the filename paths is actually a protocol, then
6038 * compare unmodified paths; otherwise make paths relative.
6039 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006040 char *backing_file_full_ret;
6041
Jeff Codyb1b1d782012-10-16 15:49:09 -04006042 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006043 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006044 break;
6045 }
Jeff Cody418661e2017-01-25 20:08:20 -05006046 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006047 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6048 NULL);
6049 if (backing_file_full_ret) {
6050 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6051 g_free(backing_file_full_ret);
6052 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006053 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006054 break;
6055 }
Jeff Cody418661e2017-01-25 20:08:20 -05006056 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006057 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006058 /* If not an absolute filename path, make it relative to the current
6059 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006060 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6061 NULL);
6062 /* We are going to compare canonicalized absolute pathnames */
6063 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6064 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006065 continue;
6066 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006067 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006068
6069 /* We need to make sure the backing filename we are comparing against
6070 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006071 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6072 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6073 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006074 continue;
6075 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006076 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006077
6078 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006079 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006080 break;
6081 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006082 }
6083 }
6084
Jeff Codyb1b1d782012-10-16 15:49:09 -04006085 g_free(filename_full);
6086 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006087 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006088}
6089
bellardea2384d2004-08-01 21:59:26 +00006090void bdrv_init(void)
6091{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006092 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006093}
pbrookce1a14d2006-08-07 02:38:06 +00006094
Markus Armbrustereb852012009-10-27 18:41:44 +01006095void bdrv_init_with_whitelist(void)
6096{
6097 use_bdrv_whitelist = 1;
6098 bdrv_init();
6099}
6100
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03006101int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006102{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006103 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006104 Error *local_err = NULL;
6105 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006106 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006107
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006108 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006109 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006110 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006111
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006112 QLIST_FOREACH(child, &bs->children, next) {
Paolo Bonzini2b148f32018-03-01 17:36:18 +01006113 bdrv_co_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006114 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006115 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006116 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006117 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006118 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006119
Kevin Wolfdafe0962017-11-16 13:00:01 +01006120 /*
6121 * Update permissions, they may differ for inactive nodes.
6122 *
6123 * Note that the required permissions of inactive images are always a
6124 * subset of the permissions required after activating the image. This
6125 * allows us to just get the permissions upfront without restricting
6126 * drv->bdrv_invalidate_cache().
6127 *
6128 * It also means that in error cases, we don't have to try and revert to
6129 * the old permissions (which is an operation that could fail, too). We can
6130 * just keep the extended permissions for the next time that an activation
6131 * of the image is tried.
6132 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006133 if (bs->open_flags & BDRV_O_INACTIVE) {
6134 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006135 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006136 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006137 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006138 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006139 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006140
Kevin Wolf7bb49412019-12-17 15:06:38 +01006141 if (bs->drv->bdrv_co_invalidate_cache) {
6142 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6143 if (local_err) {
6144 bs->open_flags |= BDRV_O_INACTIVE;
6145 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006146 return -EINVAL;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006147 }
6148 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006149
Kevin Wolf7bb49412019-12-17 15:06:38 +01006150 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6151 bdrv_dirty_bitmap_skip_store(bm, false);
6152 }
6153
6154 ret = refresh_total_sectors(bs, bs->total_sectors);
6155 if (ret < 0) {
6156 bs->open_flags |= BDRV_O_INACTIVE;
6157 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006158 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006159 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006160 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006161
6162 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006163 if (parent->klass->activate) {
6164 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006165 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006166 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006167 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006168 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006169 }
6170 }
6171 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006172
6173 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006174}
6175
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006176void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006177{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006178 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006179 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006180
Kevin Wolf88be7b42016-05-20 18:49:07 +02006181 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006182 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006183 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006184
6185 aio_context_acquire(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006186 ret = bdrv_invalidate_cache(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006187 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006188 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006189 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006190 return;
6191 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006192 }
6193}
6194
Kevin Wolf9e372712018-11-23 15:11:14 +01006195static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6196{
6197 BdrvChild *parent;
6198
6199 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006200 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006201 BlockDriverState *parent_bs = parent->opaque;
6202 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6203 return true;
6204 }
6205 }
6206 }
6207
6208 return false;
6209}
6210
6211static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006212{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006213 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006214 int ret;
6215
Max Reitzd470ad42017-11-10 21:31:09 +01006216 if (!bs->drv) {
6217 return -ENOMEDIUM;
6218 }
6219
Kevin Wolf9e372712018-11-23 15:11:14 +01006220 /* Make sure that we don't inactivate a child before its parent.
6221 * It will be covered by recursion from the yet active parent. */
6222 if (bdrv_has_bds_parent(bs, true)) {
6223 return 0;
6224 }
6225
6226 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6227
6228 /* Inactivate this node */
6229 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006230 ret = bs->drv->bdrv_inactivate(bs);
6231 if (ret < 0) {
6232 return ret;
6233 }
6234 }
6235
Kevin Wolf9e372712018-11-23 15:11:14 +01006236 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006237 if (parent->klass->inactivate) {
6238 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006239 if (ret < 0) {
6240 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006241 }
6242 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006243 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006244
Kevin Wolf9e372712018-11-23 15:11:14 +01006245 bs->open_flags |= BDRV_O_INACTIVE;
6246
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006247 /*
6248 * Update permissions, they may differ for inactive nodes.
6249 * We only tried to loosen restrictions, so errors are not fatal, ignore
6250 * them.
6251 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006252 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006253
6254 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006255 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006256 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006257 if (ret < 0) {
6258 return ret;
6259 }
6260 }
6261
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006262 return 0;
6263}
6264
6265int bdrv_inactivate_all(void)
6266{
Max Reitz79720af2016-03-16 19:54:44 +01006267 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006268 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006269 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006270 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006271
Kevin Wolf88be7b42016-05-20 18:49:07 +02006272 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006273 AioContext *aio_context = bdrv_get_aio_context(bs);
6274
6275 if (!g_slist_find(aio_ctxs, aio_context)) {
6276 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6277 aio_context_acquire(aio_context);
6278 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006279 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006280
Kevin Wolf9e372712018-11-23 15:11:14 +01006281 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6282 /* Nodes with BDS parents are covered by recursion from the last
6283 * parent that gets inactivated. Don't inactivate them a second
6284 * time if that has already happened. */
6285 if (bdrv_has_bds_parent(bs, false)) {
6286 continue;
6287 }
6288 ret = bdrv_inactivate_recurse(bs);
6289 if (ret < 0) {
6290 bdrv_next_cleanup(&it);
6291 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006292 }
6293 }
6294
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006295out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006296 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6297 AioContext *aio_context = ctx->data;
6298 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006299 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006300 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006301
6302 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006303}
6304
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006305/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006306/* removable device support */
6307
6308/**
6309 * Return TRUE if the media is present
6310 */
Max Reitze031f752015-10-19 17:53:11 +02006311bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006312{
6313 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006314 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006315
Max Reitze031f752015-10-19 17:53:11 +02006316 if (!drv) {
6317 return false;
6318 }
Max Reitz28d7a782015-10-19 17:53:13 +02006319 if (drv->bdrv_is_inserted) {
6320 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006321 }
Max Reitz28d7a782015-10-19 17:53:13 +02006322 QLIST_FOREACH(child, &bs->children, next) {
6323 if (!bdrv_is_inserted(child->bs)) {
6324 return false;
6325 }
6326 }
6327 return true;
bellard19cb3732006-08-19 11:45:59 +00006328}
6329
6330/**
bellard19cb3732006-08-19 11:45:59 +00006331 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6332 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006333void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006334{
6335 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006336
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006337 if (drv && drv->bdrv_eject) {
6338 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006339 }
bellard19cb3732006-08-19 11:45:59 +00006340}
6341
bellard19cb3732006-08-19 11:45:59 +00006342/**
6343 * Lock or unlock the media (if it is locked, the user won't be able
6344 * to eject it manually).
6345 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006346void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006347{
6348 BlockDriver *drv = bs->drv;
6349
Markus Armbruster025e8492011-09-06 18:58:47 +02006350 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006351
Markus Armbruster025e8492011-09-06 18:58:47 +02006352 if (drv && drv->bdrv_lock_medium) {
6353 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006354 }
6355}
ths985a03b2007-12-24 16:10:43 +00006356
Fam Zheng9fcb0252013-08-23 09:14:46 +08006357/* Get a reference to bs */
6358void bdrv_ref(BlockDriverState *bs)
6359{
6360 bs->refcnt++;
6361}
6362
6363/* Release a previously grabbed reference to bs.
6364 * If after releasing, reference count is zero, the BlockDriverState is
6365 * deleted. */
6366void bdrv_unref(BlockDriverState *bs)
6367{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006368 if (!bs) {
6369 return;
6370 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006371 assert(bs->refcnt > 0);
6372 if (--bs->refcnt == 0) {
6373 bdrv_delete(bs);
6374 }
6375}
6376
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006377struct BdrvOpBlocker {
6378 Error *reason;
6379 QLIST_ENTRY(BdrvOpBlocker) list;
6380};
6381
6382bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6383{
6384 BdrvOpBlocker *blocker;
6385 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6386 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6387 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006388 error_propagate_prepend(errp, error_copy(blocker->reason),
6389 "Node '%s' is busy: ",
6390 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006391 return true;
6392 }
6393 return false;
6394}
6395
6396void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6397{
6398 BdrvOpBlocker *blocker;
6399 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6400
Markus Armbruster5839e532014-08-19 10:31:08 +02006401 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006402 blocker->reason = reason;
6403 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6404}
6405
6406void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6407{
6408 BdrvOpBlocker *blocker, *next;
6409 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6410 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6411 if (blocker->reason == reason) {
6412 QLIST_REMOVE(blocker, list);
6413 g_free(blocker);
6414 }
6415 }
6416}
6417
6418void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6419{
6420 int i;
6421 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6422 bdrv_op_block(bs, i, reason);
6423 }
6424}
6425
6426void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6427{
6428 int i;
6429 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6430 bdrv_op_unblock(bs, i, reason);
6431 }
6432}
6433
6434bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6435{
6436 int i;
6437
6438 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6439 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6440 return false;
6441 }
6442 }
6443 return true;
6444}
6445
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006446void bdrv_img_create(const char *filename, const char *fmt,
6447 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006448 char *options, uint64_t img_size, int flags, bool quiet,
6449 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006450{
Chunyan Liu83d05212014-06-05 17:20:51 +08006451 QemuOptsList *create_opts = NULL;
6452 QemuOpts *opts = NULL;
6453 const char *backing_fmt, *backing_file;
6454 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006455 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006456 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006457 int ret = 0;
6458
6459 /* Find driver and parse its options */
6460 drv = bdrv_find_format(fmt);
6461 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006462 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006463 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006464 }
6465
Max Reitzb65a5e12015-02-05 13:58:12 -05006466 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006467 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006468 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006469 }
6470
Max Reitzc6149722014-12-02 18:32:45 +01006471 if (!drv->create_opts) {
6472 error_setg(errp, "Format driver '%s' does not support image creation",
6473 drv->format_name);
6474 return;
6475 }
6476
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006477 if (!proto_drv->create_opts) {
6478 error_setg(errp, "Protocol driver '%s' does not support image creation",
6479 proto_drv->format_name);
6480 return;
6481 }
6482
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006483 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006484 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006485 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006486
Chunyan Liu83d05212014-06-05 17:20:51 +08006487 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006488
6489 /* Parse -o options */
6490 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006491 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006492 goto out;
6493 }
6494 }
6495
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006496 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6497 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6498 } else if (img_size != UINT64_C(-1)) {
6499 error_setg(errp, "The image size must be specified only once");
6500 goto out;
6501 }
6502
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006503 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006504 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006505 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006506 error_setg(errp, "Backing file not supported for file format '%s'",
6507 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006508 goto out;
6509 }
6510 }
6511
6512 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006513 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006514 error_setg(errp, "Backing file format not supported for file "
6515 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006516 goto out;
6517 }
6518 }
6519
Chunyan Liu83d05212014-06-05 17:20:51 +08006520 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6521 if (backing_file) {
6522 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006523 error_setg(errp, "Error: Trying to create an image with the "
6524 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006525 goto out;
6526 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006527 if (backing_file[0] == '\0') {
6528 error_setg(errp, "Expected backing file name, got empty string");
6529 goto out;
6530 }
Jes Sorensen792da932010-12-16 13:52:17 +01006531 }
6532
Chunyan Liu83d05212014-06-05 17:20:51 +08006533 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006534
John Snow6e6e55f2017-07-17 20:34:22 -04006535 /* The size for the image must always be specified, unless we have a backing
6536 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006537 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006538 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6539 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006540 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006541 int back_flags;
6542 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006543
Max Reitz645ae7d2019-02-01 20:29:14 +01006544 full_backing =
6545 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6546 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006547 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006548 goto out;
6549 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006550 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006551
Max Reitzd5b23992021-06-22 16:00:30 +02006552 /*
6553 * No need to do I/O here, which allows us to open encrypted
6554 * backing images without needing the secret
6555 */
John Snow6e6e55f2017-07-17 20:34:22 -04006556 back_flags = flags;
6557 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02006558 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04006559
Fam Zhengcc954f02017-12-15 16:04:45 +08006560 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006561 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006562 qdict_put_str(backing_options, "driver", backing_fmt);
6563 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006564 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006565
6566 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6567 &local_err);
6568 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006569 if (!bs) {
6570 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006571 goto out;
6572 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006573 if (!backing_fmt) {
6574 warn_report("Deprecated use of backing file without explicit "
6575 "backing format (detected format of %s)",
6576 bs->drv->format_name);
6577 if (bs->drv != &bdrv_raw) {
6578 /*
6579 * A probe of raw deserves the most attention:
6580 * leaving the backing format out of the image
6581 * will ensure bs->probed is set (ensuring we
6582 * don't accidentally commit into the backing
6583 * file), and allow more spots to warn the users
6584 * to fix their toolchain when opening this image
6585 * later. For other images, we can safely record
6586 * the format that we probed.
6587 */
6588 backing_fmt = bs->drv->format_name;
6589 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
6590 NULL);
6591 }
6592 }
John Snow6e6e55f2017-07-17 20:34:22 -04006593 if (size == -1) {
6594 /* Opened BS, have no size */
6595 size = bdrv_getlength(bs);
6596 if (size < 0) {
6597 error_setg_errno(errp, -size, "Could not get size of '%s'",
6598 backing_file);
6599 bdrv_unref(bs);
6600 goto out;
6601 }
6602 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6603 }
6604 bdrv_unref(bs);
6605 }
Eric Blaked9f059a2020-07-06 15:39:54 -05006606 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6607 } else if (backing_file && !backing_fmt) {
6608 warn_report("Deprecated use of unopened backing file without "
6609 "explicit backing format, use of this image requires "
6610 "potentially unsafe format probing");
6611 }
John Snow6e6e55f2017-07-17 20:34:22 -04006612
6613 if (size == -1) {
6614 error_setg(errp, "Image creation needs a size parameter");
6615 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006616 }
6617
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006618 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02006619 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08006620 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006621 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05006622 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006623 }
Chunyan Liu83d05212014-06-05 17:20:51 +08006624
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006625 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08006626
Max Reitzcc84d902013-09-06 17:14:26 +02006627 if (ret == -EFBIG) {
6628 /* This is generally a better message than whatever the driver would
6629 * deliver (especially because of the cluster_size_hint), since that
6630 * is most probably not much different from "image too large". */
6631 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08006632 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02006633 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006634 }
Max Reitzcc84d902013-09-06 17:14:26 +02006635 error_setg(errp, "The image size is too large for file format '%s'"
6636 "%s", fmt, cluster_size_hint);
6637 error_free(local_err);
6638 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006639 }
6640
6641out:
Chunyan Liu83d05212014-06-05 17:20:51 +08006642 qemu_opts_del(opts);
6643 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03006644 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006645}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006646
6647AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6648{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00006649 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006650}
6651
Kevin Wolfe336fd42020-10-05 17:58:53 +02006652AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6653{
6654 Coroutine *self = qemu_coroutine_self();
6655 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6656 AioContext *new_ctx;
6657
6658 /*
6659 * Increase bs->in_flight to ensure that this operation is completed before
6660 * moving the node to a different AioContext. Read new_ctx only afterwards.
6661 */
6662 bdrv_inc_in_flight(bs);
6663
6664 new_ctx = bdrv_get_aio_context(bs);
6665 aio_co_reschedule_self(new_ctx);
6666 return old_ctx;
6667}
6668
6669void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6670{
6671 aio_co_reschedule_self(old_ctx);
6672 bdrv_dec_in_flight(bs);
6673}
6674
Kevin Wolf18c6ac12020-10-05 17:58:54 +02006675void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6676{
6677 AioContext *ctx = bdrv_get_aio_context(bs);
6678
6679 /* In the main thread, bs->aio_context won't change concurrently */
6680 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6681
6682 /*
6683 * We're in coroutine context, so we already hold the lock of the main
6684 * loop AioContext. Don't lock it twice to avoid deadlocks.
6685 */
6686 assert(qemu_in_coroutine());
6687 if (ctx != qemu_get_aio_context()) {
6688 aio_context_acquire(ctx);
6689 }
6690}
6691
6692void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6693{
6694 AioContext *ctx = bdrv_get_aio_context(bs);
6695
6696 assert(qemu_in_coroutine());
6697 if (ctx != qemu_get_aio_context()) {
6698 aio_context_release(ctx);
6699 }
6700}
6701
Fam Zheng052a7572017-04-10 20:09:25 +08006702void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6703{
6704 aio_co_enter(bdrv_get_aio_context(bs), co);
6705}
6706
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006707static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6708{
6709 QLIST_REMOVE(ban, list);
6710 g_free(ban);
6711}
6712
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006713static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006714{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006715 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006716
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006717 assert(!bs->walking_aio_notifiers);
6718 bs->walking_aio_notifiers = true;
6719 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6720 if (baf->deleted) {
6721 bdrv_do_remove_aio_context_notifier(baf);
6722 } else {
6723 baf->detach_aio_context(baf->opaque);
6724 }
Max Reitz33384422014-06-20 21:57:33 +02006725 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006726 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6727 * remove remaining aio notifiers if we aren't called again.
6728 */
6729 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02006730
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006731 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006732 bs->drv->bdrv_detach_aio_context(bs);
6733 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006734
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006735 if (bs->quiesce_counter) {
6736 aio_enable_external(bs->aio_context);
6737 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006738 bs->aio_context = NULL;
6739}
6740
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006741static void bdrv_attach_aio_context(BlockDriverState *bs,
6742 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006743{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006744 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006745
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006746 if (bs->quiesce_counter) {
6747 aio_disable_external(new_context);
6748 }
6749
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006750 bs->aio_context = new_context;
6751
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006752 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006753 bs->drv->bdrv_attach_aio_context(bs, new_context);
6754 }
Max Reitz33384422014-06-20 21:57:33 +02006755
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006756 assert(!bs->walking_aio_notifiers);
6757 bs->walking_aio_notifiers = true;
6758 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6759 if (ban->deleted) {
6760 bdrv_do_remove_aio_context_notifier(ban);
6761 } else {
6762 ban->attached_aio_context(new_context, ban->opaque);
6763 }
Max Reitz33384422014-06-20 21:57:33 +02006764 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006765 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006766}
6767
Kevin Wolf42a65f02019-05-07 18:31:38 +02006768/*
6769 * Changes the AioContext used for fd handlers, timers, and BHs by this
6770 * BlockDriverState and all its children and parents.
6771 *
Max Reitz43eaaae2019-07-22 15:30:54 +02006772 * Must be called from the main AioContext.
6773 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02006774 * The caller must own the AioContext lock for the old AioContext of bs, but it
6775 * must not own the AioContext lock for new_context (unless new_context is the
6776 * same as the current context of bs).
6777 *
6778 * @ignore will accumulate all visited BdrvChild object. The caller is
6779 * responsible for freeing the list afterwards.
6780 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02006781void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6782 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006783{
Max Reitze037c092019-07-19 11:26:14 +02006784 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006785 GSList *children_to_process = NULL;
6786 GSList *parents_to_process = NULL;
6787 GSList *entry;
6788 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02006789
Max Reitz43eaaae2019-07-22 15:30:54 +02006790 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6791
Max Reitze037c092019-07-19 11:26:14 +02006792 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03006793 return;
6794 }
6795
Kevin Wolfd70d5952019-02-08 16:53:37 +01006796 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02006797
6798 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006799 if (g_slist_find(*ignore, child)) {
6800 continue;
6801 }
6802 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006803 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02006804 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006805
6806 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6807 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006808 continue;
6809 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006810 *ignore = g_slist_prepend(*ignore, parent);
6811 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02006812 }
6813
Sergio Lopez722d8e72021-02-01 13:50:31 +01006814 for (entry = children_to_process;
6815 entry != NULL;
6816 entry = g_slist_next(entry)) {
6817 child = entry->data;
6818 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6819 }
6820 g_slist_free(children_to_process);
6821
6822 for (entry = parents_to_process;
6823 entry != NULL;
6824 entry = g_slist_next(entry)) {
6825 parent = entry->data;
6826 assert(parent->klass->set_aio_ctx);
6827 parent->klass->set_aio_ctx(parent, new_context, ignore);
6828 }
6829 g_slist_free(parents_to_process);
6830
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006831 bdrv_detach_aio_context(bs);
6832
Max Reitze037c092019-07-19 11:26:14 +02006833 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02006834 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006835 aio_context_acquire(new_context);
6836 }
6837
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006838 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02006839
6840 /*
6841 * If this function was recursively called from
6842 * bdrv_set_aio_context_ignore(), there may be nodes in the
6843 * subtree that have not yet been moved to the new AioContext.
6844 * Release the old one so bdrv_drained_end() can poll them.
6845 */
Max Reitz43eaaae2019-07-22 15:30:54 +02006846 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006847 aio_context_release(old_context);
6848 }
6849
Kevin Wolfd70d5952019-02-08 16:53:37 +01006850 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02006851
Max Reitz43eaaae2019-07-22 15:30:54 +02006852 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006853 aio_context_acquire(old_context);
6854 }
Max Reitz43eaaae2019-07-22 15:30:54 +02006855 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006856 aio_context_release(new_context);
6857 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006858}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02006859
Kevin Wolf5d231842019-05-06 19:17:56 +02006860static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6861 GSList **ignore, Error **errp)
6862{
6863 if (g_slist_find(*ignore, c)) {
6864 return true;
6865 }
6866 *ignore = g_slist_prepend(*ignore, c);
6867
Max Reitzbd86fb92020-05-13 13:05:13 +02006868 /*
6869 * A BdrvChildClass that doesn't handle AioContext changes cannot
6870 * tolerate any AioContext changes
6871 */
6872 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006873 char *user = bdrv_child_user_desc(c);
6874 error_setg(errp, "Changing iothreads is not supported by %s", user);
6875 g_free(user);
6876 return false;
6877 }
Max Reitzbd86fb92020-05-13 13:05:13 +02006878 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006879 assert(!errp || *errp);
6880 return false;
6881 }
6882 return true;
6883}
6884
6885bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6886 GSList **ignore, Error **errp)
6887{
6888 if (g_slist_find(*ignore, c)) {
6889 return true;
6890 }
6891 *ignore = g_slist_prepend(*ignore, c);
6892 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6893}
6894
6895/* @ignore will accumulate all visited BdrvChild object. The caller is
6896 * responsible for freeing the list afterwards. */
6897bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6898 GSList **ignore, Error **errp)
6899{
6900 BdrvChild *c;
6901
6902 if (bdrv_get_aio_context(bs) == ctx) {
6903 return true;
6904 }
6905
6906 QLIST_FOREACH(c, &bs->parents, next_parent) {
6907 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6908 return false;
6909 }
6910 }
6911 QLIST_FOREACH(c, &bs->children, next) {
6912 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6913 return false;
6914 }
6915 }
6916
6917 return true;
6918}
6919
6920int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6921 BdrvChild *ignore_child, Error **errp)
6922{
6923 GSList *ignore;
6924 bool ret;
6925
6926 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6927 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6928 g_slist_free(ignore);
6929
6930 if (!ret) {
6931 return -EPERM;
6932 }
6933
Kevin Wolf53a7d042019-05-06 19:17:59 +02006934 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6935 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6936 g_slist_free(ignore);
6937
Kevin Wolf5d231842019-05-06 19:17:56 +02006938 return 0;
6939}
6940
6941int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6942 Error **errp)
6943{
6944 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6945}
6946
Max Reitz33384422014-06-20 21:57:33 +02006947void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6948 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6949 void (*detach_aio_context)(void *opaque), void *opaque)
6950{
6951 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6952 *ban = (BdrvAioNotifier){
6953 .attached_aio_context = attached_aio_context,
6954 .detach_aio_context = detach_aio_context,
6955 .opaque = opaque
6956 };
6957
6958 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6959}
6960
6961void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6962 void (*attached_aio_context)(AioContext *,
6963 void *),
6964 void (*detach_aio_context)(void *),
6965 void *opaque)
6966{
6967 BdrvAioNotifier *ban, *ban_next;
6968
6969 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6970 if (ban->attached_aio_context == attached_aio_context &&
6971 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006972 ban->opaque == opaque &&
6973 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02006974 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006975 if (bs->walking_aio_notifiers) {
6976 ban->deleted = true;
6977 } else {
6978 bdrv_do_remove_aio_context_notifier(ban);
6979 }
Max Reitz33384422014-06-20 21:57:33 +02006980 return;
6981 }
6982 }
6983
6984 abort();
6985}
6986
Max Reitz77485432014-10-27 11:12:50 +01006987int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02006988 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02006989 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02006990 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02006991{
Max Reitzd470ad42017-11-10 21:31:09 +01006992 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02006993 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01006994 return -ENOMEDIUM;
6995 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006996 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02006997 error_setg(errp, "Block driver '%s' does not support option amendment",
6998 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02006999 return -ENOTSUP;
7000 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007001 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7002 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007003}
Benoît Canetf6186f42013-10-02 14:33:48 +02007004
Max Reitz5d69b5a2020-02-18 11:34:41 +01007005/*
7006 * This function checks whether the given @to_replace is allowed to be
7007 * replaced by a node that always shows the same data as @bs. This is
7008 * used for example to verify whether the mirror job can replace
7009 * @to_replace by the target mirrored from @bs.
7010 * To be replaceable, @bs and @to_replace may either be guaranteed to
7011 * always show the same data (because they are only connected through
7012 * filters), or some driver may allow replacing one of its children
7013 * because it can guarantee that this child's data is not visible at
7014 * all (for example, for dissenting quorum children that have no other
7015 * parents).
7016 */
7017bool bdrv_recurse_can_replace(BlockDriverState *bs,
7018 BlockDriverState *to_replace)
7019{
Max Reitz93393e62019-06-12 17:03:38 +02007020 BlockDriverState *filtered;
7021
Max Reitz5d69b5a2020-02-18 11:34:41 +01007022 if (!bs || !bs->drv) {
7023 return false;
7024 }
7025
7026 if (bs == to_replace) {
7027 return true;
7028 }
7029
7030 /* See what the driver can do */
7031 if (bs->drv->bdrv_recurse_can_replace) {
7032 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7033 }
7034
7035 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007036 filtered = bdrv_filter_bs(bs);
7037 if (filtered) {
7038 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007039 }
7040
7041 /* Safe default */
7042 return false;
7043}
7044
Max Reitz810803a2020-02-18 11:34:44 +01007045/*
7046 * Check whether the given @node_name can be replaced by a node that
7047 * has the same data as @parent_bs. If so, return @node_name's BDS;
7048 * NULL otherwise.
7049 *
7050 * @node_name must be a (recursive) *child of @parent_bs (or this
7051 * function will return NULL).
7052 *
7053 * The result (whether the node can be replaced or not) is only valid
7054 * for as long as no graph or permission changes occur.
7055 */
Wen Congyange12f3782015-07-17 10:12:22 +08007056BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7057 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007058{
7059 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007060 AioContext *aio_context;
7061
Benoît Canet09158f02014-06-27 18:25:25 +02007062 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007063 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007064 return NULL;
7065 }
7066
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007067 aio_context = bdrv_get_aio_context(to_replace_bs);
7068 aio_context_acquire(aio_context);
7069
Benoît Canet09158f02014-06-27 18:25:25 +02007070 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007071 to_replace_bs = NULL;
7072 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007073 }
7074
7075 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7076 * most non filter in order to prevent data corruption.
7077 * Another benefit is that this tests exclude backing files which are
7078 * blocked by the backing blockers.
7079 */
Max Reitz810803a2020-02-18 11:34:44 +01007080 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7081 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7082 "because it cannot be guaranteed that doing so would not "
7083 "lead to an abrupt change of visible data",
7084 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007085 to_replace_bs = NULL;
7086 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007087 }
7088
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007089out:
7090 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007091 return to_replace_bs;
7092}
Ming Lei448ad912014-07-04 18:04:33 +08007093
Max Reitz97e2f022019-02-01 20:29:27 +01007094/**
7095 * Iterates through the list of runtime option keys that are said to
7096 * be "strong" for a BDS. An option is called "strong" if it changes
7097 * a BDS's data. For example, the null block driver's "size" and
7098 * "read-zeroes" options are strong, but its "latency-ns" option is
7099 * not.
7100 *
7101 * If a key returned by this function ends with a dot, all options
7102 * starting with that prefix are strong.
7103 */
7104static const char *const *strong_options(BlockDriverState *bs,
7105 const char *const *curopt)
7106{
7107 static const char *const global_options[] = {
7108 "driver", "filename", NULL
7109 };
7110
7111 if (!curopt) {
7112 return &global_options[0];
7113 }
7114
7115 curopt++;
7116 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7117 curopt = bs->drv->strong_runtime_opts;
7118 }
7119
7120 return (curopt && *curopt) ? curopt : NULL;
7121}
7122
7123/**
7124 * Copies all strong runtime options from bs->options to the given
7125 * QDict. The set of strong option keys is determined by invoking
7126 * strong_options().
7127 *
7128 * Returns true iff any strong option was present in bs->options (and
7129 * thus copied to the target QDict) with the exception of "filename"
7130 * and "driver". The caller is expected to use this value to decide
7131 * whether the existence of strong options prevents the generation of
7132 * a plain filename.
7133 */
7134static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7135{
7136 bool found_any = false;
7137 const char *const *option_name = NULL;
7138
7139 if (!bs->drv) {
7140 return false;
7141 }
7142
7143 while ((option_name = strong_options(bs, option_name))) {
7144 bool option_given = false;
7145
7146 assert(strlen(*option_name) > 0);
7147 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7148 QObject *entry = qdict_get(bs->options, *option_name);
7149 if (!entry) {
7150 continue;
7151 }
7152
7153 qdict_put_obj(d, *option_name, qobject_ref(entry));
7154 option_given = true;
7155 } else {
7156 const QDictEntry *entry;
7157 for (entry = qdict_first(bs->options); entry;
7158 entry = qdict_next(bs->options, entry))
7159 {
7160 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7161 qdict_put_obj(d, qdict_entry_key(entry),
7162 qobject_ref(qdict_entry_value(entry)));
7163 option_given = true;
7164 }
7165 }
7166 }
7167
7168 /* While "driver" and "filename" need to be included in a JSON filename,
7169 * their existence does not prohibit generation of a plain filename. */
7170 if (!found_any && option_given &&
7171 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7172 {
7173 found_any = true;
7174 }
7175 }
7176
Max Reitz62a01a272019-02-01 20:29:34 +01007177 if (!qdict_haskey(d, "driver")) {
7178 /* Drivers created with bdrv_new_open_driver() may not have a
7179 * @driver option. Add it here. */
7180 qdict_put_str(d, "driver", bs->drv->format_name);
7181 }
7182
Max Reitz97e2f022019-02-01 20:29:27 +01007183 return found_any;
7184}
7185
Max Reitz90993622019-02-01 20:29:09 +01007186/* Note: This function may return false positives; it may return true
7187 * even if opening the backing file specified by bs's image header
7188 * would result in exactly bs->backing. */
Max Reitz0b877d02018-08-01 20:34:11 +02007189bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007190{
7191 if (bs->backing) {
7192 return strcmp(bs->auto_backing_file,
7193 bs->backing->bs->filename);
7194 } else {
7195 /* No backing BDS, so if the image header reports any backing
7196 * file, it must have been suppressed */
7197 return bs->auto_backing_file[0] != '\0';
7198 }
7199}
7200
Max Reitz91af7012014-07-18 20:24:56 +02007201/* Updates the following BDS fields:
7202 * - exact_filename: A filename which may be used for opening a block device
7203 * which (mostly) equals the given BDS (even without any
7204 * other options; so reading and writing must return the same
7205 * results, but caching etc. may be different)
7206 * - full_open_options: Options which, when given when opening a block device
7207 * (without a filename), result in a BDS (mostly)
7208 * equalling the given one
7209 * - filename: If exact_filename is set, it is copied here. Otherwise,
7210 * full_open_options is converted to a JSON object, prefixed with
7211 * "json:" (for use through the JSON pseudo protocol) and put here.
7212 */
7213void bdrv_refresh_filename(BlockDriverState *bs)
7214{
7215 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007216 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007217 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007218 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007219 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007220 bool generate_json_filename; /* Whether our default implementation should
7221 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007222
7223 if (!drv) {
7224 return;
7225 }
7226
Max Reitze24518e2019-02-01 20:29:06 +01007227 /* This BDS's file name may depend on any of its children's file names, so
7228 * refresh those first */
7229 QLIST_FOREACH(child, &bs->children, next) {
7230 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007231 }
7232
Max Reitzbb808d52019-02-01 20:29:07 +01007233 if (bs->implicit) {
7234 /* For implicit nodes, just copy everything from the single child */
7235 child = QLIST_FIRST(&bs->children);
7236 assert(QLIST_NEXT(child, next) == NULL);
7237
7238 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7239 child->bs->exact_filename);
7240 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7241
Pan Nengyuancb895612020-01-16 16:56:00 +08007242 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007243 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7244
7245 return;
7246 }
7247
Max Reitz90993622019-02-01 20:29:09 +01007248 backing_overridden = bdrv_backing_overridden(bs);
7249
7250 if (bs->open_flags & BDRV_O_NO_IO) {
7251 /* Without I/O, the backing file does not change anything.
7252 * Therefore, in such a case (primarily qemu-img), we can
7253 * pretend the backing file has not been overridden even if
7254 * it technically has been. */
7255 backing_overridden = false;
7256 }
7257
Max Reitz97e2f022019-02-01 20:29:27 +01007258 /* Gather the options QDict */
7259 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007260 generate_json_filename = append_strong_runtime_options(opts, bs);
7261 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007262
7263 if (drv->bdrv_gather_child_options) {
7264 /* Some block drivers may not want to present all of their children's
7265 * options, or name them differently from BdrvChild.name */
7266 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7267 } else {
7268 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007269 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007270 /* We can skip the backing BDS if it has not been overridden */
7271 continue;
7272 }
7273
7274 qdict_put(opts, child->name,
7275 qobject_ref(child->bs->full_open_options));
7276 }
7277
7278 if (backing_overridden && !bs->backing) {
7279 /* Force no backing file */
7280 qdict_put_null(opts, "backing");
7281 }
7282 }
7283
7284 qobject_unref(bs->full_open_options);
7285 bs->full_open_options = opts;
7286
Max Reitz52f72d62019-06-12 17:43:03 +02007287 primary_child_bs = bdrv_primary_bs(bs);
7288
Max Reitz998b3a12019-02-01 20:29:28 +01007289 if (drv->bdrv_refresh_filename) {
7290 /* Obsolete information is of no use here, so drop the old file name
7291 * information before refreshing it */
7292 bs->exact_filename[0] = '\0';
7293
7294 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007295 } else if (primary_child_bs) {
7296 /*
7297 * Try to reconstruct valid information from the underlying
7298 * file -- this only works for format nodes (filter nodes
7299 * cannot be probed and as such must be selected by the user
7300 * either through an options dict, or through a special
7301 * filename which the filter driver must construct in its
7302 * .bdrv_refresh_filename() implementation).
7303 */
Max Reitz998b3a12019-02-01 20:29:28 +01007304
7305 bs->exact_filename[0] = '\0';
7306
Max Reitzfb695c72019-02-01 20:29:29 +01007307 /*
7308 * We can use the underlying file's filename if:
7309 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007310 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007311 * - the file is a protocol BDS, and
7312 * - opening that file (as this BDS's format) will automatically create
7313 * the BDS tree we have right now, that is:
7314 * - the user did not significantly change this BDS's behavior with
7315 * some explicit (strong) options
7316 * - no non-file child of this BDS has been overridden by the user
7317 * Both of these conditions are represented by generate_json_filename.
7318 */
Max Reitz52f72d62019-06-12 17:43:03 +02007319 if (primary_child_bs->exact_filename[0] &&
7320 primary_child_bs->drv->bdrv_file_open &&
7321 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007322 {
Max Reitz52f72d62019-06-12 17:43:03 +02007323 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007324 }
7325 }
7326
Max Reitz91af7012014-07-18 20:24:56 +02007327 if (bs->exact_filename[0]) {
7328 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007329 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007330 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007331 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007332 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007333 /* Give user a hint if we truncated things. */
7334 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7335 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007336 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007337 }
7338}
Wen Congyange06018a2016-05-10 15:36:37 +08007339
Max Reitz1e89d0f2019-02-01 20:29:18 +01007340char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7341{
7342 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007343 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007344
7345 if (!drv) {
7346 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7347 return NULL;
7348 }
7349
7350 if (drv->bdrv_dirname) {
7351 return drv->bdrv_dirname(bs, errp);
7352 }
7353
Max Reitz52f72d62019-06-12 17:43:03 +02007354 child_bs = bdrv_primary_bs(bs);
7355 if (child_bs) {
7356 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007357 }
7358
7359 bdrv_refresh_filename(bs);
7360 if (bs->exact_filename[0] != '\0') {
7361 return path_combine(bs->exact_filename, "");
7362 }
7363
7364 error_setg(errp, "Cannot generate a base directory for %s nodes",
7365 drv->format_name);
7366 return NULL;
7367}
7368
Wen Congyange06018a2016-05-10 15:36:37 +08007369/*
7370 * Hot add/remove a BDS's child. So the user can take a child offline when
7371 * it is broken and take a new child online
7372 */
7373void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7374 Error **errp)
7375{
7376
7377 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7378 error_setg(errp, "The node %s does not support adding a child",
7379 bdrv_get_device_or_node_name(parent_bs));
7380 return;
7381 }
7382
7383 if (!QLIST_EMPTY(&child_bs->parents)) {
7384 error_setg(errp, "The node %s already has a parent",
7385 child_bs->node_name);
7386 return;
7387 }
7388
7389 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7390}
7391
7392void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7393{
7394 BdrvChild *tmp;
7395
7396 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7397 error_setg(errp, "The node %s does not support removing a child",
7398 bdrv_get_device_or_node_name(parent_bs));
7399 return;
7400 }
7401
7402 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7403 if (tmp == child) {
7404 break;
7405 }
7406 }
7407
7408 if (!tmp) {
7409 error_setg(errp, "The node %s does not have a child named %s",
7410 bdrv_get_device_or_node_name(parent_bs),
7411 bdrv_get_device_or_node_name(child->bs));
7412 return;
7413 }
7414
7415 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7416}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007417
7418int bdrv_make_empty(BdrvChild *c, Error **errp)
7419{
7420 BlockDriver *drv = c->bs->drv;
7421 int ret;
7422
7423 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7424
7425 if (!drv->bdrv_make_empty) {
7426 error_setg(errp, "%s does not support emptying nodes",
7427 drv->format_name);
7428 return -ENOTSUP;
7429 }
7430
7431 ret = drv->bdrv_make_empty(c->bs);
7432 if (ret < 0) {
7433 error_setg_errno(errp, -ret, "Failed to empty %s",
7434 c->bs->filename);
7435 return ret;
7436 }
7437
7438 return 0;
7439}
Max Reitz9a6fc882019-05-31 15:23:11 +02007440
7441/*
7442 * Return the child that @bs acts as an overlay for, and from which data may be
7443 * copied in COW or COR operations. Usually this is the backing file.
7444 */
7445BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7446{
7447 if (!bs || !bs->drv) {
7448 return NULL;
7449 }
7450
7451 if (bs->drv->is_filter) {
7452 return NULL;
7453 }
7454
7455 if (!bs->backing) {
7456 return NULL;
7457 }
7458
7459 assert(bs->backing->role & BDRV_CHILD_COW);
7460 return bs->backing;
7461}
7462
7463/*
7464 * If @bs acts as a filter for exactly one of its children, return
7465 * that child.
7466 */
7467BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7468{
7469 BdrvChild *c;
7470
7471 if (!bs || !bs->drv) {
7472 return NULL;
7473 }
7474
7475 if (!bs->drv->is_filter) {
7476 return NULL;
7477 }
7478
7479 /* Only one of @backing or @file may be used */
7480 assert(!(bs->backing && bs->file));
7481
7482 c = bs->backing ?: bs->file;
7483 if (!c) {
7484 return NULL;
7485 }
7486
7487 assert(c->role & BDRV_CHILD_FILTERED);
7488 return c;
7489}
7490
7491/*
7492 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7493 * whichever is non-NULL.
7494 *
7495 * Return NULL if both are NULL.
7496 */
7497BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7498{
7499 BdrvChild *cow_child = bdrv_cow_child(bs);
7500 BdrvChild *filter_child = bdrv_filter_child(bs);
7501
7502 /* Filter nodes cannot have COW backing files */
7503 assert(!(cow_child && filter_child));
7504
7505 return cow_child ?: filter_child;
7506}
7507
7508/*
7509 * Return the primary child of this node: For filters, that is the
7510 * filtered child. For other nodes, that is usually the child storing
7511 * metadata.
7512 * (A generally more helpful description is that this is (usually) the
7513 * child that has the same filename as @bs.)
7514 *
7515 * Drivers do not necessarily have a primary child; for example quorum
7516 * does not.
7517 */
7518BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7519{
7520 BdrvChild *c, *found = NULL;
7521
7522 QLIST_FOREACH(c, &bs->children, next) {
7523 if (c->role & BDRV_CHILD_PRIMARY) {
7524 assert(!found);
7525 found = c;
7526 }
7527 }
7528
7529 return found;
7530}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007531
7532static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7533 bool stop_on_explicit_filter)
7534{
7535 BdrvChild *c;
7536
7537 if (!bs) {
7538 return NULL;
7539 }
7540
7541 while (!(stop_on_explicit_filter && !bs->implicit)) {
7542 c = bdrv_filter_child(bs);
7543 if (!c) {
7544 /*
7545 * A filter that is embedded in a working block graph must
7546 * have a child. Assert this here so this function does
7547 * not return a filter node that is not expected by the
7548 * caller.
7549 */
7550 assert(!bs->drv || !bs->drv->is_filter);
7551 break;
7552 }
7553 bs = c->bs;
7554 }
7555 /*
7556 * Note that this treats nodes with bs->drv == NULL as not being
7557 * filters (bs->drv == NULL should be replaced by something else
7558 * anyway).
7559 * The advantage of this behavior is that this function will thus
7560 * always return a non-NULL value (given a non-NULL @bs).
7561 */
7562
7563 return bs;
7564}
7565
7566/*
7567 * Return the first BDS that has not been added implicitly or that
7568 * does not have a filtered child down the chain starting from @bs
7569 * (including @bs itself).
7570 */
7571BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7572{
7573 return bdrv_do_skip_filters(bs, true);
7574}
7575
7576/*
7577 * Return the first BDS that does not have a filtered child down the
7578 * chain starting from @bs (including @bs itself).
7579 */
7580BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7581{
7582 return bdrv_do_skip_filters(bs, false);
7583}
7584
7585/*
7586 * For a backing chain, return the first non-filter backing image of
7587 * the first non-filter image.
7588 */
7589BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7590{
7591 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7592}