blob: e97ce0b1c83eb68db8abccfe90867afb2e8542cb [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,
Alberto Garciaecd30d22021-06-10 15:05:36 +030095 Transaction *change_child_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
Alberto Garciaab5b52282021-07-08 13:47:05 +02004098void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4099{
4100 if (bs_queue) {
4101 BlockReopenQueueEntry *bs_entry, *next;
4102 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4103 qobject_unref(bs_entry->state.explicit_options);
4104 qobject_unref(bs_entry->state.options);
4105 g_free(bs_entry);
4106 }
4107 g_free(bs_queue);
4108 }
4109}
4110
Jeff Codye971aa12012-09-20 15:13:19 -04004111/*
4112 * Reopen multiple BlockDriverStates atomically & transactionally.
4113 *
4114 * The queue passed in (bs_queue) must have been built up previous
4115 * via bdrv_reopen_queue().
4116 *
4117 * Reopens all BDS specified in the queue, with the appropriate
4118 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004119 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004120 * data cleaned up.
4121 *
4122 * If all devices prepare successfully, then the changes are committed
4123 * to all devices.
4124 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004125 * All affected nodes must be drained between bdrv_reopen_queue() and
4126 * bdrv_reopen_multiple().
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004127 *
4128 * To be called from the main thread, with all other AioContexts unlocked.
Jeff Codye971aa12012-09-20 15:13:19 -04004129 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004130int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004131{
4132 int ret = -1;
4133 BlockReopenQueueEntry *bs_entry, *next;
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004134 AioContext *ctx;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004135 Transaction *tran = tran_new();
4136 g_autoptr(GHashTable) found = NULL;
4137 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004138
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004139 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Jeff Codye971aa12012-09-20 15:13:19 -04004140 assert(bs_queue != NULL);
4141
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004142 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004143 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4144 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004145 ret = bdrv_flush(bs_entry->state.bs);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004146 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004147 if (ret < 0) {
4148 error_setg_errno(errp, -ret, "Error flushing drive");
Kevin Wolfe3fc91a2021-05-03 13:05:55 +02004149 goto abort;
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004150 }
4151 }
4152
4153 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004154 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004155 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4156 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004157 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004158 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004159 if (ret < 0) {
4160 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004161 }
4162 bs_entry->prepared = true;
4163 }
4164
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004165 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004166 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004167 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004168
4169 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4170 if (state->old_backing_bs) {
4171 refresh_list = bdrv_topological_dfs(refresh_list, found,
4172 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004173 }
Alberto Garciaecd30d22021-06-10 15:05:36 +03004174 if (state->old_file_bs) {
4175 refresh_list = bdrv_topological_dfs(refresh_list, found,
4176 state->old_file_bs);
4177 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004178 }
4179
4180 /*
4181 * Note that file-posix driver rely on permission update done during reopen
4182 * (even if no permission changed), because it wants "new" permissions for
4183 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4184 * in raw_reopen_prepare() which is called with "old" permissions.
4185 */
4186 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4187 if (ret < 0) {
4188 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004189 }
4190
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004191 /*
4192 * If we reach this point, we have success and just need to apply the
4193 * changes.
4194 *
4195 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4196 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4197 * children are usually goes after parents in reopen-queue, so go from last
4198 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004199 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004200 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004201 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4202 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004203 bdrv_reopen_commit(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004204 aio_context_release(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04004205 }
4206
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004207 tran_commit(tran);
4208
4209 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4210 BlockDriverState *bs = bs_entry->state.bs;
4211
4212 if (bs->drv->bdrv_reopen_commit_post) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004213 ctx = bdrv_get_aio_context(bs);
4214 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004215 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004216 aio_context_release(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004217 }
4218 }
4219
Jeff Codye971aa12012-09-20 15:13:19 -04004220 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004221 goto cleanup;
4222
4223abort:
4224 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004225 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004226 if (bs_entry->prepared) {
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004227 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4228 aio_context_acquire(ctx);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004229 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004230 aio_context_release(ctx);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004231 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004232 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004233
Jeff Codye971aa12012-09-20 15:13:19 -04004234cleanup:
Alberto Garciaab5b52282021-07-08 13:47:05 +02004235 bdrv_reopen_queue_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004236
Jeff Codye971aa12012-09-20 15:13:19 -04004237 return ret;
4238}
4239
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004240int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4241 Error **errp)
4242{
4243 AioContext *ctx = bdrv_get_aio_context(bs);
4244 BlockReopenQueue *queue;
4245 int ret;
4246
4247 bdrv_subtree_drained_begin(bs);
4248 if (ctx != qemu_get_aio_context()) {
4249 aio_context_release(ctx);
4250 }
4251
4252 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4253 ret = bdrv_reopen_multiple(queue, errp);
4254
4255 if (ctx != qemu_get_aio_context()) {
4256 aio_context_acquire(ctx);
4257 }
4258 bdrv_subtree_drained_end(bs);
4259
4260 return ret;
4261}
4262
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004263int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4264 Error **errp)
4265{
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004266 QDict *opts = qdict_new();
4267
4268 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4269
Kevin Wolf6cf42ca2021-07-08 13:47:06 +02004270 return bdrv_reopen(bs, opts, true, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004271}
4272
Jeff Codye971aa12012-09-20 15:13:19 -04004273/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004274 * Take a BDRVReopenState and check if the value of 'backing' in the
4275 * reopen_state->options QDict is valid or not.
4276 *
4277 * If 'backing' is missing from the QDict then return 0.
4278 *
4279 * If 'backing' contains the node name of the backing file of
4280 * reopen_state->bs then return 0.
4281 *
4282 * If 'backing' contains a different node name (or is null) then check
4283 * whether the current backing file can be replaced with the new one.
4284 * If that's the case then reopen_state->replace_backing_bs is set to
4285 * true and reopen_state->new_backing_bs contains a pointer to the new
4286 * backing BlockDriverState (or NULL).
4287 *
4288 * Return 0 on success, otherwise return < 0 and set @errp.
4289 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004290static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4291 bool is_backing, Transaction *tran,
4292 Error **errp)
Alberto Garciacb828c32019-03-12 18:48:47 +02004293{
4294 BlockDriverState *bs = reopen_state->bs;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004295 BlockDriverState *new_child_bs;
4296 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4297 child_bs(bs->file);
4298 const char *child_name = is_backing ? "backing" : "file";
Alberto Garciacb828c32019-03-12 18:48:47 +02004299 QObject *value;
4300 const char *str;
4301
Alberto Garciaecd30d22021-06-10 15:05:36 +03004302 value = qdict_get(reopen_state->options, child_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004303 if (value == NULL) {
4304 return 0;
4305 }
4306
4307 switch (qobject_type(value)) {
4308 case QTYPE_QNULL:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004309 assert(is_backing); /* The 'file' option does not allow a null value */
4310 new_child_bs = NULL;
Alberto Garciacb828c32019-03-12 18:48:47 +02004311 break;
4312 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004313 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciaecd30d22021-06-10 15:05:36 +03004314 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4315 if (new_child_bs == NULL) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004316 return -EINVAL;
Alberto Garciaecd30d22021-06-10 15:05:36 +03004317 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4318 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4319 "cycle", str, child_name, bs->node_name);
Alberto Garciacb828c32019-03-12 18:48:47 +02004320 return -EINVAL;
4321 }
4322 break;
4323 default:
Alberto Garciaecd30d22021-06-10 15:05:36 +03004324 /*
4325 * The options QDict has been flattened, so 'backing' and 'file'
4326 * do not allow any other data type here.
4327 */
Alberto Garciacb828c32019-03-12 18:48:47 +02004328 g_assert_not_reached();
4329 }
4330
Alberto Garciaecd30d22021-06-10 15:05:36 +03004331 if (old_child_bs == new_child_bs) {
4332 return 0;
4333 }
4334
4335 if (old_child_bs) {
4336 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004337 return 0;
4338 }
4339
Alberto Garciaecd30d22021-06-10 15:05:36 +03004340 if (old_child_bs->implicit) {
4341 error_setg(errp, "Cannot replace implicit %s child of %s",
4342 child_name, bs->node_name);
Vladimir Sementsov-Ogievskiycbfdb982021-06-10 15:05:33 +03004343 return -EPERM;
4344 }
4345 }
4346
Alberto Garciaecd30d22021-06-10 15:05:36 +03004347 if (bs->drv->is_filter && !old_child_bs) {
Vladimir Sementsov-Ogievskiy25f78d92021-06-10 15:05:34 +03004348 /*
4349 * Filters always have a file or a backing child, so we are trying to
4350 * change wrong child
4351 */
4352 error_setg(errp, "'%s' is a %s filter node that does not support a "
Alberto Garciaecd30d22021-06-10 15:05:36 +03004353 "%s child", bs->node_name, bs->drv->format_name, child_name);
Max Reitz1d42f482019-06-12 17:24:39 +02004354 return -EINVAL;
4355 }
4356
Alberto Garciaecd30d22021-06-10 15:05:36 +03004357 if (is_backing) {
4358 reopen_state->old_backing_bs = old_child_bs;
4359 } else {
4360 reopen_state->old_file_bs = old_child_bs;
4361 }
4362
4363 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4364 tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004365}
4366
4367/*
Jeff Codye971aa12012-09-20 15:13:19 -04004368 * Prepares a BlockDriverState for reopen. All changes are staged in the
4369 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4370 * the block driver layer .bdrv_reopen_prepare()
4371 *
4372 * bs is the BlockDriverState to reopen
4373 * flags are the new open flags
4374 * queue is the reopen queue
4375 *
4376 * Returns 0 on success, non-zero on error. On error errp will be set
4377 * as well.
4378 *
4379 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4380 * It is the responsibility of the caller to then call the abort() or
4381 * commit() for any other BDS that have been left in a prepare() state
4382 *
4383 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004384static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004385 BlockReopenQueue *queue,
Alberto Garciaecd30d22021-06-10 15:05:36 +03004386 Transaction *change_child_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004387{
4388 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004389 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004390 Error *local_err = NULL;
4391 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004392 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004393 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004394 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004395 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004396 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004397
4398 assert(reopen_state != NULL);
4399 assert(reopen_state->bs->drv != NULL);
4400 drv = reopen_state->bs->drv;
4401
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004402 /* This function and each driver's bdrv_reopen_prepare() remove
4403 * entries from reopen_state->options as they are processed, so
4404 * we need to make a copy of the original QDict. */
4405 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4406
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004407 /* Process generic block layer options */
4408 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004409 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004410 ret = -EINVAL;
4411 goto error;
4412 }
4413
Alberto Garciae6d79c42018-11-12 16:00:47 +02004414 /* This was already called in bdrv_reopen_queue_child() so the flags
4415 * are up-to-date. This time we simply want to remove the options from
4416 * QemuOpts in order to indicate that they have been processed. */
4417 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004418 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004419 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004420
Alberto Garcia415bbca2018-10-03 13:23:13 +03004421 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004422 if (discard != NULL) {
4423 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4424 error_setg(errp, "Invalid discard option");
4425 ret = -EINVAL;
4426 goto error;
4427 }
4428 }
4429
Alberto Garcia543770b2018-09-06 12:37:09 +03004430 reopen_state->detect_zeroes =
4431 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4432 if (local_err) {
4433 error_propagate(errp, local_err);
4434 ret = -EINVAL;
4435 goto error;
4436 }
4437
Alberto Garcia57f9db92018-09-06 12:37:06 +03004438 /* All other options (including node-name and driver) must be unchanged.
4439 * Put them back into the QDict, so that they are checked at the end
4440 * of this function. */
4441 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004442
Jeff Cody3d8ce172017-04-07 16:55:30 -04004443 /* If we are to stay read-only, do not allow permission change
4444 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4445 * not set, or if the BDS still has copy_on_read enabled */
4446 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004447 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004448 if (local_err) {
4449 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004450 goto error;
4451 }
4452
Jeff Codye971aa12012-09-20 15:13:19 -04004453 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004454 /*
4455 * If a driver-specific option is missing, it means that we
4456 * should reset it to its default value.
4457 * But not all options allow that, so we need to check it first.
4458 */
4459 ret = bdrv_reset_options_allowed(reopen_state->bs,
4460 reopen_state->options, errp);
4461 if (ret) {
4462 goto error;
4463 }
4464
Jeff Codye971aa12012-09-20 15:13:19 -04004465 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4466 if (ret) {
4467 if (local_err != NULL) {
4468 error_propagate(errp, local_err);
4469 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004470 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004471 error_setg(errp, "failed while preparing to reopen image '%s'",
4472 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004473 }
4474 goto error;
4475 }
4476 } else {
4477 /* It is currently mandatory to have a bdrv_reopen_prepare()
4478 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004479 error_setg(errp, "Block format '%s' used by node '%s' "
4480 "does not support reopening files", drv->format_name,
4481 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004482 ret = -1;
4483 goto error;
4484 }
4485
Max Reitz9ad08c42018-11-16 17:45:24 +01004486 drv_prepared = true;
4487
Alberto Garciabacd9b82019-03-12 18:48:46 +02004488 /*
4489 * We must provide the 'backing' option if the BDS has a backing
4490 * file or if the image file has a backing file name as part of
4491 * its metadata. Otherwise the 'backing' option can be omitted.
4492 */
4493 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004494 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004495 error_setg(errp, "backing is missing for '%s'",
4496 reopen_state->bs->node_name);
4497 ret = -EINVAL;
4498 goto error;
4499 }
4500
Alberto Garciacb828c32019-03-12 18:48:47 +02004501 /*
4502 * Allow changing the 'backing' option. The new value can be
4503 * either a reference to an existing node (using its node name)
4504 * or NULL to simply detach the current backing file.
4505 */
Alberto Garciaecd30d22021-06-10 15:05:36 +03004506 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4507 change_child_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004508 if (ret < 0) {
4509 goto error;
4510 }
4511 qdict_del(reopen_state->options, "backing");
4512
Alberto Garciaecd30d22021-06-10 15:05:36 +03004513 /* Allow changing the 'file' option. In this case NULL is not allowed */
4514 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4515 change_child_tran, errp);
4516 if (ret < 0) {
4517 goto error;
4518 }
4519 qdict_del(reopen_state->options, "file");
4520
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004521 /* Options that are not handled are only okay if they are unchanged
4522 * compared to the old state. It is expected that some options are only
4523 * used for the initial open, but not reopen (e.g. filename) */
4524 if (qdict_size(reopen_state->options)) {
4525 const QDictEntry *entry = qdict_first(reopen_state->options);
4526
4527 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004528 QObject *new = entry->value;
4529 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004530
Alberto Garciadb905282018-09-06 12:37:05 +03004531 /* Allow child references (child_name=node_name) as long as they
4532 * point to the current child (i.e. everything stays the same). */
4533 if (qobject_type(new) == QTYPE_QSTRING) {
4534 BdrvChild *child;
4535 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4536 if (!strcmp(child->name, entry->key)) {
4537 break;
4538 }
4539 }
4540
4541 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004542 if (!strcmp(child->bs->node_name,
4543 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004544 continue; /* Found child with this name, skip option */
4545 }
4546 }
4547 }
4548
Max Reitz54fd1b02017-11-14 19:01:26 +01004549 /*
4550 * TODO: When using -drive to specify blockdev options, all values
4551 * will be strings; however, when using -blockdev, blockdev-add or
4552 * filenames using the json:{} pseudo-protocol, they will be
4553 * correctly typed.
4554 * In contrast, reopening options are (currently) always strings
4555 * (because you can only specify them through qemu-io; all other
4556 * callers do not specify any options).
4557 * Therefore, when using anything other than -drive to create a BDS,
4558 * this cannot detect non-string options as unchanged, because
4559 * qobject_is_equal() always returns false for objects of different
4560 * type. In the future, this should be remedied by correctly typing
4561 * all options. For now, this is not too big of an issue because
4562 * the user can simply omit options which cannot be changed anyway,
4563 * so they will stay unchanged.
4564 */
4565 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004566 error_setg(errp, "Cannot change the option '%s'", entry->key);
4567 ret = -EINVAL;
4568 goto error;
4569 }
4570 } while ((entry = qdict_next(reopen_state->options, entry)));
4571 }
4572
Jeff Codye971aa12012-09-20 15:13:19 -04004573 ret = 0;
4574
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004575 /* Restore the original reopen_state->options QDict */
4576 qobject_unref(reopen_state->options);
4577 reopen_state->options = qobject_ref(orig_reopen_opts);
4578
Jeff Codye971aa12012-09-20 15:13:19 -04004579error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004580 if (ret < 0 && drv_prepared) {
4581 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4582 * call drv->bdrv_reopen_abort() before signaling an error
4583 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4584 * when the respective bdrv_reopen_prepare() has failed) */
4585 if (drv->bdrv_reopen_abort) {
4586 drv->bdrv_reopen_abort(reopen_state);
4587 }
4588 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004589 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004590 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004591 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004592 return ret;
4593}
4594
4595/*
4596 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4597 * makes them final by swapping the staging BlockDriverState contents into
4598 * the active BlockDriverState contents.
4599 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004600static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004601{
4602 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004603 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004604 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004605
4606 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004607 bs = reopen_state->bs;
4608 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004609 assert(drv != NULL);
4610
4611 /* If there are any driver level actions to take */
4612 if (drv->bdrv_reopen_commit) {
4613 drv->bdrv_reopen_commit(reopen_state);
4614 }
4615
4616 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004617 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004618 qobject_unref(bs->options);
Alberto Garciaab5b52282021-07-08 13:47:05 +02004619 qobject_ref(reopen_state->explicit_options);
4620 qobject_ref(reopen_state->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004621
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004622 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004623 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004624 bs->open_flags = reopen_state->flags;
Alberto Garcia543770b2018-09-06 12:37:09 +03004625 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004626
Alberto Garcia50196d72018-09-06 12:37:03 +03004627 /* Remove child references from bs->options and bs->explicit_options.
4628 * Child options were already removed in bdrv_reopen_queue_child() */
4629 QLIST_FOREACH(child, &bs->children, next) {
4630 qdict_del(bs->explicit_options, child->name);
4631 qdict_del(bs->options, child->name);
4632 }
Vladimir Sementsov-Ogievskiy3d0e8742021-06-10 15:05:35 +03004633 /* backing is probably removed, so it's not handled by previous loop */
4634 qdict_del(bs->explicit_options, "backing");
4635 qdict_del(bs->options, "backing");
4636
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004637 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004638}
4639
4640/*
4641 * Abort the reopen, and delete and free the staged changes in
4642 * reopen_state
4643 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004644static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004645{
4646 BlockDriver *drv;
4647
4648 assert(reopen_state != NULL);
4649 drv = reopen_state->bs->drv;
4650 assert(drv != NULL);
4651
4652 if (drv->bdrv_reopen_abort) {
4653 drv->bdrv_reopen_abort(reopen_state);
4654 }
4655}
4656
4657
Max Reitz64dff522016-01-29 16:36:10 +01004658static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004659{
Max Reitz33384422014-06-20 21:57:33 +02004660 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004661 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004662
Max Reitz30f55fb2016-05-17 16:41:32 +02004663 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004664
Paolo Bonzinifc272912015-12-23 11:48:24 +01004665 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004666 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004667 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004668
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004669 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004670 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004671 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004672 bs->drv->bdrv_close(bs);
4673 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004674 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004675 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004676
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004677 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004678 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004679 }
4680
Alberto Garciadd4118c2019-05-13 16:46:17 +03004681 bs->backing = NULL;
4682 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004683 g_free(bs->opaque);
4684 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004685 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004686 bs->backing_file[0] = '\0';
4687 bs->backing_format[0] = '\0';
4688 bs->total_sectors = 0;
4689 bs->encrypted = false;
4690 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004691 qobject_unref(bs->options);
4692 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004693 bs->options = NULL;
4694 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004695 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004696 bs->full_open_options = NULL;
4697
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004698 bdrv_release_named_dirty_bitmaps(bs);
4699 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4700
Max Reitz33384422014-06-20 21:57:33 +02004701 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4702 g_free(ban);
4703 }
4704 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004705 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004706
4707 /*
4708 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4709 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4710 * gets called.
4711 */
4712 if (bs->quiesce_counter) {
4713 bdrv_drain_all_end_quiesce(bs);
4714 }
bellardb3380822004-03-14 21:38:54 +00004715}
4716
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004717void bdrv_close_all(void)
4718{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004719 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004720
Max Reitzca9bd242016-01-29 16:36:14 +01004721 /* Drop references from requests still in flight, such as canceled block
4722 * jobs whose AIO context has not been polled yet */
4723 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004724
Max Reitzca9bd242016-01-29 16:36:14 +01004725 blk_remove_all_bs();
4726 blockdev_close_all_bdrv_states();
4727
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004728 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004729}
4730
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004731static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004732{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004733 GQueue *queue;
4734 GHashTable *found;
4735 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004736
Max Reitzbd86fb92020-05-13 13:05:13 +02004737 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004738 return false;
4739 }
4740
Max Reitzec9f10f2018-06-13 20:18:15 +02004741 /* If the child @c belongs to the BDS @to, replacing the current
4742 * c->bs by @to would mean to create a loop.
4743 *
4744 * Such a case occurs when appending a BDS to a backing chain.
4745 * For instance, imagine the following chain:
4746 *
4747 * guest device -> node A -> further backing chain...
4748 *
4749 * Now we create a new BDS B which we want to put on top of this
4750 * chain, so we first attach A as its backing node:
4751 *
4752 * node B
4753 * |
4754 * v
4755 * guest device -> node A -> further backing chain...
4756 *
4757 * Finally we want to replace A by B. When doing that, we want to
4758 * replace all pointers to A by pointers to B -- except for the
4759 * pointer from B because (1) that would create a loop, and (2)
4760 * that pointer should simply stay intact:
4761 *
4762 * guest device -> node B
4763 * |
4764 * v
4765 * node A -> further backing chain...
4766 *
4767 * In general, when replacing a node A (c->bs) by a node B (@to),
4768 * if A is a child of B, that means we cannot replace A by B there
4769 * because that would create a loop. Silently detaching A from B
4770 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004771 * place there is the most sensible choice.
4772 *
4773 * We would also create a loop in any cases where @c is only
4774 * indirectly referenced by @to. Prevent this by returning false
4775 * if @c is found (by breadth-first search) anywhere in the whole
4776 * subtree of @to.
4777 */
4778
4779 ret = true;
4780 found = g_hash_table_new(NULL, NULL);
4781 g_hash_table_add(found, to);
4782 queue = g_queue_new();
4783 g_queue_push_tail(queue, to);
4784
4785 while (!g_queue_is_empty(queue)) {
4786 BlockDriverState *v = g_queue_pop_head(queue);
4787 BdrvChild *c2;
4788
4789 QLIST_FOREACH(c2, &v->children, next) {
4790 if (c2 == c) {
4791 ret = false;
4792 break;
4793 }
4794
4795 if (g_hash_table_contains(found, c2->bs)) {
4796 continue;
4797 }
4798
4799 g_queue_push_tail(queue, c2->bs);
4800 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004801 }
4802 }
4803
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004804 g_queue_free(queue);
4805 g_hash_table_destroy(found);
4806
4807 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004808}
4809
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004810typedef struct BdrvRemoveFilterOrCowChild {
4811 BdrvChild *child;
4812 bool is_backing;
4813} BdrvRemoveFilterOrCowChild;
4814
4815static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
4816{
4817 BdrvRemoveFilterOrCowChild *s = opaque;
4818 BlockDriverState *parent_bs = s->child->opaque;
4819
4820 QLIST_INSERT_HEAD(&parent_bs->children, s->child, next);
4821 if (s->is_backing) {
4822 parent_bs->backing = s->child;
4823 } else {
4824 parent_bs->file = s->child;
4825 }
4826
4827 /*
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004828 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004829 * because that function is transactionable and it registered own completion
4830 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
4831 * called automatically.
4832 */
4833}
4834
4835static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
4836{
4837 BdrvRemoveFilterOrCowChild *s = opaque;
4838
4839 bdrv_child_free(s->child);
4840}
4841
4842static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
4843 .abort = bdrv_remove_filter_or_cow_child_abort,
4844 .commit = bdrv_remove_filter_or_cow_child_commit,
4845 .clean = g_free,
4846};
4847
4848/*
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004849 * A function to remove backing or file child of @bs.
Vladimir Sementsov-Ogievskiy7ec390d2021-06-10 14:25:45 +03004850 * Function doesn't update permissions, caller is responsible for this.
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004851 */
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004852static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
4853 BdrvChild *child,
4854 Transaction *tran)
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004855{
4856 BdrvRemoveFilterOrCowChild *s;
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004857
4858 assert(child == bs->backing || child == bs->file);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004859
4860 if (!child) {
4861 return;
4862 }
4863
4864 if (child->bs) {
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004865 bdrv_replace_child_tran(child, NULL, tran);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004866 }
4867
4868 s = g_new(BdrvRemoveFilterOrCowChild, 1);
4869 *s = (BdrvRemoveFilterOrCowChild) {
4870 .child = child,
4871 .is_backing = (child == bs->backing),
4872 };
4873 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
4874
4875 QLIST_SAFE_REMOVE(child, next);
4876 if (s->is_backing) {
4877 bs->backing = NULL;
4878 } else {
4879 bs->file = NULL;
4880 }
4881}
4882
Vladimir Sementsov-Ogievskiy5b995012021-06-10 15:05:29 +03004883/*
4884 * A function to remove backing-chain child of @bs if exists: cow child for
4885 * format nodes (always .backing) and filter child for filters (may be .file or
4886 * .backing)
4887 */
4888static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
4889 Transaction *tran)
4890{
4891 bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
4892}
4893
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004894static int bdrv_replace_node_noperm(BlockDriverState *from,
4895 BlockDriverState *to,
4896 bool auto_skip, Transaction *tran,
4897 Error **errp)
4898{
4899 BdrvChild *c, *next;
4900
4901 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4902 assert(c->bs == from);
4903 if (!should_update_child(c, to)) {
4904 if (auto_skip) {
4905 continue;
4906 }
4907 error_setg(errp, "Should not change '%s' link to '%s'",
4908 c->name, from->node_name);
4909 return -EINVAL;
4910 }
4911 if (c->frozen) {
4912 error_setg(errp, "Cannot change '%s' link to '%s'",
4913 c->name, from->node_name);
4914 return -EPERM;
4915 }
Vladimir Sementsov-Ogievskiy4bf021d2021-06-10 14:25:44 +03004916 bdrv_replace_child_tran(c, to, tran);
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004917 }
4918
4919 return 0;
4920}
4921
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004922/*
4923 * With auto_skip=true bdrv_replace_node_common skips updating from parents
4924 * if it creates a parent-child relation loop or if parent is block-job.
4925 *
4926 * With auto_skip=false the error is returned if from has a parent which should
4927 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004928 *
4929 * With @detach_subchain=true @to must be in a backing chain of @from. In this
4930 * case backing link of the cow-parent of @to is removed.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004931 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004932static int bdrv_replace_node_common(BlockDriverState *from,
4933 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004934 bool auto_skip, bool detach_subchain,
4935 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004936{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004937 Transaction *tran = tran_new();
4938 g_autoptr(GHashTable) found = NULL;
4939 g_autoptr(GSList) refresh_list = NULL;
Miroslav Rezanina2d369d62021-05-05 03:59:03 -04004940 BlockDriverState *to_cow_parent = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004941 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004942
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004943 if (detach_subchain) {
4944 assert(bdrv_chain_contains(from, to));
4945 assert(from != to);
4946 for (to_cow_parent = from;
4947 bdrv_filter_or_cow_bs(to_cow_parent) != to;
4948 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
4949 {
4950 ;
4951 }
4952 }
4953
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004954 /* Make sure that @from doesn't go away until we have successfully attached
4955 * all of its parents to @to. */
4956 bdrv_ref(from);
4957
Kevin Wolff871abd2019-05-21 19:00:25 +02004958 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01004959 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02004960 bdrv_drained_begin(from);
4961
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004962 /*
4963 * Do the replacement without permission update.
4964 * Replacement may influence the permissions, we should calculate new
4965 * permissions based on new graph. If we fail, we'll roll-back the
4966 * replacement.
4967 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004968 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
4969 if (ret < 0) {
4970 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004971 }
4972
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004973 if (detach_subchain) {
4974 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
4975 }
4976
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004977 found = g_hash_table_new(NULL, NULL);
4978
4979 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
4980 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
4981
4982 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004983 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004984 goto out;
4985 }
4986
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004987 ret = 0;
4988
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004989out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004990 tran_finalize(tran, ret);
4991
Kevin Wolff871abd2019-05-21 19:00:25 +02004992 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004993 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004994
4995 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004996}
4997
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004998int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4999 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005000{
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005001 return bdrv_replace_node_common(from, to, true, false, errp);
5002}
5003
5004int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5005{
5006 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5007 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005008}
5009
Jeff Cody8802d1f2012-02-28 15:54:06 -05005010/*
5011 * Add new bs contents at the top of an image chain while the chain is
5012 * live, while keeping required fields on the top layer.
5013 *
5014 * This will modify the BlockDriverState fields, and swap contents
5015 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5016 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005017 * bs_new must not be attached to a BlockBackend and must not have backing
5018 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005019 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005020 * This function does not create any image files.
5021 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005022int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5023 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005024{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005025 int ret;
5026 Transaction *tran = tran_new();
5027
5028 assert(!bs_new->backing);
5029
5030 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5031 &child_of_bds, bdrv_backing_role(bs_new),
5032 &bs_new->backing, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005033 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005034 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005035 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005036
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005037 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005038 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005039 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005040 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005041
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005042 ret = bdrv_refresh_perms(bs_new, errp);
5043out:
5044 tran_finalize(tran, ret);
5045
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005046 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005047
5048 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005049}
5050
Fam Zheng4f6fd342013-08-23 09:14:47 +08005051static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005052{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005053 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005054 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02005055
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005056 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005057 if (bs->node_name[0] != '\0') {
5058 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5059 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005060 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5061
Anton Kuchin30c321f2019-05-07 11:12:56 +03005062 bdrv_close(bs);
5063
Anthony Liguori7267c092011-08-20 22:09:37 -05005064 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005065}
5066
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005067BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *node_options,
5068 int flags, Error **errp)
5069{
5070 BlockDriverState *new_node_bs;
5071 Error *local_err = NULL;
5072
5073 new_node_bs = bdrv_open(NULL, NULL, node_options, flags, errp);
5074 if (new_node_bs == NULL) {
5075 error_prepend(errp, "Could not create node: ");
5076 return NULL;
5077 }
5078
5079 bdrv_drained_begin(bs);
5080 bdrv_replace_node(bs, new_node_bs, &local_err);
5081 bdrv_drained_end(bs);
5082
5083 if (local_err) {
5084 bdrv_unref(new_node_bs);
5085 error_propagate(errp, local_err);
5086 return NULL;
5087 }
5088
5089 return new_node_bs;
5090}
5091
aliguorie97fc192009-04-21 23:11:50 +00005092/*
5093 * Run consistency checks on an image
5094 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005095 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005096 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005097 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005098 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005099int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5100 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005101{
Max Reitz908bcd52014-08-07 22:47:55 +02005102 if (bs->drv == NULL) {
5103 return -ENOMEDIUM;
5104 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005105 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005106 return -ENOTSUP;
5107 }
5108
Kevin Wolfe076f332010-06-29 11:43:13 +02005109 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005110 return bs->drv->bdrv_co_check(bs, res, fix);
5111}
5112
Kevin Wolf756e6732010-01-12 12:55:17 +01005113/*
5114 * Return values:
5115 * 0 - success
5116 * -EINVAL - backing format specified, but no file
5117 * -ENOSPC - can't update the backing file because no space is left in the
5118 * image file header
5119 * -ENOTSUP - format driver doesn't support changing the backing file
5120 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005121int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
Eric Blake497a30d2021-05-03 14:36:00 -07005122 const char *backing_fmt, bool require)
Kevin Wolf756e6732010-01-12 12:55:17 +01005123{
5124 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005125 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005126
Max Reitzd470ad42017-11-10 21:31:09 +01005127 if (!drv) {
5128 return -ENOMEDIUM;
5129 }
5130
Paolo Bonzini5f377792012-04-12 14:01:01 +02005131 /* Backing file format doesn't make sense without a backing file */
5132 if (backing_fmt && !backing_file) {
5133 return -EINVAL;
5134 }
5135
Eric Blake497a30d2021-05-03 14:36:00 -07005136 if (require && backing_file && !backing_fmt) {
5137 return -EINVAL;
Eric Blakee54ee1b2020-07-06 15:39:53 -05005138 }
5139
Kevin Wolf756e6732010-01-12 12:55:17 +01005140 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005141 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005142 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005143 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005144 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005145
5146 if (ret == 0) {
5147 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5148 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005149 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5150 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005151 }
5152 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005153}
5154
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005155/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005156 * Finds the first non-filter node above bs in the chain between
5157 * active and bs. The returned node is either an immediate parent of
5158 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005159 *
5160 * Returns NULL if bs is not found in active's image chain,
5161 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005162 *
5163 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005164 */
5165BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5166 BlockDriverState *bs)
5167{
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005168 bs = bdrv_skip_filters(bs);
5169 active = bdrv_skip_filters(active);
5170
5171 while (active) {
5172 BlockDriverState *next = bdrv_backing_chain_next(active);
5173 if (bs == next) {
5174 return active;
5175 }
5176 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005177 }
5178
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005179 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005180}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005181
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005182/* Given a BDS, searches for the base layer. */
5183BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5184{
5185 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005186}
5187
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005188/*
Max Reitz7b99a262019-06-12 16:07:11 +02005189 * Return true if at least one of the COW (backing) and filter links
5190 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005191 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005192 */
5193bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5194 Error **errp)
5195{
5196 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005197 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005198
Max Reitz7b99a262019-06-12 16:07:11 +02005199 for (i = bs; i != base; i = child_bs(child)) {
5200 child = bdrv_filter_or_cow_child(i);
5201
5202 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005203 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005204 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005205 return true;
5206 }
5207 }
5208
5209 return false;
5210}
5211
5212/*
Max Reitz7b99a262019-06-12 16:07:11 +02005213 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005214 * If any of the links is already frozen the operation is aborted and
5215 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005216 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005217 * Returns 0 on success. On failure returns < 0 and sets @errp.
5218 */
5219int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5220 Error **errp)
5221{
5222 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005223 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005224
5225 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5226 return -EPERM;
5227 }
5228
Max Reitz7b99a262019-06-12 16:07:11 +02005229 for (i = bs; i != base; i = child_bs(child)) {
5230 child = bdrv_filter_or_cow_child(i);
5231 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005232 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005233 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005234 return -EPERM;
5235 }
5236 }
5237
Max Reitz7b99a262019-06-12 16:07:11 +02005238 for (i = bs; i != base; i = child_bs(child)) {
5239 child = bdrv_filter_or_cow_child(i);
5240 if (child) {
5241 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005242 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005243 }
5244
5245 return 0;
5246}
5247
5248/*
Max Reitz7b99a262019-06-12 16:07:11 +02005249 * Unfreeze all COW (backing) and filter links between @bs and @base.
5250 * The caller must ensure that all links are frozen before using this
5251 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005252 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005253 */
5254void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5255{
5256 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005257 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005258
Max Reitz7b99a262019-06-12 16:07:11 +02005259 for (i = bs; i != base; i = child_bs(child)) {
5260 child = bdrv_filter_or_cow_child(i);
5261 if (child) {
5262 assert(child->frozen);
5263 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005264 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005265 }
5266}
5267
5268/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005269 * Drops images above 'base' up to and including 'top', and sets the image
5270 * above 'top' to have base as its backing file.
5271 *
5272 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5273 * information in 'bs' can be properly updated.
5274 *
5275 * E.g., this will convert the following chain:
5276 * bottom <- base <- intermediate <- top <- active
5277 *
5278 * to
5279 *
5280 * bottom <- base <- active
5281 *
5282 * It is allowed for bottom==base, in which case it converts:
5283 *
5284 * base <- intermediate <- top <- active
5285 *
5286 * to
5287 *
5288 * base <- active
5289 *
Jeff Cody54e26902014-06-25 15:40:10 -04005290 * If backing_file_str is non-NULL, it will be used when modifying top's
5291 * overlay image metadata.
5292 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005293 * Error conditions:
5294 * if active == top, that is considered an error
5295 *
5296 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005297int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5298 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005299{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005300 BlockDriverState *explicit_top = top;
5301 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005302 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005303 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005304 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005305 g_autoptr(GSList) updated_children = NULL;
5306 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005307
Kevin Wolf6858eba2017-06-29 19:32:21 +02005308 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005309 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005310
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005311 if (!top->drv || !base->drv) {
5312 goto exit;
5313 }
5314
Kevin Wolf5db15a52015-09-14 15:33:33 +02005315 /* Make sure that base is in the backing chain of top */
5316 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005317 goto exit;
5318 }
5319
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005320 /* If 'base' recursively inherits from 'top' then we should set
5321 * base->inherits_from to top->inherits_from after 'top' and all
5322 * other intermediate nodes have been dropped.
5323 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5324 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005325 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005326 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5327
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005328 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolfbde70712017-06-27 20:36:18 +02005329 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
5330 * we've figured out how they should work. */
Max Reitzf30c66b2019-02-01 20:29:05 +01005331 if (!backing_file_str) {
5332 bdrv_refresh_filename(base);
5333 backing_file_str = base->filename;
5334 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005335
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005336 QLIST_FOREACH(c, &top->parents, next_parent) {
5337 updated_children = g_slist_prepend(updated_children, c);
5338 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005339
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005340 /*
5341 * It seems correct to pass detach_subchain=true here, but it triggers
5342 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5343 * another drained section, which modify the graph (for example, removing
5344 * the child, which we keep in updated_children list). So, it's a TODO.
5345 *
5346 * Note, bug triggered if pass detach_subchain=true here and run
5347 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5348 * That's a FIXME.
5349 */
5350 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005351 if (local_err) {
5352 error_report_err(local_err);
5353 goto exit;
5354 }
5355
5356 for (p = updated_children; p; p = p->next) {
5357 c = p->data;
5358
Max Reitzbd86fb92020-05-13 13:05:13 +02005359 if (c->klass->update_filename) {
5360 ret = c->klass->update_filename(c, base, backing_file_str,
5361 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005362 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005363 /*
5364 * TODO: Actually, we want to rollback all previous iterations
5365 * of this loop, and (which is almost impossible) previous
5366 * bdrv_replace_node()...
5367 *
5368 * Note, that c->klass->update_filename may lead to permission
5369 * update, so it's a bad idea to call it inside permission
5370 * update transaction of bdrv_replace_node.
5371 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005372 error_report_err(local_err);
5373 goto exit;
5374 }
5375 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005376 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005377
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005378 if (update_inherits_from) {
5379 base->inherits_from = explicit_top->inherits_from;
5380 }
5381
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005382 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005383exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005384 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005385 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005386 return ret;
5387}
5388
bellard83f64092006-08-01 16:21:11 +00005389/**
Max Reitz081e4652019-06-12 18:14:13 +02005390 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5391 * sums the size of all data-bearing children. (This excludes backing
5392 * children.)
5393 */
5394static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5395{
5396 BdrvChild *child;
5397 int64_t child_size, sum = 0;
5398
5399 QLIST_FOREACH(child, &bs->children, next) {
5400 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5401 BDRV_CHILD_FILTERED))
5402 {
5403 child_size = bdrv_get_allocated_file_size(child->bs);
5404 if (child_size < 0) {
5405 return child_size;
5406 }
5407 sum += child_size;
5408 }
5409 }
5410
5411 return sum;
5412}
5413
5414/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005415 * Length of a allocated file in bytes. Sparse files are counted by actual
5416 * allocated space. Return < 0 if error or unknown.
5417 */
5418int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5419{
5420 BlockDriver *drv = bs->drv;
5421 if (!drv) {
5422 return -ENOMEDIUM;
5423 }
5424 if (drv->bdrv_get_allocated_file_size) {
5425 return drv->bdrv_get_allocated_file_size(bs);
5426 }
Max Reitz081e4652019-06-12 18:14:13 +02005427
5428 if (drv->bdrv_file_open) {
5429 /*
5430 * Protocol drivers default to -ENOTSUP (most of their data is
5431 * not stored in any of their children (if they even have any),
5432 * so there is no generic way to figure it out).
5433 */
5434 return -ENOTSUP;
5435 } else if (drv->is_filter) {
5436 /* Filter drivers default to the size of their filtered child */
5437 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5438 } else {
5439 /* Other drivers default to summing their children's sizes */
5440 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005441 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005442}
5443
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005444/*
5445 * bdrv_measure:
5446 * @drv: Format driver
5447 * @opts: Creation options for new image
5448 * @in_bs: Existing image containing data for new image (may be NULL)
5449 * @errp: Error object
5450 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5451 * or NULL on error
5452 *
5453 * Calculate file size required to create a new image.
5454 *
5455 * If @in_bs is given then space for allocated clusters and zero clusters
5456 * from that image are included in the calculation. If @opts contains a
5457 * backing file that is shared by @in_bs then backing clusters may be omitted
5458 * from the calculation.
5459 *
5460 * If @in_bs is NULL then the calculation includes no allocated clusters
5461 * unless a preallocation option is given in @opts.
5462 *
5463 * Note that @in_bs may use a different BlockDriver from @drv.
5464 *
5465 * If an error occurs the @errp pointer is set.
5466 */
5467BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5468 BlockDriverState *in_bs, Error **errp)
5469{
5470 if (!drv->bdrv_measure) {
5471 error_setg(errp, "Block driver '%s' does not support size measurement",
5472 drv->format_name);
5473 return NULL;
5474 }
5475
5476 return drv->bdrv_measure(opts, in_bs, errp);
5477}
5478
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005479/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005480 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005481 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005482int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005483{
5484 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005485
bellard83f64092006-08-01 16:21:11 +00005486 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005487 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005488
Kevin Wolfb94a2612013-10-29 12:18:58 +01005489 if (drv->has_variable_length) {
5490 int ret = refresh_total_sectors(bs, bs->total_sectors);
5491 if (ret < 0) {
5492 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005493 }
bellard83f64092006-08-01 16:21:11 +00005494 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005495 return bs->total_sectors;
5496}
5497
5498/**
5499 * Return length in bytes on success, -errno on error.
5500 * The length is always a multiple of BDRV_SECTOR_SIZE.
5501 */
5502int64_t bdrv_getlength(BlockDriverState *bs)
5503{
5504 int64_t ret = bdrv_nb_sectors(bs);
5505
Eric Blake122860b2020-11-05 09:51:22 -06005506 if (ret < 0) {
5507 return ret;
5508 }
5509 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5510 return -EFBIG;
5511 }
5512 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005513}
5514
bellard19cb3732006-08-19 11:45:59 +00005515/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005516void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005517{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005518 int64_t nb_sectors = bdrv_nb_sectors(bs);
5519
5520 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005521}
bellardcf989512004-02-16 21:56:36 +00005522
Eric Blake54115412016-06-23 16:37:26 -06005523bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005524{
5525 return bs->sg;
5526}
5527
Max Reitzae23f782019-06-12 22:57:15 +02005528/**
5529 * Return whether the given node supports compressed writes.
5530 */
5531bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5532{
5533 BlockDriverState *filtered;
5534
5535 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5536 return false;
5537 }
5538
5539 filtered = bdrv_filter_bs(bs);
5540 if (filtered) {
5541 /*
5542 * Filters can only forward compressed writes, so we have to
5543 * check the child.
5544 */
5545 return bdrv_supports_compressed_writes(filtered);
5546 }
5547
5548 return true;
5549}
5550
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005551const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005552{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005553 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005554}
5555
Stefan Hajnocziada42402014-08-27 12:08:55 +01005556static int qsort_strcmp(const void *a, const void *b)
5557{
Max Reitzceff5bd2016-10-12 22:49:05 +02005558 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005559}
5560
ths5fafdf22007-09-16 21:08:06 +00005561void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005562 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005563{
5564 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005565 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005566 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005567 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005568
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005569 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005570 if (drv->format_name) {
5571 bool found = false;
5572 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005573
5574 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5575 continue;
5576 }
5577
Jeff Codye855e4f2014-04-28 18:29:54 -04005578 while (formats && i && !found) {
5579 found = !strcmp(formats[--i], drv->format_name);
5580 }
5581
5582 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005583 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005584 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005585 }
5586 }
bellardea2384d2004-08-01 21:59:26 +00005587 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005588
Max Reitzeb0df692016-10-12 22:49:06 +02005589 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5590 const char *format_name = block_driver_modules[i].format_name;
5591
5592 if (format_name) {
5593 bool found = false;
5594 int j = count;
5595
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005596 if (use_bdrv_whitelist &&
5597 !bdrv_format_is_whitelisted(format_name, read_only)) {
5598 continue;
5599 }
5600
Max Reitzeb0df692016-10-12 22:49:06 +02005601 while (formats && j && !found) {
5602 found = !strcmp(formats[--j], format_name);
5603 }
5604
5605 if (!found) {
5606 formats = g_renew(const char *, formats, count + 1);
5607 formats[count++] = format_name;
5608 }
5609 }
5610 }
5611
Stefan Hajnocziada42402014-08-27 12:08:55 +01005612 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5613
5614 for (i = 0; i < count; i++) {
5615 it(opaque, formats[i]);
5616 }
5617
Jeff Codye855e4f2014-04-28 18:29:54 -04005618 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005619}
5620
Benoît Canetdc364f42014-01-23 21:31:32 +01005621/* This function is to find a node in the bs graph */
5622BlockDriverState *bdrv_find_node(const char *node_name)
5623{
5624 BlockDriverState *bs;
5625
5626 assert(node_name);
5627
5628 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5629 if (!strcmp(node_name, bs->node_name)) {
5630 return bs;
5631 }
5632 }
5633 return NULL;
5634}
5635
Benoît Canetc13163f2014-01-23 21:31:34 +01005636/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005637BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5638 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005639{
Eric Blake9812e712020-10-27 00:05:47 -05005640 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005641 BlockDriverState *bs;
5642
5643 list = NULL;
5644 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005645 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005646 if (!info) {
5647 qapi_free_BlockDeviceInfoList(list);
5648 return NULL;
5649 }
Eric Blake9812e712020-10-27 00:05:47 -05005650 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005651 }
5652
5653 return list;
5654}
5655
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005656typedef struct XDbgBlockGraphConstructor {
5657 XDbgBlockGraph *graph;
5658 GHashTable *graph_nodes;
5659} XDbgBlockGraphConstructor;
5660
5661static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5662{
5663 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5664
5665 gr->graph = g_new0(XDbgBlockGraph, 1);
5666 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5667
5668 return gr;
5669}
5670
5671static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5672{
5673 XDbgBlockGraph *graph = gr->graph;
5674
5675 g_hash_table_destroy(gr->graph_nodes);
5676 g_free(gr);
5677
5678 return graph;
5679}
5680
5681static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5682{
5683 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5684
5685 if (ret != 0) {
5686 return ret;
5687 }
5688
5689 /*
5690 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5691 * answer of g_hash_table_lookup.
5692 */
5693 ret = g_hash_table_size(gr->graph_nodes) + 1;
5694 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5695
5696 return ret;
5697}
5698
5699static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5700 XDbgBlockGraphNodeType type, const char *name)
5701{
5702 XDbgBlockGraphNode *n;
5703
5704 n = g_new0(XDbgBlockGraphNode, 1);
5705
5706 n->id = xdbg_graph_node_num(gr, node);
5707 n->type = type;
5708 n->name = g_strdup(name);
5709
Eric Blake9812e712020-10-27 00:05:47 -05005710 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005711}
5712
5713static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5714 const BdrvChild *child)
5715{
Max Reitzcdb1cec2019-11-08 13:34:52 +01005716 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005717 XDbgBlockGraphEdge *edge;
5718
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005719 edge = g_new0(XDbgBlockGraphEdge, 1);
5720
5721 edge->parent = xdbg_graph_node_num(gr, parent);
5722 edge->child = xdbg_graph_node_num(gr, child->bs);
5723 edge->name = g_strdup(child->name);
5724
Max Reitzcdb1cec2019-11-08 13:34:52 +01005725 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5726 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5727
5728 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005729 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005730 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01005731 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005732 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005733 }
5734 }
5735
Eric Blake9812e712020-10-27 00:05:47 -05005736 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005737}
5738
5739
5740XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5741{
5742 BlockBackend *blk;
5743 BlockJob *job;
5744 BlockDriverState *bs;
5745 BdrvChild *child;
5746 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5747
5748 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5749 char *allocated_name = NULL;
5750 const char *name = blk_name(blk);
5751
5752 if (!*name) {
5753 name = allocated_name = blk_get_attached_dev_id(blk);
5754 }
5755 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5756 name);
5757 g_free(allocated_name);
5758 if (blk_root(blk)) {
5759 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5760 }
5761 }
5762
5763 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5764 GSList *el;
5765
5766 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5767 job->job.id);
5768 for (el = job->nodes; el; el = el->next) {
5769 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5770 }
5771 }
5772
5773 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5774 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5775 bs->node_name);
5776 QLIST_FOREACH(child, &bs->children, next) {
5777 xdbg_graph_add_edge(gr, bs, child);
5778 }
5779 }
5780
5781 return xdbg_graph_finalize(gr);
5782}
5783
Benoît Canet12d3ba82014-01-23 21:31:35 +01005784BlockDriverState *bdrv_lookup_bs(const char *device,
5785 const char *node_name,
5786 Error **errp)
5787{
Markus Armbruster7f06d472014-10-07 13:59:12 +02005788 BlockBackend *blk;
5789 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005790
Benoît Canet12d3ba82014-01-23 21:31:35 +01005791 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02005792 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005793
Markus Armbruster7f06d472014-10-07 13:59:12 +02005794 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005795 bs = blk_bs(blk);
5796 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02005797 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02005798 }
5799
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005800 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005801 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005802 }
5803
Benoît Canetdd67fa52014-02-12 17:15:06 +01005804 if (node_name) {
5805 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005806
Benoît Canetdd67fa52014-02-12 17:15:06 +01005807 if (bs) {
5808 return bs;
5809 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005810 }
5811
Connor Kuehl785ec4b2021-03-05 09:19:28 -06005812 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01005813 device ? device : "",
5814 node_name ? node_name : "");
5815 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005816}
5817
Jeff Cody5a6684d2014-06-25 15:40:09 -04005818/* If 'base' is in the same chain as 'top', return true. Otherwise,
5819 * return false. If either argument is NULL, return false. */
5820bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5821{
5822 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005823 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04005824 }
5825
5826 return top != NULL;
5827}
5828
Fam Zheng04df7652014-10-31 11:32:54 +08005829BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5830{
5831 if (!bs) {
5832 return QTAILQ_FIRST(&graph_bdrv_states);
5833 }
5834 return QTAILQ_NEXT(bs, node_list);
5835}
5836
Kevin Wolf0f122642018-03-28 18:29:18 +02005837BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5838{
5839 if (!bs) {
5840 return QTAILQ_FIRST(&all_bdrv_states);
5841 }
5842 return QTAILQ_NEXT(bs, bs_list);
5843}
5844
Fam Zheng20a9e772014-10-31 11:32:55 +08005845const char *bdrv_get_node_name(const BlockDriverState *bs)
5846{
5847 return bs->node_name;
5848}
5849
Kevin Wolf1f0c4612016-03-22 18:38:44 +01005850const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005851{
5852 BdrvChild *c;
5853 const char *name;
5854
5855 /* If multiple parents have a name, just pick the first one. */
5856 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005857 if (c->klass->get_name) {
5858 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005859 if (name && *name) {
5860 return name;
5861 }
5862 }
5863 }
5864
5865 return NULL;
5866}
5867
Markus Armbruster7f06d472014-10-07 13:59:12 +02005868/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02005869const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005870{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005871 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00005872}
5873
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005874/* This can be used to identify nodes that might not have a device
5875 * name associated. Since node and device names live in the same
5876 * namespace, the result is unambiguous. The exception is if both are
5877 * absent, then this returns an empty (non-null) string. */
5878const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5879{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005880 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005881}
5882
Markus Armbrusterc8433282012-06-05 16:49:24 +02005883int bdrv_get_flags(BlockDriverState *bs)
5884{
5885 return bs->open_flags;
5886}
5887
Peter Lieven3ac21622013-06-28 12:47:42 +02005888int bdrv_has_zero_init_1(BlockDriverState *bs)
5889{
5890 return 1;
5891}
5892
Kevin Wolff2feebb2010-04-14 17:30:35 +02005893int bdrv_has_zero_init(BlockDriverState *bs)
5894{
Max Reitz93393e62019-06-12 17:03:38 +02005895 BlockDriverState *filtered;
5896
Max Reitzd470ad42017-11-10 21:31:09 +01005897 if (!bs->drv) {
5898 return 0;
5899 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005900
Paolo Bonzini11212d82013-09-04 19:00:27 +02005901 /* If BS is a copy on write image, it is initialized to
5902 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02005903 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02005904 return 0;
5905 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02005906 if (bs->drv->bdrv_has_zero_init) {
5907 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02005908 }
Max Reitz93393e62019-06-12 17:03:38 +02005909
5910 filtered = bdrv_filter_bs(bs);
5911 if (filtered) {
5912 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005913 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005914
Peter Lieven3ac21622013-06-28 12:47:42 +02005915 /* safe default */
5916 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02005917}
5918
Peter Lieven4ce78692013-10-24 12:06:54 +02005919bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5920{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03005921 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02005922 return false;
5923 }
5924
Eric Blakee24d8132018-01-26 13:34:39 -06005925 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02005926}
5927
ths5fafdf22007-09-16 21:08:06 +00005928void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00005929 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00005930{
Kevin Wolf3574c602011-10-26 11:02:11 +02005931 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00005932}
5933
bellardfaea38e2006-08-05 21:31:00 +00005934int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5935{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005936 int ret;
bellardfaea38e2006-08-05 21:31:00 +00005937 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005938 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5939 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00005940 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005941 }
5942 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02005943 BlockDriverState *filtered = bdrv_filter_bs(bs);
5944 if (filtered) {
5945 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005946 }
bellardfaea38e2006-08-05 21:31:00 +00005947 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005948 }
bellardfaea38e2006-08-05 21:31:00 +00005949 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005950 ret = drv->bdrv_get_info(bs, bdi);
5951 if (ret < 0) {
5952 return ret;
5953 }
5954
5955 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
5956 return -EINVAL;
5957 }
5958
5959 return 0;
bellardfaea38e2006-08-05 21:31:00 +00005960}
5961
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005962ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5963 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02005964{
5965 BlockDriver *drv = bs->drv;
5966 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005967 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02005968 }
5969 return NULL;
5970}
5971
Anton Nefedovd9245592019-09-23 15:17:37 +03005972BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5973{
5974 BlockDriver *drv = bs->drv;
5975 if (!drv || !drv->bdrv_get_specific_stats) {
5976 return NULL;
5977 }
5978 return drv->bdrv_get_specific_stats(bs);
5979}
5980
Eric Blakea31939e2015-11-18 01:52:54 -07005981void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005982{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005983 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005984 return;
5985 }
5986
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005987 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005988}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005989
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005990static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01005991{
5992 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02005993 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005994 }
5995
5996 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005997 assert(bs->drv->bdrv_debug_remove_breakpoint);
5998 return bs;
5999 }
6000
6001 return NULL;
6002}
6003
6004int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6005 const char *tag)
6006{
6007 bs = bdrv_find_debug_node(bs);
6008 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006009 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6010 }
6011
6012 return -ENOTSUP;
6013}
6014
Fam Zheng4cc70e92013-11-20 10:01:54 +08006015int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6016{
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006017 bs = bdrv_find_debug_node(bs);
6018 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006019 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6020 }
6021
6022 return -ENOTSUP;
6023}
6024
Kevin Wolf41c695c2012-12-06 14:32:58 +01006025int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6026{
Max Reitz938789e2014-03-10 23:44:08 +01006027 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006028 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006029 }
6030
6031 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6032 return bs->drv->bdrv_debug_resume(bs, tag);
6033 }
6034
6035 return -ENOTSUP;
6036}
6037
6038bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6039{
6040 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006041 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006042 }
6043
6044 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6045 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6046 }
6047
6048 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006049}
6050
Jeff Codyb1b1d782012-10-16 15:49:09 -04006051/* backing_file can either be relative, or absolute, or a protocol. If it is
6052 * relative, it must be relative to the chain. So, passing in bs->filename
6053 * from a BDS as backing_file should not be done, as that may be relative to
6054 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006055BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6056 const char *backing_file)
6057{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006058 char *filename_full = NULL;
6059 char *backing_file_full = NULL;
6060 char *filename_tmp = NULL;
6061 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006062 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006063 BlockDriverState *curr_bs = NULL;
6064 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006065 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006066
6067 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006068 return NULL;
6069 }
6070
Jeff Codyb1b1d782012-10-16 15:49:09 -04006071 filename_full = g_malloc(PATH_MAX);
6072 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006073
6074 is_protocol = path_has_protocol(backing_file);
6075
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006076 /*
6077 * Being largely a legacy function, skip any filters here
6078 * (because filters do not have normal filenames, so they cannot
6079 * match anyway; and allowing json:{} filenames is a bit out of
6080 * scope).
6081 */
6082 for (curr_bs = bdrv_skip_filters(bs);
6083 bdrv_cow_child(curr_bs) != NULL;
6084 curr_bs = bs_below)
6085 {
6086 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006087
Max Reitz0b877d02018-08-01 20:34:11 +02006088 if (bdrv_backing_overridden(curr_bs)) {
6089 /*
6090 * If the backing file was overridden, we can only compare
6091 * directly against the backing node's filename.
6092 */
6093
6094 if (!filenames_refreshed) {
6095 /*
6096 * This will automatically refresh all of the
6097 * filenames in the rest of the backing chain, so we
6098 * only need to do this once.
6099 */
6100 bdrv_refresh_filename(bs_below);
6101 filenames_refreshed = true;
6102 }
6103
6104 if (strcmp(backing_file, bs_below->filename) == 0) {
6105 retval = bs_below;
6106 break;
6107 }
6108 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6109 /*
6110 * If either of the filename paths is actually a protocol, then
6111 * compare unmodified paths; otherwise make paths relative.
6112 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006113 char *backing_file_full_ret;
6114
Jeff Codyb1b1d782012-10-16 15:49:09 -04006115 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006116 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006117 break;
6118 }
Jeff Cody418661e2017-01-25 20:08:20 -05006119 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006120 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6121 NULL);
6122 if (backing_file_full_ret) {
6123 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6124 g_free(backing_file_full_ret);
6125 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006126 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006127 break;
6128 }
Jeff Cody418661e2017-01-25 20:08:20 -05006129 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006130 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006131 /* If not an absolute filename path, make it relative to the current
6132 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006133 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6134 NULL);
6135 /* We are going to compare canonicalized absolute pathnames */
6136 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6137 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006138 continue;
6139 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006140 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006141
6142 /* We need to make sure the backing filename we are comparing against
6143 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006144 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6145 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6146 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006147 continue;
6148 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006149 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006150
6151 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006152 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006153 break;
6154 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006155 }
6156 }
6157
Jeff Codyb1b1d782012-10-16 15:49:09 -04006158 g_free(filename_full);
6159 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006160 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006161}
6162
bellardea2384d2004-08-01 21:59:26 +00006163void bdrv_init(void)
6164{
Kevin Wolfe5f05f82021-07-09 18:41:41 +02006165#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6166 use_bdrv_whitelist = 1;
6167#endif
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006168 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006169}
pbrookce1a14d2006-08-07 02:38:06 +00006170
Markus Armbrustereb852012009-10-27 18:41:44 +01006171void bdrv_init_with_whitelist(void)
6172{
6173 use_bdrv_whitelist = 1;
6174 bdrv_init();
6175}
6176
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03006177int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006178{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006179 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006180 Error *local_err = NULL;
6181 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006182 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006183
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006184 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006185 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006186 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006187
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006188 QLIST_FOREACH(child, &bs->children, next) {
Paolo Bonzini2b148f32018-03-01 17:36:18 +01006189 bdrv_co_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006190 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006191 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006192 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006193 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006194 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006195
Kevin Wolfdafe0962017-11-16 13:00:01 +01006196 /*
6197 * Update permissions, they may differ for inactive nodes.
6198 *
6199 * Note that the required permissions of inactive images are always a
6200 * subset of the permissions required after activating the image. This
6201 * allows us to just get the permissions upfront without restricting
6202 * drv->bdrv_invalidate_cache().
6203 *
6204 * It also means that in error cases, we don't have to try and revert to
6205 * the old permissions (which is an operation that could fail, too). We can
6206 * just keep the extended permissions for the next time that an activation
6207 * of the image is tried.
6208 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006209 if (bs->open_flags & BDRV_O_INACTIVE) {
6210 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006211 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006212 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006213 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006214 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006215 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006216
Kevin Wolf7bb49412019-12-17 15:06:38 +01006217 if (bs->drv->bdrv_co_invalidate_cache) {
6218 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6219 if (local_err) {
6220 bs->open_flags |= BDRV_O_INACTIVE;
6221 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006222 return -EINVAL;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006223 }
6224 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006225
Kevin Wolf7bb49412019-12-17 15:06:38 +01006226 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6227 bdrv_dirty_bitmap_skip_store(bm, false);
6228 }
6229
6230 ret = refresh_total_sectors(bs, bs->total_sectors);
6231 if (ret < 0) {
6232 bs->open_flags |= BDRV_O_INACTIVE;
6233 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006234 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006235 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006236 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006237
6238 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006239 if (parent->klass->activate) {
6240 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006241 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006242 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006243 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006244 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006245 }
6246 }
6247 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006248
6249 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006250}
6251
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006252void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006253{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006254 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006255 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006256
Kevin Wolf88be7b42016-05-20 18:49:07 +02006257 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006258 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006259 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006260
6261 aio_context_acquire(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006262 ret = bdrv_invalidate_cache(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006263 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006264 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006265 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006266 return;
6267 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006268 }
6269}
6270
Kevin Wolf9e372712018-11-23 15:11:14 +01006271static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6272{
6273 BdrvChild *parent;
6274
6275 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006276 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006277 BlockDriverState *parent_bs = parent->opaque;
6278 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6279 return true;
6280 }
6281 }
6282 }
6283
6284 return false;
6285}
6286
6287static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006288{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006289 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006290 int ret;
6291
Max Reitzd470ad42017-11-10 21:31:09 +01006292 if (!bs->drv) {
6293 return -ENOMEDIUM;
6294 }
6295
Kevin Wolf9e372712018-11-23 15:11:14 +01006296 /* Make sure that we don't inactivate a child before its parent.
6297 * It will be covered by recursion from the yet active parent. */
6298 if (bdrv_has_bds_parent(bs, true)) {
6299 return 0;
6300 }
6301
6302 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6303
6304 /* Inactivate this node */
6305 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006306 ret = bs->drv->bdrv_inactivate(bs);
6307 if (ret < 0) {
6308 return ret;
6309 }
6310 }
6311
Kevin Wolf9e372712018-11-23 15:11:14 +01006312 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006313 if (parent->klass->inactivate) {
6314 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006315 if (ret < 0) {
6316 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006317 }
6318 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006319 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006320
Kevin Wolf9e372712018-11-23 15:11:14 +01006321 bs->open_flags |= BDRV_O_INACTIVE;
6322
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006323 /*
6324 * Update permissions, they may differ for inactive nodes.
6325 * We only tried to loosen restrictions, so errors are not fatal, ignore
6326 * them.
6327 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006328 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006329
6330 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006331 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006332 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006333 if (ret < 0) {
6334 return ret;
6335 }
6336 }
6337
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006338 return 0;
6339}
6340
6341int bdrv_inactivate_all(void)
6342{
Max Reitz79720af2016-03-16 19:54:44 +01006343 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006344 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006345 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006346 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006347
Kevin Wolf88be7b42016-05-20 18:49:07 +02006348 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006349 AioContext *aio_context = bdrv_get_aio_context(bs);
6350
6351 if (!g_slist_find(aio_ctxs, aio_context)) {
6352 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6353 aio_context_acquire(aio_context);
6354 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006355 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006356
Kevin Wolf9e372712018-11-23 15:11:14 +01006357 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6358 /* Nodes with BDS parents are covered by recursion from the last
6359 * parent that gets inactivated. Don't inactivate them a second
6360 * time if that has already happened. */
6361 if (bdrv_has_bds_parent(bs, false)) {
6362 continue;
6363 }
6364 ret = bdrv_inactivate_recurse(bs);
6365 if (ret < 0) {
6366 bdrv_next_cleanup(&it);
6367 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006368 }
6369 }
6370
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006371out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006372 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6373 AioContext *aio_context = ctx->data;
6374 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006375 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006376 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006377
6378 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006379}
6380
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006381/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006382/* removable device support */
6383
6384/**
6385 * Return TRUE if the media is present
6386 */
Max Reitze031f752015-10-19 17:53:11 +02006387bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006388{
6389 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006390 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006391
Max Reitze031f752015-10-19 17:53:11 +02006392 if (!drv) {
6393 return false;
6394 }
Max Reitz28d7a782015-10-19 17:53:13 +02006395 if (drv->bdrv_is_inserted) {
6396 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006397 }
Max Reitz28d7a782015-10-19 17:53:13 +02006398 QLIST_FOREACH(child, &bs->children, next) {
6399 if (!bdrv_is_inserted(child->bs)) {
6400 return false;
6401 }
6402 }
6403 return true;
bellard19cb3732006-08-19 11:45:59 +00006404}
6405
6406/**
bellard19cb3732006-08-19 11:45:59 +00006407 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6408 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006409void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006410{
6411 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006412
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006413 if (drv && drv->bdrv_eject) {
6414 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006415 }
bellard19cb3732006-08-19 11:45:59 +00006416}
6417
bellard19cb3732006-08-19 11:45:59 +00006418/**
6419 * Lock or unlock the media (if it is locked, the user won't be able
6420 * to eject it manually).
6421 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006422void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006423{
6424 BlockDriver *drv = bs->drv;
6425
Markus Armbruster025e8492011-09-06 18:58:47 +02006426 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006427
Markus Armbruster025e8492011-09-06 18:58:47 +02006428 if (drv && drv->bdrv_lock_medium) {
6429 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006430 }
6431}
ths985a03b2007-12-24 16:10:43 +00006432
Fam Zheng9fcb0252013-08-23 09:14:46 +08006433/* Get a reference to bs */
6434void bdrv_ref(BlockDriverState *bs)
6435{
6436 bs->refcnt++;
6437}
6438
6439/* Release a previously grabbed reference to bs.
6440 * If after releasing, reference count is zero, the BlockDriverState is
6441 * deleted. */
6442void bdrv_unref(BlockDriverState *bs)
6443{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006444 if (!bs) {
6445 return;
6446 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006447 assert(bs->refcnt > 0);
6448 if (--bs->refcnt == 0) {
6449 bdrv_delete(bs);
6450 }
6451}
6452
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006453struct BdrvOpBlocker {
6454 Error *reason;
6455 QLIST_ENTRY(BdrvOpBlocker) list;
6456};
6457
6458bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6459{
6460 BdrvOpBlocker *blocker;
6461 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6462 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6463 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006464 error_propagate_prepend(errp, error_copy(blocker->reason),
6465 "Node '%s' is busy: ",
6466 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006467 return true;
6468 }
6469 return false;
6470}
6471
6472void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6473{
6474 BdrvOpBlocker *blocker;
6475 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6476
Markus Armbruster5839e532014-08-19 10:31:08 +02006477 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006478 blocker->reason = reason;
6479 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6480}
6481
6482void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6483{
6484 BdrvOpBlocker *blocker, *next;
6485 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6486 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6487 if (blocker->reason == reason) {
6488 QLIST_REMOVE(blocker, list);
6489 g_free(blocker);
6490 }
6491 }
6492}
6493
6494void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6495{
6496 int i;
6497 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6498 bdrv_op_block(bs, i, reason);
6499 }
6500}
6501
6502void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6503{
6504 int i;
6505 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6506 bdrv_op_unblock(bs, i, reason);
6507 }
6508}
6509
6510bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6511{
6512 int i;
6513
6514 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6515 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6516 return false;
6517 }
6518 }
6519 return true;
6520}
6521
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006522void bdrv_img_create(const char *filename, const char *fmt,
6523 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006524 char *options, uint64_t img_size, int flags, bool quiet,
6525 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006526{
Chunyan Liu83d05212014-06-05 17:20:51 +08006527 QemuOptsList *create_opts = NULL;
6528 QemuOpts *opts = NULL;
6529 const char *backing_fmt, *backing_file;
6530 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006531 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006532 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006533 int ret = 0;
6534
6535 /* Find driver and parse its options */
6536 drv = bdrv_find_format(fmt);
6537 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006538 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006539 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006540 }
6541
Max Reitzb65a5e12015-02-05 13:58:12 -05006542 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006543 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006544 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006545 }
6546
Max Reitzc6149722014-12-02 18:32:45 +01006547 if (!drv->create_opts) {
6548 error_setg(errp, "Format driver '%s' does not support image creation",
6549 drv->format_name);
6550 return;
6551 }
6552
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006553 if (!proto_drv->create_opts) {
6554 error_setg(errp, "Protocol driver '%s' does not support image creation",
6555 proto_drv->format_name);
6556 return;
6557 }
6558
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006559 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006560 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006561 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006562
Chunyan Liu83d05212014-06-05 17:20:51 +08006563 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006564
6565 /* Parse -o options */
6566 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006567 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006568 goto out;
6569 }
6570 }
6571
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006572 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6573 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6574 } else if (img_size != UINT64_C(-1)) {
6575 error_setg(errp, "The image size must be specified only once");
6576 goto out;
6577 }
6578
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006579 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006580 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006581 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006582 error_setg(errp, "Backing file not supported for file format '%s'",
6583 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006584 goto out;
6585 }
6586 }
6587
6588 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006589 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006590 error_setg(errp, "Backing file format not supported for file "
6591 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006592 goto out;
6593 }
6594 }
6595
Chunyan Liu83d05212014-06-05 17:20:51 +08006596 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6597 if (backing_file) {
6598 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006599 error_setg(errp, "Error: Trying to create an image with the "
6600 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006601 goto out;
6602 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006603 if (backing_file[0] == '\0') {
6604 error_setg(errp, "Expected backing file name, got empty string");
6605 goto out;
6606 }
Jes Sorensen792da932010-12-16 13:52:17 +01006607 }
6608
Chunyan Liu83d05212014-06-05 17:20:51 +08006609 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006610
John Snow6e6e55f2017-07-17 20:34:22 -04006611 /* The size for the image must always be specified, unless we have a backing
6612 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006613 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006614 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6615 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006616 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006617 int back_flags;
6618 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006619
Max Reitz645ae7d2019-02-01 20:29:14 +01006620 full_backing =
6621 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6622 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006623 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006624 goto out;
6625 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006626 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006627
Max Reitzd5b23992021-06-22 16:00:30 +02006628 /*
6629 * No need to do I/O here, which allows us to open encrypted
6630 * backing images without needing the secret
6631 */
John Snow6e6e55f2017-07-17 20:34:22 -04006632 back_flags = flags;
6633 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Max Reitzd5b23992021-06-22 16:00:30 +02006634 back_flags |= BDRV_O_NO_IO;
John Snow6e6e55f2017-07-17 20:34:22 -04006635
Fam Zhengcc954f02017-12-15 16:04:45 +08006636 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006637 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006638 qdict_put_str(backing_options, "driver", backing_fmt);
6639 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006640 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006641
6642 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6643 &local_err);
6644 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006645 if (!bs) {
6646 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006647 goto out;
6648 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006649 if (!backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07006650 error_setg(&local_err,
6651 "Backing file specified without backing format");
6652 error_append_hint(&local_err, "Detected format of %s.",
6653 bs->drv->format_name);
6654 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05006655 }
John Snow6e6e55f2017-07-17 20:34:22 -04006656 if (size == -1) {
6657 /* Opened BS, have no size */
6658 size = bdrv_getlength(bs);
6659 if (size < 0) {
6660 error_setg_errno(errp, -size, "Could not get size of '%s'",
6661 backing_file);
6662 bdrv_unref(bs);
6663 goto out;
6664 }
6665 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6666 }
6667 bdrv_unref(bs);
6668 }
Eric Blaked9f059a2020-07-06 15:39:54 -05006669 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6670 } else if (backing_file && !backing_fmt) {
Eric Blake497a30d2021-05-03 14:36:00 -07006671 error_setg(&local_err,
6672 "Backing file specified without backing format");
6673 goto out;
Eric Blaked9f059a2020-07-06 15:39:54 -05006674 }
John Snow6e6e55f2017-07-17 20:34:22 -04006675
6676 if (size == -1) {
6677 error_setg(errp, "Image creation needs a size parameter");
6678 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006679 }
6680
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006681 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02006682 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08006683 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006684 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05006685 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006686 }
Chunyan Liu83d05212014-06-05 17:20:51 +08006687
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006688 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08006689
Max Reitzcc84d902013-09-06 17:14:26 +02006690 if (ret == -EFBIG) {
6691 /* This is generally a better message than whatever the driver would
6692 * deliver (especially because of the cluster_size_hint), since that
6693 * is most probably not much different from "image too large". */
6694 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08006695 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02006696 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006697 }
Max Reitzcc84d902013-09-06 17:14:26 +02006698 error_setg(errp, "The image size is too large for file format '%s'"
6699 "%s", fmt, cluster_size_hint);
6700 error_free(local_err);
6701 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006702 }
6703
6704out:
Chunyan Liu83d05212014-06-05 17:20:51 +08006705 qemu_opts_del(opts);
6706 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03006707 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006708}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006709
6710AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6711{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00006712 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006713}
6714
Kevin Wolfe336fd42020-10-05 17:58:53 +02006715AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6716{
6717 Coroutine *self = qemu_coroutine_self();
6718 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6719 AioContext *new_ctx;
6720
6721 /*
6722 * Increase bs->in_flight to ensure that this operation is completed before
6723 * moving the node to a different AioContext. Read new_ctx only afterwards.
6724 */
6725 bdrv_inc_in_flight(bs);
6726
6727 new_ctx = bdrv_get_aio_context(bs);
6728 aio_co_reschedule_self(new_ctx);
6729 return old_ctx;
6730}
6731
6732void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6733{
6734 aio_co_reschedule_self(old_ctx);
6735 bdrv_dec_in_flight(bs);
6736}
6737
Kevin Wolf18c6ac12020-10-05 17:58:54 +02006738void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6739{
6740 AioContext *ctx = bdrv_get_aio_context(bs);
6741
6742 /* In the main thread, bs->aio_context won't change concurrently */
6743 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6744
6745 /*
6746 * We're in coroutine context, so we already hold the lock of the main
6747 * loop AioContext. Don't lock it twice to avoid deadlocks.
6748 */
6749 assert(qemu_in_coroutine());
6750 if (ctx != qemu_get_aio_context()) {
6751 aio_context_acquire(ctx);
6752 }
6753}
6754
6755void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6756{
6757 AioContext *ctx = bdrv_get_aio_context(bs);
6758
6759 assert(qemu_in_coroutine());
6760 if (ctx != qemu_get_aio_context()) {
6761 aio_context_release(ctx);
6762 }
6763}
6764
Fam Zheng052a7572017-04-10 20:09:25 +08006765void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6766{
6767 aio_co_enter(bdrv_get_aio_context(bs), co);
6768}
6769
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006770static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6771{
6772 QLIST_REMOVE(ban, list);
6773 g_free(ban);
6774}
6775
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006776static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006777{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006778 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006779
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006780 assert(!bs->walking_aio_notifiers);
6781 bs->walking_aio_notifiers = true;
6782 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6783 if (baf->deleted) {
6784 bdrv_do_remove_aio_context_notifier(baf);
6785 } else {
6786 baf->detach_aio_context(baf->opaque);
6787 }
Max Reitz33384422014-06-20 21:57:33 +02006788 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006789 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6790 * remove remaining aio notifiers if we aren't called again.
6791 */
6792 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02006793
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006794 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006795 bs->drv->bdrv_detach_aio_context(bs);
6796 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006797
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006798 if (bs->quiesce_counter) {
6799 aio_enable_external(bs->aio_context);
6800 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006801 bs->aio_context = NULL;
6802}
6803
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006804static void bdrv_attach_aio_context(BlockDriverState *bs,
6805 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006806{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006807 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006808
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006809 if (bs->quiesce_counter) {
6810 aio_disable_external(new_context);
6811 }
6812
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006813 bs->aio_context = new_context;
6814
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006815 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006816 bs->drv->bdrv_attach_aio_context(bs, new_context);
6817 }
Max Reitz33384422014-06-20 21:57:33 +02006818
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006819 assert(!bs->walking_aio_notifiers);
6820 bs->walking_aio_notifiers = true;
6821 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6822 if (ban->deleted) {
6823 bdrv_do_remove_aio_context_notifier(ban);
6824 } else {
6825 ban->attached_aio_context(new_context, ban->opaque);
6826 }
Max Reitz33384422014-06-20 21:57:33 +02006827 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006828 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006829}
6830
Kevin Wolf42a65f02019-05-07 18:31:38 +02006831/*
6832 * Changes the AioContext used for fd handlers, timers, and BHs by this
6833 * BlockDriverState and all its children and parents.
6834 *
Max Reitz43eaaae2019-07-22 15:30:54 +02006835 * Must be called from the main AioContext.
6836 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02006837 * The caller must own the AioContext lock for the old AioContext of bs, but it
6838 * must not own the AioContext lock for new_context (unless new_context is the
6839 * same as the current context of bs).
6840 *
6841 * @ignore will accumulate all visited BdrvChild object. The caller is
6842 * responsible for freeing the list afterwards.
6843 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02006844void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6845 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006846{
Max Reitze037c092019-07-19 11:26:14 +02006847 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006848 GSList *children_to_process = NULL;
6849 GSList *parents_to_process = NULL;
6850 GSList *entry;
6851 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02006852
Max Reitz43eaaae2019-07-22 15:30:54 +02006853 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6854
Max Reitze037c092019-07-19 11:26:14 +02006855 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03006856 return;
6857 }
6858
Kevin Wolfd70d5952019-02-08 16:53:37 +01006859 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02006860
6861 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006862 if (g_slist_find(*ignore, child)) {
6863 continue;
6864 }
6865 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006866 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02006867 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006868
6869 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6870 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006871 continue;
6872 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006873 *ignore = g_slist_prepend(*ignore, parent);
6874 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02006875 }
6876
Sergio Lopez722d8e72021-02-01 13:50:31 +01006877 for (entry = children_to_process;
6878 entry != NULL;
6879 entry = g_slist_next(entry)) {
6880 child = entry->data;
6881 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6882 }
6883 g_slist_free(children_to_process);
6884
6885 for (entry = parents_to_process;
6886 entry != NULL;
6887 entry = g_slist_next(entry)) {
6888 parent = entry->data;
6889 assert(parent->klass->set_aio_ctx);
6890 parent->klass->set_aio_ctx(parent, new_context, ignore);
6891 }
6892 g_slist_free(parents_to_process);
6893
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006894 bdrv_detach_aio_context(bs);
6895
Max Reitze037c092019-07-19 11:26:14 +02006896 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02006897 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006898 aio_context_acquire(new_context);
6899 }
6900
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006901 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02006902
6903 /*
6904 * If this function was recursively called from
6905 * bdrv_set_aio_context_ignore(), there may be nodes in the
6906 * subtree that have not yet been moved to the new AioContext.
6907 * Release the old one so bdrv_drained_end() can poll them.
6908 */
Max Reitz43eaaae2019-07-22 15:30:54 +02006909 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006910 aio_context_release(old_context);
6911 }
6912
Kevin Wolfd70d5952019-02-08 16:53:37 +01006913 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02006914
Max Reitz43eaaae2019-07-22 15:30:54 +02006915 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006916 aio_context_acquire(old_context);
6917 }
Max Reitz43eaaae2019-07-22 15:30:54 +02006918 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006919 aio_context_release(new_context);
6920 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006921}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02006922
Kevin Wolf5d231842019-05-06 19:17:56 +02006923static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6924 GSList **ignore, Error **errp)
6925{
6926 if (g_slist_find(*ignore, c)) {
6927 return true;
6928 }
6929 *ignore = g_slist_prepend(*ignore, c);
6930
Max Reitzbd86fb92020-05-13 13:05:13 +02006931 /*
6932 * A BdrvChildClass that doesn't handle AioContext changes cannot
6933 * tolerate any AioContext changes
6934 */
6935 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006936 char *user = bdrv_child_user_desc(c);
6937 error_setg(errp, "Changing iothreads is not supported by %s", user);
6938 g_free(user);
6939 return false;
6940 }
Max Reitzbd86fb92020-05-13 13:05:13 +02006941 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006942 assert(!errp || *errp);
6943 return false;
6944 }
6945 return true;
6946}
6947
6948bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6949 GSList **ignore, Error **errp)
6950{
6951 if (g_slist_find(*ignore, c)) {
6952 return true;
6953 }
6954 *ignore = g_slist_prepend(*ignore, c);
6955 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6956}
6957
6958/* @ignore will accumulate all visited BdrvChild object. The caller is
6959 * responsible for freeing the list afterwards. */
6960bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6961 GSList **ignore, Error **errp)
6962{
6963 BdrvChild *c;
6964
6965 if (bdrv_get_aio_context(bs) == ctx) {
6966 return true;
6967 }
6968
6969 QLIST_FOREACH(c, &bs->parents, next_parent) {
6970 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6971 return false;
6972 }
6973 }
6974 QLIST_FOREACH(c, &bs->children, next) {
6975 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6976 return false;
6977 }
6978 }
6979
6980 return true;
6981}
6982
6983int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6984 BdrvChild *ignore_child, Error **errp)
6985{
6986 GSList *ignore;
6987 bool ret;
6988
6989 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6990 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6991 g_slist_free(ignore);
6992
6993 if (!ret) {
6994 return -EPERM;
6995 }
6996
Kevin Wolf53a7d042019-05-06 19:17:59 +02006997 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6998 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6999 g_slist_free(ignore);
7000
Kevin Wolf5d231842019-05-06 19:17:56 +02007001 return 0;
7002}
7003
7004int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7005 Error **errp)
7006{
7007 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7008}
7009
Max Reitz33384422014-06-20 21:57:33 +02007010void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7011 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7012 void (*detach_aio_context)(void *opaque), void *opaque)
7013{
7014 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7015 *ban = (BdrvAioNotifier){
7016 .attached_aio_context = attached_aio_context,
7017 .detach_aio_context = detach_aio_context,
7018 .opaque = opaque
7019 };
7020
7021 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7022}
7023
7024void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7025 void (*attached_aio_context)(AioContext *,
7026 void *),
7027 void (*detach_aio_context)(void *),
7028 void *opaque)
7029{
7030 BdrvAioNotifier *ban, *ban_next;
7031
7032 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7033 if (ban->attached_aio_context == attached_aio_context &&
7034 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007035 ban->opaque == opaque &&
7036 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007037 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007038 if (bs->walking_aio_notifiers) {
7039 ban->deleted = true;
7040 } else {
7041 bdrv_do_remove_aio_context_notifier(ban);
7042 }
Max Reitz33384422014-06-20 21:57:33 +02007043 return;
7044 }
7045 }
7046
7047 abort();
7048}
7049
Max Reitz77485432014-10-27 11:12:50 +01007050int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007051 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007052 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007053 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007054{
Max Reitzd470ad42017-11-10 21:31:09 +01007055 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007056 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007057 return -ENOMEDIUM;
7058 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007059 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007060 error_setg(errp, "Block driver '%s' does not support option amendment",
7061 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007062 return -ENOTSUP;
7063 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007064 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7065 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007066}
Benoît Canetf6186f42013-10-02 14:33:48 +02007067
Max Reitz5d69b5a2020-02-18 11:34:41 +01007068/*
7069 * This function checks whether the given @to_replace is allowed to be
7070 * replaced by a node that always shows the same data as @bs. This is
7071 * used for example to verify whether the mirror job can replace
7072 * @to_replace by the target mirrored from @bs.
7073 * To be replaceable, @bs and @to_replace may either be guaranteed to
7074 * always show the same data (because they are only connected through
7075 * filters), or some driver may allow replacing one of its children
7076 * because it can guarantee that this child's data is not visible at
7077 * all (for example, for dissenting quorum children that have no other
7078 * parents).
7079 */
7080bool bdrv_recurse_can_replace(BlockDriverState *bs,
7081 BlockDriverState *to_replace)
7082{
Max Reitz93393e62019-06-12 17:03:38 +02007083 BlockDriverState *filtered;
7084
Max Reitz5d69b5a2020-02-18 11:34:41 +01007085 if (!bs || !bs->drv) {
7086 return false;
7087 }
7088
7089 if (bs == to_replace) {
7090 return true;
7091 }
7092
7093 /* See what the driver can do */
7094 if (bs->drv->bdrv_recurse_can_replace) {
7095 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7096 }
7097
7098 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007099 filtered = bdrv_filter_bs(bs);
7100 if (filtered) {
7101 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007102 }
7103
7104 /* Safe default */
7105 return false;
7106}
7107
Max Reitz810803a2020-02-18 11:34:44 +01007108/*
7109 * Check whether the given @node_name can be replaced by a node that
7110 * has the same data as @parent_bs. If so, return @node_name's BDS;
7111 * NULL otherwise.
7112 *
7113 * @node_name must be a (recursive) *child of @parent_bs (or this
7114 * function will return NULL).
7115 *
7116 * The result (whether the node can be replaced or not) is only valid
7117 * for as long as no graph or permission changes occur.
7118 */
Wen Congyange12f3782015-07-17 10:12:22 +08007119BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7120 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007121{
7122 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007123 AioContext *aio_context;
7124
Benoît Canet09158f02014-06-27 18:25:25 +02007125 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007126 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007127 return NULL;
7128 }
7129
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007130 aio_context = bdrv_get_aio_context(to_replace_bs);
7131 aio_context_acquire(aio_context);
7132
Benoît Canet09158f02014-06-27 18:25:25 +02007133 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007134 to_replace_bs = NULL;
7135 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007136 }
7137
7138 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7139 * most non filter in order to prevent data corruption.
7140 * Another benefit is that this tests exclude backing files which are
7141 * blocked by the backing blockers.
7142 */
Max Reitz810803a2020-02-18 11:34:44 +01007143 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7144 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7145 "because it cannot be guaranteed that doing so would not "
7146 "lead to an abrupt change of visible data",
7147 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007148 to_replace_bs = NULL;
7149 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007150 }
7151
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007152out:
7153 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007154 return to_replace_bs;
7155}
Ming Lei448ad912014-07-04 18:04:33 +08007156
Max Reitz97e2f022019-02-01 20:29:27 +01007157/**
7158 * Iterates through the list of runtime option keys that are said to
7159 * be "strong" for a BDS. An option is called "strong" if it changes
7160 * a BDS's data. For example, the null block driver's "size" and
7161 * "read-zeroes" options are strong, but its "latency-ns" option is
7162 * not.
7163 *
7164 * If a key returned by this function ends with a dot, all options
7165 * starting with that prefix are strong.
7166 */
7167static const char *const *strong_options(BlockDriverState *bs,
7168 const char *const *curopt)
7169{
7170 static const char *const global_options[] = {
7171 "driver", "filename", NULL
7172 };
7173
7174 if (!curopt) {
7175 return &global_options[0];
7176 }
7177
7178 curopt++;
7179 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7180 curopt = bs->drv->strong_runtime_opts;
7181 }
7182
7183 return (curopt && *curopt) ? curopt : NULL;
7184}
7185
7186/**
7187 * Copies all strong runtime options from bs->options to the given
7188 * QDict. The set of strong option keys is determined by invoking
7189 * strong_options().
7190 *
7191 * Returns true iff any strong option was present in bs->options (and
7192 * thus copied to the target QDict) with the exception of "filename"
7193 * and "driver". The caller is expected to use this value to decide
7194 * whether the existence of strong options prevents the generation of
7195 * a plain filename.
7196 */
7197static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7198{
7199 bool found_any = false;
7200 const char *const *option_name = NULL;
7201
7202 if (!bs->drv) {
7203 return false;
7204 }
7205
7206 while ((option_name = strong_options(bs, option_name))) {
7207 bool option_given = false;
7208
7209 assert(strlen(*option_name) > 0);
7210 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7211 QObject *entry = qdict_get(bs->options, *option_name);
7212 if (!entry) {
7213 continue;
7214 }
7215
7216 qdict_put_obj(d, *option_name, qobject_ref(entry));
7217 option_given = true;
7218 } else {
7219 const QDictEntry *entry;
7220 for (entry = qdict_first(bs->options); entry;
7221 entry = qdict_next(bs->options, entry))
7222 {
7223 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7224 qdict_put_obj(d, qdict_entry_key(entry),
7225 qobject_ref(qdict_entry_value(entry)));
7226 option_given = true;
7227 }
7228 }
7229 }
7230
7231 /* While "driver" and "filename" need to be included in a JSON filename,
7232 * their existence does not prohibit generation of a plain filename. */
7233 if (!found_any && option_given &&
7234 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7235 {
7236 found_any = true;
7237 }
7238 }
7239
Max Reitz62a01a272019-02-01 20:29:34 +01007240 if (!qdict_haskey(d, "driver")) {
7241 /* Drivers created with bdrv_new_open_driver() may not have a
7242 * @driver option. Add it here. */
7243 qdict_put_str(d, "driver", bs->drv->format_name);
7244 }
7245
Max Reitz97e2f022019-02-01 20:29:27 +01007246 return found_any;
7247}
7248
Max Reitz90993622019-02-01 20:29:09 +01007249/* Note: This function may return false positives; it may return true
7250 * even if opening the backing file specified by bs's image header
7251 * would result in exactly bs->backing. */
Max Reitz0b877d02018-08-01 20:34:11 +02007252bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007253{
7254 if (bs->backing) {
7255 return strcmp(bs->auto_backing_file,
7256 bs->backing->bs->filename);
7257 } else {
7258 /* No backing BDS, so if the image header reports any backing
7259 * file, it must have been suppressed */
7260 return bs->auto_backing_file[0] != '\0';
7261 }
7262}
7263
Max Reitz91af7012014-07-18 20:24:56 +02007264/* Updates the following BDS fields:
7265 * - exact_filename: A filename which may be used for opening a block device
7266 * which (mostly) equals the given BDS (even without any
7267 * other options; so reading and writing must return the same
7268 * results, but caching etc. may be different)
7269 * - full_open_options: Options which, when given when opening a block device
7270 * (without a filename), result in a BDS (mostly)
7271 * equalling the given one
7272 * - filename: If exact_filename is set, it is copied here. Otherwise,
7273 * full_open_options is converted to a JSON object, prefixed with
7274 * "json:" (for use through the JSON pseudo protocol) and put here.
7275 */
7276void bdrv_refresh_filename(BlockDriverState *bs)
7277{
7278 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007279 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007280 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007281 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007282 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007283 bool generate_json_filename; /* Whether our default implementation should
7284 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007285
7286 if (!drv) {
7287 return;
7288 }
7289
Max Reitze24518e2019-02-01 20:29:06 +01007290 /* This BDS's file name may depend on any of its children's file names, so
7291 * refresh those first */
7292 QLIST_FOREACH(child, &bs->children, next) {
7293 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007294 }
7295
Max Reitzbb808d52019-02-01 20:29:07 +01007296 if (bs->implicit) {
7297 /* For implicit nodes, just copy everything from the single child */
7298 child = QLIST_FIRST(&bs->children);
7299 assert(QLIST_NEXT(child, next) == NULL);
7300
7301 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7302 child->bs->exact_filename);
7303 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7304
Pan Nengyuancb895612020-01-16 16:56:00 +08007305 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007306 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7307
7308 return;
7309 }
7310
Max Reitz90993622019-02-01 20:29:09 +01007311 backing_overridden = bdrv_backing_overridden(bs);
7312
7313 if (bs->open_flags & BDRV_O_NO_IO) {
7314 /* Without I/O, the backing file does not change anything.
7315 * Therefore, in such a case (primarily qemu-img), we can
7316 * pretend the backing file has not been overridden even if
7317 * it technically has been. */
7318 backing_overridden = false;
7319 }
7320
Max Reitz97e2f022019-02-01 20:29:27 +01007321 /* Gather the options QDict */
7322 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007323 generate_json_filename = append_strong_runtime_options(opts, bs);
7324 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007325
7326 if (drv->bdrv_gather_child_options) {
7327 /* Some block drivers may not want to present all of their children's
7328 * options, or name them differently from BdrvChild.name */
7329 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7330 } else {
7331 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007332 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007333 /* We can skip the backing BDS if it has not been overridden */
7334 continue;
7335 }
7336
7337 qdict_put(opts, child->name,
7338 qobject_ref(child->bs->full_open_options));
7339 }
7340
7341 if (backing_overridden && !bs->backing) {
7342 /* Force no backing file */
7343 qdict_put_null(opts, "backing");
7344 }
7345 }
7346
7347 qobject_unref(bs->full_open_options);
7348 bs->full_open_options = opts;
7349
Max Reitz52f72d62019-06-12 17:43:03 +02007350 primary_child_bs = bdrv_primary_bs(bs);
7351
Max Reitz998b3a12019-02-01 20:29:28 +01007352 if (drv->bdrv_refresh_filename) {
7353 /* Obsolete information is of no use here, so drop the old file name
7354 * information before refreshing it */
7355 bs->exact_filename[0] = '\0';
7356
7357 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007358 } else if (primary_child_bs) {
7359 /*
7360 * Try to reconstruct valid information from the underlying
7361 * file -- this only works for format nodes (filter nodes
7362 * cannot be probed and as such must be selected by the user
7363 * either through an options dict, or through a special
7364 * filename which the filter driver must construct in its
7365 * .bdrv_refresh_filename() implementation).
7366 */
Max Reitz998b3a12019-02-01 20:29:28 +01007367
7368 bs->exact_filename[0] = '\0';
7369
Max Reitzfb695c72019-02-01 20:29:29 +01007370 /*
7371 * We can use the underlying file's filename if:
7372 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007373 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007374 * - the file is a protocol BDS, and
7375 * - opening that file (as this BDS's format) will automatically create
7376 * the BDS tree we have right now, that is:
7377 * - the user did not significantly change this BDS's behavior with
7378 * some explicit (strong) options
7379 * - no non-file child of this BDS has been overridden by the user
7380 * Both of these conditions are represented by generate_json_filename.
7381 */
Max Reitz52f72d62019-06-12 17:43:03 +02007382 if (primary_child_bs->exact_filename[0] &&
7383 primary_child_bs->drv->bdrv_file_open &&
7384 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007385 {
Max Reitz52f72d62019-06-12 17:43:03 +02007386 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007387 }
7388 }
7389
Max Reitz91af7012014-07-18 20:24:56 +02007390 if (bs->exact_filename[0]) {
7391 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007392 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007393 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007394 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007395 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007396 /* Give user a hint if we truncated things. */
7397 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7398 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007399 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007400 }
7401}
Wen Congyange06018a2016-05-10 15:36:37 +08007402
Max Reitz1e89d0f2019-02-01 20:29:18 +01007403char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7404{
7405 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007406 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007407
7408 if (!drv) {
7409 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7410 return NULL;
7411 }
7412
7413 if (drv->bdrv_dirname) {
7414 return drv->bdrv_dirname(bs, errp);
7415 }
7416
Max Reitz52f72d62019-06-12 17:43:03 +02007417 child_bs = bdrv_primary_bs(bs);
7418 if (child_bs) {
7419 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007420 }
7421
7422 bdrv_refresh_filename(bs);
7423 if (bs->exact_filename[0] != '\0') {
7424 return path_combine(bs->exact_filename, "");
7425 }
7426
7427 error_setg(errp, "Cannot generate a base directory for %s nodes",
7428 drv->format_name);
7429 return NULL;
7430}
7431
Wen Congyange06018a2016-05-10 15:36:37 +08007432/*
7433 * Hot add/remove a BDS's child. So the user can take a child offline when
7434 * it is broken and take a new child online
7435 */
7436void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7437 Error **errp)
7438{
7439
7440 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7441 error_setg(errp, "The node %s does not support adding a child",
7442 bdrv_get_device_or_node_name(parent_bs));
7443 return;
7444 }
7445
7446 if (!QLIST_EMPTY(&child_bs->parents)) {
7447 error_setg(errp, "The node %s already has a parent",
7448 child_bs->node_name);
7449 return;
7450 }
7451
7452 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7453}
7454
7455void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7456{
7457 BdrvChild *tmp;
7458
7459 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7460 error_setg(errp, "The node %s does not support removing a child",
7461 bdrv_get_device_or_node_name(parent_bs));
7462 return;
7463 }
7464
7465 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7466 if (tmp == child) {
7467 break;
7468 }
7469 }
7470
7471 if (!tmp) {
7472 error_setg(errp, "The node %s does not have a child named %s",
7473 bdrv_get_device_or_node_name(parent_bs),
7474 bdrv_get_device_or_node_name(child->bs));
7475 return;
7476 }
7477
7478 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7479}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007480
7481int bdrv_make_empty(BdrvChild *c, Error **errp)
7482{
7483 BlockDriver *drv = c->bs->drv;
7484 int ret;
7485
7486 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7487
7488 if (!drv->bdrv_make_empty) {
7489 error_setg(errp, "%s does not support emptying nodes",
7490 drv->format_name);
7491 return -ENOTSUP;
7492 }
7493
7494 ret = drv->bdrv_make_empty(c->bs);
7495 if (ret < 0) {
7496 error_setg_errno(errp, -ret, "Failed to empty %s",
7497 c->bs->filename);
7498 return ret;
7499 }
7500
7501 return 0;
7502}
Max Reitz9a6fc882019-05-31 15:23:11 +02007503
7504/*
7505 * Return the child that @bs acts as an overlay for, and from which data may be
7506 * copied in COW or COR operations. Usually this is the backing file.
7507 */
7508BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7509{
7510 if (!bs || !bs->drv) {
7511 return NULL;
7512 }
7513
7514 if (bs->drv->is_filter) {
7515 return NULL;
7516 }
7517
7518 if (!bs->backing) {
7519 return NULL;
7520 }
7521
7522 assert(bs->backing->role & BDRV_CHILD_COW);
7523 return bs->backing;
7524}
7525
7526/*
7527 * If @bs acts as a filter for exactly one of its children, return
7528 * that child.
7529 */
7530BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7531{
7532 BdrvChild *c;
7533
7534 if (!bs || !bs->drv) {
7535 return NULL;
7536 }
7537
7538 if (!bs->drv->is_filter) {
7539 return NULL;
7540 }
7541
7542 /* Only one of @backing or @file may be used */
7543 assert(!(bs->backing && bs->file));
7544
7545 c = bs->backing ?: bs->file;
7546 if (!c) {
7547 return NULL;
7548 }
7549
7550 assert(c->role & BDRV_CHILD_FILTERED);
7551 return c;
7552}
7553
7554/*
7555 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7556 * whichever is non-NULL.
7557 *
7558 * Return NULL if both are NULL.
7559 */
7560BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7561{
7562 BdrvChild *cow_child = bdrv_cow_child(bs);
7563 BdrvChild *filter_child = bdrv_filter_child(bs);
7564
7565 /* Filter nodes cannot have COW backing files */
7566 assert(!(cow_child && filter_child));
7567
7568 return cow_child ?: filter_child;
7569}
7570
7571/*
7572 * Return the primary child of this node: For filters, that is the
7573 * filtered child. For other nodes, that is usually the child storing
7574 * metadata.
7575 * (A generally more helpful description is that this is (usually) the
7576 * child that has the same filename as @bs.)
7577 *
7578 * Drivers do not necessarily have a primary child; for example quorum
7579 * does not.
7580 */
7581BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7582{
7583 BdrvChild *c, *found = NULL;
7584
7585 QLIST_FOREACH(c, &bs->children, next) {
7586 if (c->role & BDRV_CHILD_PRIMARY) {
7587 assert(!found);
7588 found = c;
7589 }
7590 }
7591
7592 return found;
7593}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007594
7595static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7596 bool stop_on_explicit_filter)
7597{
7598 BdrvChild *c;
7599
7600 if (!bs) {
7601 return NULL;
7602 }
7603
7604 while (!(stop_on_explicit_filter && !bs->implicit)) {
7605 c = bdrv_filter_child(bs);
7606 if (!c) {
7607 /*
7608 * A filter that is embedded in a working block graph must
7609 * have a child. Assert this here so this function does
7610 * not return a filter node that is not expected by the
7611 * caller.
7612 */
7613 assert(!bs->drv || !bs->drv->is_filter);
7614 break;
7615 }
7616 bs = c->bs;
7617 }
7618 /*
7619 * Note that this treats nodes with bs->drv == NULL as not being
7620 * filters (bs->drv == NULL should be replaced by something else
7621 * anyway).
7622 * The advantage of this behavior is that this function will thus
7623 * always return a non-NULL value (given a non-NULL @bs).
7624 */
7625
7626 return bs;
7627}
7628
7629/*
7630 * Return the first BDS that has not been added implicitly or that
7631 * does not have a filtered child down the chain starting from @bs
7632 * (including @bs itself).
7633 */
7634BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7635{
7636 return bdrv_do_skip_filters(bs, true);
7637}
7638
7639/*
7640 * Return the first BDS that does not have a filtered child down the
7641 * chain starting from @bs (including @bs itself).
7642 */
7643BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7644{
7645 return bdrv_do_skip_filters(bs, false);
7646}
7647
7648/*
7649 * For a backing chain, return the first non-filter backing image of
7650 * the first non-filter image.
7651 */
7652BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7653{
7654 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7655}