blob: 38bd2ea32ed845dccd32581290a352c46d2e0f32 [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
ths5fafdf22007-09-16 21:08:06 +00005 *
bellardfc01f7e2003-06-30 10:03:06 +00006 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
Markus Armbrustere688df62018-02-01 12:18:31 +010024
Peter Maydelld38ea872016-01-29 17:50:05 +000025#include "qemu/osdep.h"
Daniel P. Berrange0ab8ed12017-01-25 16:14:15 +000026#include "block/trace.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010027#include "block/block_int.h"
28#include "block/blockjob.h"
Max Reitz0c9b70d2020-10-27 20:05:42 +010029#include "block/fuse.h"
Kevin Wolfcd7fca92016-07-06 11:22:39 +020030#include "block/nbd.h"
Max Reitz609f45e2018-06-14 21:14:28 +020031#include "block/qdict.h"
Markus Armbrusterd49b6832015-03-17 18:29:20 +010032#include "qemu/error-report.h"
Marc-André Lureau5e5733e2019-08-29 22:34:43 +040033#include "block/module_block.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020034#include "qemu/main-loop.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010035#include "qemu/module.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010036#include "qapi/error.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010037#include "qapi/qmp/qdict.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010038#include "qapi/qmp/qjson.h"
Max Reitze59a0cf2018-02-24 16:40:32 +010039#include "qapi/qmp/qnull.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010040#include "qapi/qmp/qstring.h"
Kevin Wolfe1d74bc2018-01-10 15:52:33 +010041#include "qapi/qobject-output-visitor.h"
42#include "qapi/qapi-visit-block-core.h"
Markus Armbrusterbfb197e2014-10-07 13:59:11 +020043#include "sysemu/block-backend.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010044#include "sysemu/sysemu.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>
blueswir1c5e97232009-03-07 20:06:23 +000057#ifndef __DragonFly__
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-Ogievskiyaa5a04c2021-04-28 18:17:47 +030087static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
88 BlockDriverState *child_bs,
89 const char *child_name,
90 const BdrvChildClass *child_class,
91 BdrvChildRole child_role,
92 BdrvChild **child,
93 Transaction *tran,
94 Error **errp);
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +030095static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
96 Transaction *tran);
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +030097
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +030098static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
99 BlockReopenQueue *queue,
100 Transaction *set_backings_tran, Error **errp);
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +0300101static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
102static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
103
Markus Armbrustereb852012009-10-27 18:41:44 +0100104/* If non-zero, use only whitelisted block drivers */
105static int use_bdrv_whitelist;
106
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000107#ifdef _WIN32
108static int is_windows_drive_prefix(const char *filename)
109{
110 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
111 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
112 filename[1] == ':');
113}
114
115int is_windows_drive(const char *filename)
116{
117 if (is_windows_drive_prefix(filename) &&
118 filename[2] == '\0')
119 return 1;
120 if (strstart(filename, "\\\\.\\", NULL) ||
121 strstart(filename, "//./", NULL))
122 return 1;
123 return 0;
124}
125#endif
126
Kevin Wolf339064d2013-11-28 10:23:32 +0100127size_t bdrv_opt_mem_align(BlockDriverState *bs)
128{
129 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300130 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800131 return MAX(4096, qemu_real_host_page_size);
Kevin Wolf339064d2013-11-28 10:23:32 +0100132 }
133
134 return bs->bl.opt_mem_alignment;
135}
136
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300137size_t bdrv_min_mem_align(BlockDriverState *bs)
138{
139 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300140 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800141 return MAX(4096, qemu_real_host_page_size);
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300142 }
143
144 return bs->bl.min_mem_alignment;
145}
146
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000147/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100148int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000149{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200150 const char *p;
151
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000152#ifdef _WIN32
153 if (is_windows_drive(path) ||
154 is_windows_drive_prefix(path)) {
155 return 0;
156 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200157 p = path + strcspn(path, ":/\\");
158#else
159 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000160#endif
161
Paolo Bonzini947995c2012-05-08 16:51:48 +0200162 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000163}
164
bellard83f64092006-08-01 16:21:11 +0000165int path_is_absolute(const char *path)
166{
bellard21664422007-01-07 18:22:37 +0000167#ifdef _WIN32
168 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200169 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000170 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200171 }
172 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000173#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200174 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000175#endif
bellard83f64092006-08-01 16:21:11 +0000176}
177
Max Reitz009b03a2019-02-01 20:29:13 +0100178/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000179 path to it by considering it is relative to base_path. URL are
180 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100181char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000182{
Max Reitz009b03a2019-02-01 20:29:13 +0100183 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000184 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100185 char *result;
bellard83f64092006-08-01 16:21:11 +0000186 int len;
187
bellard83f64092006-08-01 16:21:11 +0000188 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100189 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000190 }
Max Reitz009b03a2019-02-01 20:29:13 +0100191
192 if (path_has_protocol(base_path)) {
193 protocol_stripped = strchr(base_path, ':');
194 if (protocol_stripped) {
195 protocol_stripped++;
196 }
197 }
198 p = protocol_stripped ?: base_path;
199
200 p1 = strrchr(base_path, '/');
201#ifdef _WIN32
202 {
203 const char *p2;
204 p2 = strrchr(base_path, '\\');
205 if (!p1 || p2 > p1) {
206 p1 = p2;
207 }
208 }
209#endif
210 if (p1) {
211 p1++;
212 } else {
213 p1 = base_path;
214 }
215 if (p1 > p) {
216 p = p1;
217 }
218 len = p - base_path;
219
220 result = g_malloc(len + strlen(filename) + 1);
221 memcpy(result, base_path, len);
222 strcpy(result + len, filename);
223
224 return result;
225}
226
Max Reitz03c320d2017-05-22 21:52:16 +0200227/*
228 * Helper function for bdrv_parse_filename() implementations to remove optional
229 * protocol prefixes (especially "file:") from a filename and for putting the
230 * stripped filename into the options QDict if there is such a prefix.
231 */
232void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
233 QDict *options)
234{
235 if (strstart(filename, prefix, &filename)) {
236 /* Stripping the explicit protocol prefix may result in a protocol
237 * prefix being (wrongly) detected (if the filename contains a colon) */
238 if (path_has_protocol(filename)) {
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100239 GString *fat_filename;
Max Reitz03c320d2017-05-22 21:52:16 +0200240
241 /* This means there is some colon before the first slash; therefore,
242 * this cannot be an absolute path */
243 assert(!path_is_absolute(filename));
244
245 /* And we can thus fix the protocol detection issue by prefixing it
246 * by "./" */
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100247 fat_filename = g_string_new("./");
248 g_string_append(fat_filename, filename);
Max Reitz03c320d2017-05-22 21:52:16 +0200249
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100250 assert(!path_has_protocol(fat_filename->str));
Max Reitz03c320d2017-05-22 21:52:16 +0200251
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100252 qdict_put(options, "filename",
253 qstring_from_gstring(fat_filename));
Max Reitz03c320d2017-05-22 21:52:16 +0200254 } else {
255 /* If no protocol prefix was detected, we can use the shortened
256 * filename as-is */
257 qdict_put_str(options, "filename", filename);
258 }
259 }
260}
261
262
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200263/* Returns whether the image file is opened as read-only. Note that this can
264 * return false and writing to the image file is still not possible because the
265 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400266bool bdrv_is_read_only(BlockDriverState *bs)
267{
268 return bs->read_only;
269}
270
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200271int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
272 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400273{
Jeff Codye2b82472017-04-07 16:55:26 -0400274 /* Do not set read_only if copy_on_read is enabled */
275 if (bs->copy_on_read && read_only) {
276 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
277 bdrv_get_device_or_node_name(bs));
278 return -EINVAL;
279 }
280
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400281 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200282 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
283 !ignore_allow_rdw)
284 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400285 error_setg(errp, "Node '%s' is read only",
286 bdrv_get_device_or_node_name(bs));
287 return -EPERM;
288 }
289
Jeff Cody45803a02017-04-07 16:55:29 -0400290 return 0;
291}
292
Kevin Wolfeaa24102018-10-12 11:27:41 +0200293/*
294 * Called by a driver that can only provide a read-only image.
295 *
296 * Returns 0 if the node is already read-only or it could switch the node to
297 * read-only because BDRV_O_AUTO_RDONLY is set.
298 *
299 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
300 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
301 * is not NULL, it is used as the error message for the Error object.
302 */
303int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
304 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400305{
306 int ret = 0;
307
Kevin Wolfeaa24102018-10-12 11:27:41 +0200308 if (!(bs->open_flags & BDRV_O_RDWR)) {
309 return 0;
310 }
311 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
312 goto fail;
313 }
314
315 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400316 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200317 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400318 }
319
Kevin Wolfeaa24102018-10-12 11:27:41 +0200320 bs->read_only = true;
321 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200322
Jeff Codye2b82472017-04-07 16:55:26 -0400323 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200324
325fail:
326 error_setg(errp, "%s", errmsg ?: "Image is read-only");
327 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400328}
329
Max Reitz645ae7d2019-02-01 20:29:14 +0100330/*
331 * If @backing is empty, this function returns NULL without setting
332 * @errp. In all other cases, NULL will only be returned with @errp
333 * set.
334 *
335 * Therefore, a return value of NULL without @errp set means that
336 * there is no backing file; if @errp is set, there is one but its
337 * absolute filename cannot be generated.
338 */
339char *bdrv_get_full_backing_filename_from_filename(const char *backed,
340 const char *backing,
341 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100342{
Max Reitz645ae7d2019-02-01 20:29:14 +0100343 if (backing[0] == '\0') {
344 return NULL;
345 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
346 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100347 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
348 error_setg(errp, "Cannot use relative backing file names for '%s'",
349 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100350 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100351 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100352 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100353 }
354}
355
Max Reitz9f4793d2019-02-01 20:29:16 +0100356/*
357 * If @filename is empty or NULL, this function returns NULL without
358 * setting @errp. In all other cases, NULL will only be returned with
359 * @errp set.
360 */
361static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
362 const char *filename, Error **errp)
363{
Max Reitz8df68612019-02-01 20:29:23 +0100364 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100365
Max Reitz8df68612019-02-01 20:29:23 +0100366 if (!filename || filename[0] == '\0') {
367 return NULL;
368 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
369 return g_strdup(filename);
370 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100371
Max Reitz8df68612019-02-01 20:29:23 +0100372 dir = bdrv_dirname(relative_to, errp);
373 if (!dir) {
374 return NULL;
375 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100376
Max Reitz8df68612019-02-01 20:29:23 +0100377 full_name = g_strconcat(dir, filename, NULL);
378 g_free(dir);
379 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100380}
381
Max Reitz6b6833c2019-02-01 20:29:15 +0100382char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200383{
Max Reitz9f4793d2019-02-01 20:29:16 +0100384 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200385}
386
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100387void bdrv_register(BlockDriver *bdrv)
388{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100389 assert(bdrv->format_name);
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100390 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000391}
bellardb3380822004-03-14 21:38:54 +0000392
Markus Armbrustere4e99862014-10-07 13:59:03 +0200393BlockDriverState *bdrv_new(void)
394{
395 BlockDriverState *bs;
396 int i;
397
Markus Armbruster5839e532014-08-19 10:31:08 +0200398 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800399 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800400 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
401 QLIST_INIT(&bs->op_blockers[i]);
402 }
Stefan Hajnoczid616b222013-06-24 17:13:10 +0200403 notifier_with_return_list_init(&bs->before_write_notifiers);
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200404 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200405 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800406 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200407 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200408
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300409 qemu_co_queue_init(&bs->flush_queue);
410
Kevin Wolf0f122642018-03-28 18:29:18 +0200411 for (i = 0; i < bdrv_drain_all_count; i++) {
412 bdrv_drained_begin(bs);
413 }
414
Max Reitz2c1d04e2016-01-29 16:36:11 +0100415 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
416
bellardb3380822004-03-14 21:38:54 +0000417 return bs;
418}
419
Marc Mari88d88792016-08-12 09:27:03 -0400420static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000421{
422 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400423
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100424 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
425 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000426 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100427 }
bellardea2384d2004-08-01 21:59:26 +0000428 }
Marc Mari88d88792016-08-12 09:27:03 -0400429
bellardea2384d2004-08-01 21:59:26 +0000430 return NULL;
431}
432
Marc Mari88d88792016-08-12 09:27:03 -0400433BlockDriver *bdrv_find_format(const char *format_name)
434{
435 BlockDriver *drv1;
436 int i;
437
438 drv1 = bdrv_do_find_format(format_name);
439 if (drv1) {
440 return drv1;
441 }
442
443 /* The driver isn't registered, maybe we need to load a module */
444 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
445 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
446 block_module_load_one(block_driver_modules[i].library_name);
447 break;
448 }
449 }
450
451 return bdrv_do_find_format(format_name);
452}
453
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300454static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100455{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800456 static const char *whitelist_rw[] = {
457 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200458 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800459 };
460 static const char *whitelist_ro[] = {
461 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200462 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100463 };
464 const char **p;
465
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800466 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100467 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800468 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100469
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800470 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300471 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100472 return 1;
473 }
474 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800475 if (read_only) {
476 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300477 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800478 return 1;
479 }
480 }
481 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100482 return 0;
483}
484
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300485int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
486{
487 return bdrv_format_is_whitelisted(drv->format_name, read_only);
488}
489
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000490bool bdrv_uses_whitelist(void)
491{
492 return use_bdrv_whitelist;
493}
494
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800495typedef struct CreateCo {
496 BlockDriver *drv;
497 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800498 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800499 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200500 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800501} CreateCo;
502
503static void coroutine_fn bdrv_create_co_entry(void *opaque)
504{
Max Reitzcc84d902013-09-06 17:14:26 +0200505 Error *local_err = NULL;
506 int ret;
507
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800508 CreateCo *cco = opaque;
509 assert(cco->drv);
510
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200511 ret = cco->drv->bdrv_co_create_opts(cco->drv,
512 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300513 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200514 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800515}
516
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200517int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800518 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000519{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800520 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200521
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800522 Coroutine *co;
523 CreateCo cco = {
524 .drv = drv,
525 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800526 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800527 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200528 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800529 };
530
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100531 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200532 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300533 ret = -ENOTSUP;
534 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800535 }
536
537 if (qemu_in_coroutine()) {
538 /* Fast-path if already in coroutine context */
539 bdrv_create_co_entry(&cco);
540 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200541 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
542 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800543 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200544 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800545 }
546 }
547
548 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200549 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100550 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200551 error_propagate(errp, cco.err);
552 } else {
553 error_setg_errno(errp, -ret, "Could not create image");
554 }
555 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800556
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300557out:
558 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800559 return ret;
bellardea2384d2004-08-01 21:59:26 +0000560}
561
Max Reitzfd171462020-01-22 17:45:29 +0100562/**
563 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
564 * least the given @minimum_size.
565 *
566 * On success, return @blk's actual length.
567 * Otherwise, return -errno.
568 */
569static int64_t create_file_fallback_truncate(BlockBackend *blk,
570 int64_t minimum_size, Error **errp)
571{
572 Error *local_err = NULL;
573 int64_t size;
574 int ret;
575
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200576 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
577 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100578 if (ret < 0 && ret != -ENOTSUP) {
579 error_propagate(errp, local_err);
580 return ret;
581 }
582
583 size = blk_getlength(blk);
584 if (size < 0) {
585 error_free(local_err);
586 error_setg_errno(errp, -size,
587 "Failed to inquire the new image file's length");
588 return size;
589 }
590
591 if (size < minimum_size) {
592 /* Need to grow the image, but we failed to do that */
593 error_propagate(errp, local_err);
594 return -ENOTSUP;
595 }
596
597 error_free(local_err);
598 local_err = NULL;
599
600 return size;
601}
602
603/**
604 * Helper function for bdrv_create_file_fallback(): Zero the first
605 * sector to remove any potentially pre-existing image header.
606 */
607static int create_file_fallback_zero_first_sector(BlockBackend *blk,
608 int64_t current_size,
609 Error **errp)
610{
611 int64_t bytes_to_clear;
612 int ret;
613
614 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
615 if (bytes_to_clear) {
616 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
617 if (ret < 0) {
618 error_setg_errno(errp, -ret,
619 "Failed to clear the new image's first sector");
620 return ret;
621 }
622 }
623
624 return 0;
625}
626
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200627/**
628 * Simple implementation of bdrv_co_create_opts for protocol drivers
629 * which only support creation via opening a file
630 * (usually existing raw storage device)
631 */
632int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
633 const char *filename,
634 QemuOpts *opts,
635 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100636{
637 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100638 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100639 int64_t size = 0;
640 char *buf = NULL;
641 PreallocMode prealloc;
642 Error *local_err = NULL;
643 int ret;
644
645 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
646 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
647 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
648 PREALLOC_MODE_OFF, &local_err);
649 g_free(buf);
650 if (local_err) {
651 error_propagate(errp, local_err);
652 return -EINVAL;
653 }
654
655 if (prealloc != PREALLOC_MODE_OFF) {
656 error_setg(errp, "Unsupported preallocation mode '%s'",
657 PreallocMode_str(prealloc));
658 return -ENOTSUP;
659 }
660
Max Reitzeeea1fa2020-02-25 16:56:18 +0100661 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100662 qdict_put_str(options, "driver", drv->format_name);
663
664 blk = blk_new_open(filename, NULL, options,
665 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
666 if (!blk) {
667 error_prepend(errp, "Protocol driver '%s' does not support image "
668 "creation, and opening the image failed: ",
669 drv->format_name);
670 return -EINVAL;
671 }
672
673 size = create_file_fallback_truncate(blk, size, errp);
674 if (size < 0) {
675 ret = size;
676 goto out;
677 }
678
679 ret = create_file_fallback_zero_first_sector(blk, size, errp);
680 if (ret < 0) {
681 goto out;
682 }
683
684 ret = 0;
685out:
686 blk_unref(blk);
687 return ret;
688}
689
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800690int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200691{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100692 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200693 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100694 QDict *qdict;
695 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200696
Max Reitzb65a5e12015-02-05 13:58:12 -0500697 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200698 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000699 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200700 }
701
Stefano Garzarella729222a2021-03-08 17:12:32 +0100702 if (!drv->create_opts) {
703 error_setg(errp, "Driver '%s' does not support image creation",
704 drv->format_name);
705 return -ENOTSUP;
706 }
707
708 /*
709 * 'opts' contains a QemuOptsList with a combination of format and protocol
710 * default values.
711 *
712 * The format properly removes its options, but the default values remain
713 * in 'opts->list'. So if the protocol has options with the same name
714 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
715 * of the format, since for overlapping options, the format wins.
716 *
717 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
718 * only the set options, and then convert it back to QemuOpts, using the
719 * create_opts of the protocol. So the new QemuOpts, will contain only the
720 * protocol defaults.
721 */
722 qdict = qemu_opts_to_qdict(opts, NULL);
723 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
724 if (protocol_opts == NULL) {
725 ret = -EINVAL;
726 goto out;
727 }
728
729 ret = bdrv_create(drv, filename, protocol_opts, errp);
730out:
731 qemu_opts_del(protocol_opts);
732 qobject_unref(qdict);
733 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200734}
735
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300736int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
737{
738 Error *local_err = NULL;
739 int ret;
740
741 assert(bs != NULL);
742
743 if (!bs->drv) {
744 error_setg(errp, "Block node '%s' is not opened", bs->filename);
745 return -ENOMEDIUM;
746 }
747
748 if (!bs->drv->bdrv_co_delete_file) {
749 error_setg(errp, "Driver '%s' does not support image deletion",
750 bs->drv->format_name);
751 return -ENOTSUP;
752 }
753
754 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
755 if (ret < 0) {
756 error_propagate(errp, local_err);
757 }
758
759 return ret;
760}
761
Maxim Levitskya890f082020-12-17 19:09:03 +0200762void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
763{
764 Error *local_err = NULL;
765 int ret;
766
767 if (!bs) {
768 return;
769 }
770
771 ret = bdrv_co_delete_file(bs, &local_err);
772 /*
773 * ENOTSUP will happen if the block driver doesn't support
774 * the 'bdrv_co_delete_file' interface. This is a predictable
775 * scenario and shouldn't be reported back to the user.
776 */
777 if (ret == -ENOTSUP) {
778 error_free(local_err);
779 } else if (ret < 0) {
780 error_report_err(local_err);
781 }
782}
783
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100784/**
785 * Try to get @bs's logical and physical block size.
786 * On success, store them in @bsz struct and return 0.
787 * On failure return -errno.
788 * @bs must not be empty.
789 */
790int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
791{
792 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200793 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100794
795 if (drv && drv->bdrv_probe_blocksizes) {
796 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200797 } else if (filtered) {
798 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100799 }
800
801 return -ENOTSUP;
802}
803
804/**
805 * Try to get @bs's geometry (cyls, heads, sectors).
806 * On success, store them in @geo struct and return 0.
807 * On failure return -errno.
808 * @bs must not be empty.
809 */
810int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
811{
812 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200813 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100814
815 if (drv && drv->bdrv_probe_geometry) {
816 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200817 } else if (filtered) {
818 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100819 }
820
821 return -ENOTSUP;
822}
823
Jim Meyeringeba25052012-05-28 09:27:54 +0200824/*
825 * Create a uniquely-named empty temporary file.
826 * Return 0 upon success, otherwise a negative errno value.
827 */
828int get_tmp_filename(char *filename, int size)
829{
bellardd5249392004-08-03 21:14:23 +0000830#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000831 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200832 /* GetTempFileName requires that its output buffer (4th param)
833 have length MAX_PATH or greater. */
834 assert(size >= MAX_PATH);
835 return (GetTempPath(MAX_PATH, temp_dir)
836 && GetTempFileName(temp_dir, "qem", 0, filename)
837 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000838#else
bellardea2384d2004-08-01 21:59:26 +0000839 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000840 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000841 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530842 if (!tmpdir) {
843 tmpdir = "/var/tmp";
844 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200845 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
846 return -EOVERFLOW;
847 }
bellardea2384d2004-08-01 21:59:26 +0000848 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800849 if (fd < 0) {
850 return -errno;
851 }
852 if (close(fd) != 0) {
853 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200854 return -errno;
855 }
856 return 0;
bellardd5249392004-08-03 21:14:23 +0000857#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200858}
bellardea2384d2004-08-01 21:59:26 +0000859
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200860/*
861 * Detect host devices. By convention, /dev/cdrom[N] is always
862 * recognized as a host CDROM.
863 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200864static BlockDriver *find_hdev_driver(const char *filename)
865{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200866 int score_max = 0, score;
867 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200868
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100869 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200870 if (d->bdrv_probe_device) {
871 score = d->bdrv_probe_device(filename);
872 if (score > score_max) {
873 score_max = score;
874 drv = d;
875 }
876 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200877 }
878
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200879 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200880}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200881
Marc Mari88d88792016-08-12 09:27:03 -0400882static BlockDriver *bdrv_do_find_protocol(const char *protocol)
883{
884 BlockDriver *drv1;
885
886 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
887 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
888 return drv1;
889 }
890 }
891
892 return NULL;
893}
894
Kevin Wolf98289622013-07-10 15:47:39 +0200895BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500896 bool allow_protocol_prefix,
897 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200898{
899 BlockDriver *drv1;
900 char protocol[128];
901 int len;
902 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400903 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200904
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200905 /* TODO Drivers without bdrv_file_open must be specified explicitly */
906
Christoph Hellwig39508e72010-06-23 12:25:17 +0200907 /*
908 * XXX(hch): we really should not let host device detection
909 * override an explicit protocol specification, but moving this
910 * later breaks access to device names with colons in them.
911 * Thanks to the brain-dead persistent naming schemes on udev-
912 * based Linux systems those actually are quite common.
913 */
914 drv1 = find_hdev_driver(filename);
915 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200916 return drv1;
917 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200918
Kevin Wolf98289622013-07-10 15:47:39 +0200919 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100920 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200921 }
Kevin Wolf98289622013-07-10 15:47:39 +0200922
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000923 p = strchr(filename, ':');
924 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200925 len = p - filename;
926 if (len > sizeof(protocol) - 1)
927 len = sizeof(protocol) - 1;
928 memcpy(protocol, filename, len);
929 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400930
931 drv1 = bdrv_do_find_protocol(protocol);
932 if (drv1) {
933 return drv1;
934 }
935
936 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
937 if (block_driver_modules[i].protocol_name &&
938 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
939 block_module_load_one(block_driver_modules[i].library_name);
940 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200941 }
942 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500943
Marc Mari88d88792016-08-12 09:27:03 -0400944 drv1 = bdrv_do_find_protocol(protocol);
945 if (!drv1) {
946 error_setg(errp, "Unknown protocol '%s'", protocol);
947 }
948 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200949}
950
Markus Armbrusterc6684242014-11-20 16:27:10 +0100951/*
952 * Guess image format by probing its contents.
953 * This is not a good idea when your image is raw (CVE-2008-2004), but
954 * we do it anyway for backward compatibility.
955 *
956 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100957 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
958 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100959 * @filename is its filename.
960 *
961 * For all block drivers, call the bdrv_probe() method to get its
962 * probing score.
963 * Return the first block driver with the highest probing score.
964 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100965BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
966 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100967{
968 int score_max = 0, score;
969 BlockDriver *drv = NULL, *d;
970
971 QLIST_FOREACH(d, &bdrv_drivers, list) {
972 if (d->bdrv_probe) {
973 score = d->bdrv_probe(buf, buf_size, filename);
974 if (score > score_max) {
975 score_max = score;
976 drv = d;
977 }
978 }
979 }
980
981 return drv;
982}
983
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100984static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200985 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000986{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100987 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100988 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100989 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700990
Kevin Wolf08a00552010-06-01 18:37:31 +0200991 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100992 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100993 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200994 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700995 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700996
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100997 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +0000998 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200999 error_setg_errno(errp, -ret, "Could not read image for determining its "
1000 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +02001001 *pdrv = NULL;
1002 return ret;
bellard83f64092006-08-01 16:21:11 +00001003 }
1004
Markus Armbrusterc6684242014-11-20 16:27:10 +01001005 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +02001006 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +02001007 error_setg(errp, "Could not determine image format: No compatible "
1008 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +02001009 ret = -ENOENT;
1010 }
1011 *pdrv = drv;
1012 return ret;
bellardea2384d2004-08-01 21:59:26 +00001013}
1014
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001015/**
1016 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001017 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001018 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001019int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001020{
1021 BlockDriver *drv = bs->drv;
1022
Max Reitzd470ad42017-11-10 21:31:09 +01001023 if (!drv) {
1024 return -ENOMEDIUM;
1025 }
1026
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001027 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001028 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001029 return 0;
1030
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001031 /* query actual device if possible, otherwise just trust the hint */
1032 if (drv->bdrv_getlength) {
1033 int64_t length = drv->bdrv_getlength(bs);
1034 if (length < 0) {
1035 return length;
1036 }
Fam Zheng7e382002013-11-06 19:48:06 +08001037 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001038 }
1039
1040 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001041
1042 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1043 return -EFBIG;
1044 }
1045
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001046 return 0;
1047}
1048
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001049/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001050 * Combines a QDict of new block driver @options with any missing options taken
1051 * from @old_options, so that leaving out an option defaults to its old value.
1052 */
1053static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1054 QDict *old_options)
1055{
1056 if (bs->drv && bs->drv->bdrv_join_options) {
1057 bs->drv->bdrv_join_options(options, old_options);
1058 } else {
1059 qdict_join(options, old_options, false);
1060 }
1061}
1062
Alberto Garcia543770b2018-09-06 12:37:09 +03001063static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1064 int open_flags,
1065 Error **errp)
1066{
1067 Error *local_err = NULL;
1068 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1069 BlockdevDetectZeroesOptions detect_zeroes =
1070 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1071 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1072 g_free(value);
1073 if (local_err) {
1074 error_propagate(errp, local_err);
1075 return detect_zeroes;
1076 }
1077
1078 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1079 !(open_flags & BDRV_O_UNMAP))
1080 {
1081 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1082 "without setting discard operation to unmap");
1083 }
1084
1085 return detect_zeroes;
1086}
1087
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001088/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001089 * Set open flags for aio engine
1090 *
1091 * Return 0 on success, -1 if the engine specified is invalid
1092 */
1093int bdrv_parse_aio(const char *mode, int *flags)
1094{
1095 if (!strcmp(mode, "threads")) {
1096 /* do nothing, default */
1097 } else if (!strcmp(mode, "native")) {
1098 *flags |= BDRV_O_NATIVE_AIO;
1099#ifdef CONFIG_LINUX_IO_URING
1100 } else if (!strcmp(mode, "io_uring")) {
1101 *flags |= BDRV_O_IO_URING;
1102#endif
1103 } else {
1104 return -1;
1105 }
1106
1107 return 0;
1108}
1109
1110/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001111 * Set open flags for a given discard mode
1112 *
1113 * Return 0 on success, -1 if the discard mode was invalid.
1114 */
1115int bdrv_parse_discard_flags(const char *mode, int *flags)
1116{
1117 *flags &= ~BDRV_O_UNMAP;
1118
1119 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1120 /* do nothing */
1121 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1122 *flags |= BDRV_O_UNMAP;
1123 } else {
1124 return -1;
1125 }
1126
1127 return 0;
1128}
1129
1130/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001131 * Set open flags for a given cache mode
1132 *
1133 * Return 0 on success, -1 if the cache mode was invalid.
1134 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001135int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001136{
1137 *flags &= ~BDRV_O_CACHE_MASK;
1138
1139 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001140 *writethrough = false;
1141 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001142 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001143 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001144 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001145 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001146 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001147 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001148 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001149 *flags |= BDRV_O_NO_FLUSH;
1150 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001151 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001152 } else {
1153 return -1;
1154 }
1155
1156 return 0;
1157}
1158
Kevin Wolfb5411552017-01-17 15:56:16 +01001159static char *bdrv_child_get_parent_desc(BdrvChild *c)
1160{
1161 BlockDriverState *parent = c->opaque;
1162 return g_strdup(bdrv_get_device_or_node_name(parent));
1163}
1164
Kevin Wolf20018e12016-05-23 18:46:59 +02001165static void bdrv_child_cb_drained_begin(BdrvChild *child)
1166{
1167 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001168 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001169}
1170
Kevin Wolf89bd0302018-03-22 14:11:20 +01001171static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1172{
1173 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001174 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001175}
1176
Max Reitze037c092019-07-19 11:26:14 +02001177static void bdrv_child_cb_drained_end(BdrvChild *child,
1178 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001179{
1180 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001181 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001182}
1183
Kevin Wolf38701b62017-05-04 18:52:39 +02001184static int bdrv_child_cb_inactivate(BdrvChild *child)
1185{
1186 BlockDriverState *bs = child->opaque;
1187 assert(bs->open_flags & BDRV_O_INACTIVE);
1188 return 0;
1189}
1190
Kevin Wolf5d231842019-05-06 19:17:56 +02001191static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1192 GSList **ignore, Error **errp)
1193{
1194 BlockDriverState *bs = child->opaque;
1195 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1196}
1197
Kevin Wolf53a7d042019-05-06 19:17:59 +02001198static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1199 GSList **ignore)
1200{
1201 BlockDriverState *bs = child->opaque;
1202 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1203}
1204
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001205/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001206 * Returns the options and flags that a temporary snapshot should get, based on
1207 * the originally requested flags (the originally requested image will have
1208 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001209 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001210static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1211 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001212{
Kevin Wolf73176be2016-03-07 13:02:15 +01001213 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1214
1215 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001216 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1217 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001218
Kevin Wolf3f486862019-04-04 17:04:43 +02001219 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001220 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001221 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001222
Kevin Wolf41869042016-06-16 12:59:30 +02001223 /* aio=native doesn't work for cache.direct=off, so disable it for the
1224 * temporary snapshot */
1225 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001226}
1227
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001228static void bdrv_backing_attach(BdrvChild *c)
1229{
1230 BlockDriverState *parent = c->opaque;
1231 BlockDriverState *backing_hd = c->bs;
1232
1233 assert(!parent->backing_blocker);
1234 error_setg(&parent->backing_blocker,
1235 "node is used as backing hd of '%s'",
1236 bdrv_get_device_or_node_name(parent));
1237
Max Reitzf30c66b2019-02-01 20:29:05 +01001238 bdrv_refresh_filename(backing_hd);
1239
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001240 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001241
1242 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1243 /* Otherwise we won't be able to commit or stream */
1244 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1245 parent->backing_blocker);
1246 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1247 parent->backing_blocker);
1248 /*
1249 * We do backup in 3 ways:
1250 * 1. drive backup
1251 * The target bs is new opened, and the source is top BDS
1252 * 2. blockdev backup
1253 * Both the source and the target are top BDSes.
1254 * 3. internal backup(used for block replication)
1255 * Both the source and the target are backing file
1256 *
1257 * In case 1 and 2, neither the source nor the target is the backing file.
1258 * In case 3, we will block the top BDS, so there is only one block job
1259 * for the top BDS and its backing chain.
1260 */
1261 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1262 parent->backing_blocker);
1263 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1264 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001265}
Kevin Wolfd736f112017-12-18 16:05:48 +01001266
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001267static void bdrv_backing_detach(BdrvChild *c)
1268{
1269 BlockDriverState *parent = c->opaque;
1270
1271 assert(parent->backing_blocker);
1272 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1273 error_free(parent->backing_blocker);
1274 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001275}
Kevin Wolfd736f112017-12-18 16:05:48 +01001276
Kevin Wolf6858eba2017-06-29 19:32:21 +02001277static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1278 const char *filename, Error **errp)
1279{
1280 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001281 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001282 int ret;
1283
Alberto Garciae94d3db2018-11-12 16:00:34 +02001284 if (read_only) {
1285 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001286 if (ret < 0) {
1287 return ret;
1288 }
1289 }
1290
Kevin Wolf6858eba2017-06-29 19:32:21 +02001291 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001292 base->drv ? base->drv->format_name : "",
1293 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001294 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001295 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001296 }
1297
Alberto Garciae94d3db2018-11-12 16:00:34 +02001298 if (read_only) {
1299 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001300 }
1301
Kevin Wolf6858eba2017-06-29 19:32:21 +02001302 return ret;
1303}
1304
Max Reitzfae8bd32020-05-13 13:05:20 +02001305/*
1306 * Returns the options and flags that a generic child of a BDS should
1307 * get, based on the given options and flags for the parent BDS.
1308 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001309static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1310 int *child_flags, QDict *child_options,
1311 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001312{
1313 int flags = parent_flags;
1314
1315 /*
1316 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1317 * Generally, the question to answer is: Should this child be
1318 * format-probed by default?
1319 */
1320
1321 /*
1322 * Pure and non-filtered data children of non-format nodes should
1323 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1324 * set). This only affects a very limited set of drivers (namely
1325 * quorum and blkverify when this comment was written).
1326 * Force-clear BDRV_O_PROTOCOL then.
1327 */
1328 if (!parent_is_format &&
1329 (role & BDRV_CHILD_DATA) &&
1330 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1331 {
1332 flags &= ~BDRV_O_PROTOCOL;
1333 }
1334
1335 /*
1336 * All children of format nodes (except for COW children) and all
1337 * metadata children in general should never be format-probed.
1338 * Force-set BDRV_O_PROTOCOL then.
1339 */
1340 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1341 (role & BDRV_CHILD_METADATA))
1342 {
1343 flags |= BDRV_O_PROTOCOL;
1344 }
1345
1346 /*
1347 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1348 * the parent.
1349 */
1350 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1351 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1352 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1353
1354 if (role & BDRV_CHILD_COW) {
1355 /* backing files are opened read-only by default */
1356 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1357 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1358 } else {
1359 /* Inherit the read-only option from the parent if it's not set */
1360 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1361 qdict_copy_default(child_options, parent_options,
1362 BDRV_OPT_AUTO_READ_ONLY);
1363 }
1364
1365 /*
1366 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1367 * can default to enable it on lower layers regardless of the
1368 * parent option.
1369 */
1370 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1371
1372 /* Clear flags that only apply to the top layer */
1373 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1374
1375 if (role & BDRV_CHILD_METADATA) {
1376 flags &= ~BDRV_O_NO_IO;
1377 }
1378 if (role & BDRV_CHILD_COW) {
1379 flags &= ~BDRV_O_TEMPORARY;
1380 }
1381
1382 *child_flags = flags;
1383}
1384
Max Reitzca2f1232020-05-13 13:05:22 +02001385static void bdrv_child_cb_attach(BdrvChild *child)
1386{
1387 BlockDriverState *bs = child->opaque;
1388
1389 if (child->role & BDRV_CHILD_COW) {
1390 bdrv_backing_attach(child);
1391 }
1392
1393 bdrv_apply_subtree_drain(child, bs);
1394}
1395
Max Reitz48e08282020-05-13 13:05:23 +02001396static void bdrv_child_cb_detach(BdrvChild *child)
1397{
1398 BlockDriverState *bs = child->opaque;
1399
1400 if (child->role & BDRV_CHILD_COW) {
1401 bdrv_backing_detach(child);
1402 }
1403
1404 bdrv_unapply_subtree_drain(child, bs);
1405}
1406
Max Reitz43483552020-05-13 13:05:24 +02001407static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1408 const char *filename, Error **errp)
1409{
1410 if (c->role & BDRV_CHILD_COW) {
1411 return bdrv_backing_update_filename(c, base, filename, errp);
1412 }
1413 return 0;
1414}
1415
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001416static AioContext *bdrv_child_cb_get_parent_aio_context(BdrvChild *c)
1417{
1418 BlockDriverState *bs = c->opaque;
1419
1420 return bdrv_get_aio_context(bs);
1421}
1422
Max Reitz43483552020-05-13 13:05:24 +02001423const BdrvChildClass child_of_bds = {
1424 .parent_is_bds = true,
1425 .get_parent_desc = bdrv_child_get_parent_desc,
1426 .inherit_options = bdrv_inherited_options,
1427 .drained_begin = bdrv_child_cb_drained_begin,
1428 .drained_poll = bdrv_child_cb_drained_poll,
1429 .drained_end = bdrv_child_cb_drained_end,
1430 .attach = bdrv_child_cb_attach,
1431 .detach = bdrv_child_cb_detach,
1432 .inactivate = bdrv_child_cb_inactivate,
1433 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1434 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1435 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001436 .get_parent_aio_context = bdrv_child_cb_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001437};
1438
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001439AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1440{
1441 return c->klass->get_parent_aio_context(c);
1442}
1443
Kevin Wolf7b272452012-11-12 17:05:39 +01001444static int bdrv_open_flags(BlockDriverState *bs, int flags)
1445{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001446 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001447
1448 /*
1449 * Clear flags that are internal to the block layer before opening the
1450 * image.
1451 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001452 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001453
Kevin Wolf7b272452012-11-12 17:05:39 +01001454 return open_flags;
1455}
1456
Kevin Wolf91a097e2015-05-08 17:49:53 +02001457static void update_flags_from_options(int *flags, QemuOpts *opts)
1458{
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001459 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001460
Alberto Garcia57f9db92018-09-06 12:37:06 +03001461 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001462 *flags |= BDRV_O_NO_FLUSH;
1463 }
1464
Alberto Garcia57f9db92018-09-06 12:37:06 +03001465 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001466 *flags |= BDRV_O_NOCACHE;
1467 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001468
Alberto Garcia57f9db92018-09-06 12:37:06 +03001469 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001470 *flags |= BDRV_O_RDWR;
1471 }
1472
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001473 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1474 *flags |= BDRV_O_AUTO_RDONLY;
1475 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001476}
1477
1478static void update_options_from_flags(QDict *options, int flags)
1479{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001480 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001481 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001482 }
1483 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001484 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1485 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001486 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001487 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001488 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001489 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001490 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1491 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1492 flags & BDRV_O_AUTO_RDONLY);
1493 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001494}
1495
Kevin Wolf636ea372014-01-24 14:11:52 +01001496static void bdrv_assign_node_name(BlockDriverState *bs,
1497 const char *node_name,
1498 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001499{
Jeff Cody15489c72015-10-12 19:36:50 -04001500 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001501
Jeff Cody15489c72015-10-12 19:36:50 -04001502 if (!node_name) {
1503 node_name = gen_node_name = id_generate(ID_BLOCK);
1504 } else if (!id_wellformed(node_name)) {
1505 /*
1506 * Check for empty string or invalid characters, but not if it is
1507 * generated (generated names use characters not available to the user)
1508 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001509 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001510 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001511 }
1512
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001513 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001514 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001515 error_setg(errp, "node-name=%s is conflicting with a device id",
1516 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001517 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001518 }
1519
Benoît Canet6913c0c2014-01-23 21:31:33 +01001520 /* takes care of avoiding duplicates node names */
1521 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001522 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001523 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001524 }
1525
Kevin Wolf824808d2018-07-04 13:28:29 +02001526 /* Make sure that the node name isn't truncated */
1527 if (strlen(node_name) >= sizeof(bs->node_name)) {
1528 error_setg(errp, "Node name too long");
1529 goto out;
1530 }
1531
Benoît Canet6913c0c2014-01-23 21:31:33 +01001532 /* copy node name into the bs and insert it into the graph list */
1533 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1534 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001535out:
1536 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001537}
1538
Kevin Wolf01a56502017-01-18 15:51:56 +01001539static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1540 const char *node_name, QDict *options,
1541 int open_flags, Error **errp)
1542{
1543 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001544 int i, ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001545
1546 bdrv_assign_node_name(bs, node_name, &local_err);
1547 if (local_err) {
1548 error_propagate(errp, local_err);
1549 return -EINVAL;
1550 }
1551
1552 bs->drv = drv;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001553 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Kevin Wolf01a56502017-01-18 15:51:56 +01001554 bs->opaque = g_malloc0(drv->instance_size);
1555
1556 if (drv->bdrv_file_open) {
1557 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1558 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001559 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001560 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001561 } else {
1562 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001563 }
1564
1565 if (ret < 0) {
1566 if (local_err) {
1567 error_propagate(errp, local_err);
1568 } else if (bs->filename[0]) {
1569 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1570 } else {
1571 error_setg_errno(errp, -ret, "Could not open image");
1572 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001573 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001574 }
1575
1576 ret = refresh_total_sectors(bs, bs->total_sectors);
1577 if (ret < 0) {
1578 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001579 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001580 }
1581
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03001582 bdrv_refresh_limits(bs, NULL, &local_err);
Kevin Wolf01a56502017-01-18 15:51:56 +01001583 if (local_err) {
1584 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001585 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001586 }
1587
1588 assert(bdrv_opt_mem_align(bs) != 0);
1589 assert(bdrv_min_mem_align(bs) != 0);
1590 assert(is_power_of_2(bs->bl.request_alignment));
1591
Kevin Wolf0f122642018-03-28 18:29:18 +02001592 for (i = 0; i < bs->quiesce_counter; i++) {
1593 if (drv->bdrv_co_drain_begin) {
1594 drv->bdrv_co_drain_begin(bs);
1595 }
1596 }
1597
Kevin Wolf01a56502017-01-18 15:51:56 +01001598 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001599open_failed:
1600 bs->drv = NULL;
1601 if (bs->file != NULL) {
1602 bdrv_unref_child(bs, bs->file);
1603 bs->file = NULL;
1604 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001605 g_free(bs->opaque);
1606 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001607 return ret;
1608}
1609
Kevin Wolf680c7f92017-01-18 17:16:41 +01001610BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1611 int flags, Error **errp)
1612{
1613 BlockDriverState *bs;
1614 int ret;
1615
1616 bs = bdrv_new();
1617 bs->open_flags = flags;
1618 bs->explicit_options = qdict_new();
1619 bs->options = qdict_new();
1620 bs->opaque = NULL;
1621
1622 update_options_from_flags(bs->options, flags);
1623
1624 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1625 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001626 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001627 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001628 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001629 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001630 bdrv_unref(bs);
1631 return NULL;
1632 }
1633
1634 return bs;
1635}
1636
Kevin Wolfc5f30142016-10-06 11:33:17 +02001637QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001638 .name = "bdrv_common",
1639 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1640 .desc = {
1641 {
1642 .name = "node-name",
1643 .type = QEMU_OPT_STRING,
1644 .help = "Node name of the block device node",
1645 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001646 {
1647 .name = "driver",
1648 .type = QEMU_OPT_STRING,
1649 .help = "Block driver to use for the node",
1650 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001651 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001652 .name = BDRV_OPT_CACHE_DIRECT,
1653 .type = QEMU_OPT_BOOL,
1654 .help = "Bypass software writeback cache on the host",
1655 },
1656 {
1657 .name = BDRV_OPT_CACHE_NO_FLUSH,
1658 .type = QEMU_OPT_BOOL,
1659 .help = "Ignore flush requests",
1660 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001661 {
1662 .name = BDRV_OPT_READ_ONLY,
1663 .type = QEMU_OPT_BOOL,
1664 .help = "Node is opened in read-only mode",
1665 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001666 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001667 .name = BDRV_OPT_AUTO_READ_ONLY,
1668 .type = QEMU_OPT_BOOL,
1669 .help = "Node can become read-only if opening read-write fails",
1670 },
1671 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001672 .name = "detect-zeroes",
1673 .type = QEMU_OPT_STRING,
1674 .help = "try to optimize zero writes (off, on, unmap)",
1675 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001676 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001677 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001678 .type = QEMU_OPT_STRING,
1679 .help = "discard operation (ignore/off, unmap/on)",
1680 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001681 {
1682 .name = BDRV_OPT_FORCE_SHARE,
1683 .type = QEMU_OPT_BOOL,
1684 .help = "always accept other writers (default: off)",
1685 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001686 { /* end of list */ }
1687 },
1688};
1689
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001690QemuOptsList bdrv_create_opts_simple = {
1691 .name = "simple-create-opts",
1692 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001693 .desc = {
1694 {
1695 .name = BLOCK_OPT_SIZE,
1696 .type = QEMU_OPT_SIZE,
1697 .help = "Virtual disk size"
1698 },
1699 {
1700 .name = BLOCK_OPT_PREALLOC,
1701 .type = QEMU_OPT_STRING,
1702 .help = "Preallocation mode (allowed values: off)"
1703 },
1704 { /* end of list */ }
1705 }
1706};
1707
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001708/*
Kevin Wolf57915332010-04-14 15:24:50 +02001709 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001710 *
1711 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001712 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001713static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001714 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001715{
1716 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001717 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001718 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001719 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001720 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001721 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001722 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001723 Error *local_err = NULL;
Kevin Wolf57915332010-04-14 15:24:50 +02001724
Paolo Bonzini64058752012-05-08 16:51:49 +02001725 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001726 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001727
Kevin Wolf62392eb2015-04-24 16:38:02 +02001728 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001729 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001730 ret = -EINVAL;
1731 goto fail_opts;
1732 }
1733
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001734 update_flags_from_options(&bs->open_flags, opts);
1735
Kevin Wolf62392eb2015-04-24 16:38:02 +02001736 driver_name = qemu_opt_get(opts, "driver");
1737 drv = bdrv_find_format(driver_name);
1738 assert(drv != NULL);
1739
Fam Zheng5a9347c2017-05-03 00:35:37 +08001740 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1741
1742 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1743 error_setg(errp,
1744 BDRV_OPT_FORCE_SHARE
1745 "=on can only be used with read-only images");
1746 ret = -EINVAL;
1747 goto fail_opts;
1748 }
1749
Kevin Wolf45673672013-04-22 17:48:40 +02001750 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001751 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001752 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001753 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001754 /*
1755 * Caution: while qdict_get_try_str() is fine, getting
1756 * non-string types would require more care. When @options
1757 * come from -blockdev or blockdev_add, its members are typed
1758 * according to the QAPI schema, but when they come from
1759 * -drive, they're all QString.
1760 */
Kevin Wolf45673672013-04-22 17:48:40 +02001761 filename = qdict_get_try_str(options, "filename");
1762 }
1763
Max Reitz4a008242017-04-13 18:06:24 +02001764 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001765 error_setg(errp, "The '%s' block driver requires a file name",
1766 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001767 ret = -EINVAL;
1768 goto fail_opts;
1769 }
1770
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001771 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1772 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001773
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001774 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001775
1776 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001777 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1778 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1779 } else {
1780 ret = -ENOTSUP;
1781 }
1782 if (ret < 0) {
1783 error_setg(errp,
1784 !bs->read_only && bdrv_is_whitelisted(drv, true)
1785 ? "Driver '%s' can only be used for read-only devices"
1786 : "Driver '%s' is not whitelisted",
1787 drv->format_name);
1788 goto fail_opts;
1789 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001790 }
Kevin Wolf57915332010-04-14 15:24:50 +02001791
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001792 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001793 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001794
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001795 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001796 if (!bs->read_only) {
1797 bdrv_enable_copy_on_read(bs);
1798 } else {
1799 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001800 ret = -EINVAL;
1801 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001802 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001803 }
1804
Alberto Garcia415bbca2018-10-03 13:23:13 +03001805 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001806 if (discard != NULL) {
1807 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1808 error_setg(errp, "Invalid discard option");
1809 ret = -EINVAL;
1810 goto fail_opts;
1811 }
1812 }
1813
Alberto Garcia543770b2018-09-06 12:37:09 +03001814 bs->detect_zeroes =
1815 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1816 if (local_err) {
1817 error_propagate(errp, local_err);
1818 ret = -EINVAL;
1819 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001820 }
1821
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001822 if (filename != NULL) {
1823 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1824 } else {
1825 bs->filename[0] = '\0';
1826 }
Max Reitz91af7012014-07-18 20:24:56 +02001827 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001828
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001829 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001830 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001831 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001832
Kevin Wolf01a56502017-01-18 15:51:56 +01001833 assert(!drv->bdrv_file_open || file == NULL);
1834 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001835 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001836 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001837 }
1838
Kevin Wolf18edf282015-04-07 17:12:56 +02001839 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001840 return 0;
1841
Kevin Wolf18edf282015-04-07 17:12:56 +02001842fail_opts:
1843 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001844 return ret;
1845}
1846
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001847static QDict *parse_json_filename(const char *filename, Error **errp)
1848{
1849 QObject *options_obj;
1850 QDict *options;
1851 int ret;
1852
1853 ret = strstart(filename, "json:", &filename);
1854 assert(ret);
1855
Markus Armbruster5577fff2017-02-28 22:26:59 +01001856 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001857 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001858 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001859 return NULL;
1860 }
1861
Max Reitz7dc847e2018-02-24 16:40:29 +01001862 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001863 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001864 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001865 error_setg(errp, "Invalid JSON object given");
1866 return NULL;
1867 }
1868
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001869 qdict_flatten(options);
1870
1871 return options;
1872}
1873
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001874static void parse_json_protocol(QDict *options, const char **pfilename,
1875 Error **errp)
1876{
1877 QDict *json_options;
1878 Error *local_err = NULL;
1879
1880 /* Parse json: pseudo-protocol */
1881 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1882 return;
1883 }
1884
1885 json_options = parse_json_filename(*pfilename, &local_err);
1886 if (local_err) {
1887 error_propagate(errp, local_err);
1888 return;
1889 }
1890
1891 /* Options given in the filename have lower priority than options
1892 * specified directly */
1893 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001894 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001895 *pfilename = NULL;
1896}
1897
Kevin Wolf57915332010-04-14 15:24:50 +02001898/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001899 * Fills in default options for opening images and converts the legacy
1900 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001901 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1902 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001903 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001904static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001905 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001906{
1907 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001908 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001909 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001910 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001911 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001912
Markus Armbruster129c7d12017-03-30 19:43:12 +02001913 /*
1914 * Caution: while qdict_get_try_str() is fine, getting non-string
1915 * types would require more care. When @options come from
1916 * -blockdev or blockdev_add, its members are typed according to
1917 * the QAPI schema, but when they come from -drive, they're all
1918 * QString.
1919 */
Max Reitz53a29512015-03-19 14:53:16 -04001920 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001921 if (drvname) {
1922 drv = bdrv_find_format(drvname);
1923 if (!drv) {
1924 error_setg(errp, "Unknown driver '%s'", drvname);
1925 return -ENOENT;
1926 }
1927 /* If the user has explicitly specified the driver, this choice should
1928 * override the BDRV_O_PROTOCOL flag */
1929 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001930 }
1931
1932 if (protocol) {
1933 *flags |= BDRV_O_PROTOCOL;
1934 } else {
1935 *flags &= ~BDRV_O_PROTOCOL;
1936 }
1937
Kevin Wolf91a097e2015-05-08 17:49:53 +02001938 /* Translate cache options from flags into options */
1939 update_options_from_flags(*options, *flags);
1940
Kevin Wolff54120f2014-05-26 11:09:59 +02001941 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001942 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001943 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001944 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001945 parse_filename = true;
1946 } else {
1947 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1948 "the same time");
1949 return -EINVAL;
1950 }
1951 }
1952
1953 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001954 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001955 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001956
Max Reitz053e1572015-08-26 19:47:51 +02001957 if (!drvname && protocol) {
1958 if (filename) {
1959 drv = bdrv_find_protocol(filename, parse_filename, errp);
1960 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001961 return -EINVAL;
1962 }
Max Reitz053e1572015-08-26 19:47:51 +02001963
1964 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05001965 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02001966 } else {
1967 error_setg(errp, "Must specify either driver or file");
1968 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001969 }
1970 }
1971
Kevin Wolf17b005f2014-05-27 10:50:29 +02001972 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001973
1974 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001975 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001976 drv->bdrv_parse_filename(filename, *options, &local_err);
1977 if (local_err) {
1978 error_propagate(errp, local_err);
1979 return -EINVAL;
1980 }
1981
1982 if (!drv->bdrv_needs_filename) {
1983 qdict_del(*options, "filename");
1984 }
1985 }
1986
1987 return 0;
1988}
1989
Kevin Wolf148eb132017-09-14 14:32:04 +02001990typedef struct BlockReopenQueueEntry {
1991 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01001992 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02001993 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03001994 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02001995} BlockReopenQueueEntry;
1996
1997/*
1998 * Return the flags that @bs will have after the reopens in @q have
1999 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2000 * return the current flags.
2001 */
2002static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2003{
2004 BlockReopenQueueEntry *entry;
2005
2006 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002007 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002008 if (entry->state.bs == bs) {
2009 return entry->state.flags;
2010 }
2011 }
2012 }
2013
2014 return bs->open_flags;
2015}
2016
2017/* Returns whether the image file can be written to after the reopen queue @q
2018 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002019static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2020 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002021{
2022 int flags = bdrv_reopen_get_flags(q, bs);
2023
2024 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2025}
2026
Max Reitzcc022142018-06-06 21:37:00 +02002027/*
2028 * Return whether the BDS can be written to. This is not necessarily
2029 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2030 * be written to but do not count as read-only images.
2031 */
2032bool bdrv_is_writable(BlockDriverState *bs)
2033{
2034 return bdrv_is_writable_after_reopen(bs, NULL);
2035}
2036
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002037static char *bdrv_child_user_desc(BdrvChild *c)
2038{
2039 if (c->klass->get_parent_desc) {
2040 return c->klass->get_parent_desc(c);
2041 }
2042
2043 return g_strdup("another user");
2044}
2045
2046static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2047{
2048 g_autofree char *user = NULL;
2049 g_autofree char *perm_names = NULL;
2050
2051 if ((b->perm & a->shared_perm) == b->perm) {
2052 return true;
2053 }
2054
2055 perm_names = bdrv_perm_names(b->perm & ~a->shared_perm);
2056 user = bdrv_child_user_desc(a);
2057 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2058 "allow '%s' on %s",
2059 user, a->name, perm_names, bdrv_get_node_name(b->bs));
2060
2061 return false;
2062}
2063
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002064static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002065{
2066 BdrvChild *a, *b;
2067
2068 /*
2069 * During the loop we'll look at each pair twice. That's correct because
2070 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2071 * directions.
2072 */
2073 QLIST_FOREACH(a, &bs->parents, next_parent) {
2074 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002075 if (a == b) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002076 continue;
2077 }
2078
2079 if (!bdrv_a_allow_b(a, b, errp)) {
2080 return true;
2081 }
2082 }
2083 }
2084
2085 return false;
2086}
2087
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002088static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002089 BdrvChild *c, BdrvChildRole role,
2090 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002091 uint64_t parent_perm, uint64_t parent_shared,
2092 uint64_t *nperm, uint64_t *nshared)
2093{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002094 assert(bs->drv && bs->drv->bdrv_child_perm);
Max Reitze5d8a402020-05-13 13:05:44 +02002095 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002096 parent_perm, parent_shared,
2097 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002098 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002099 if (child_bs && child_bs->force_share) {
2100 *nshared = BLK_PERM_ALL;
2101 }
2102}
2103
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002104/*
2105 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2106 * nodes that are already in the @list, of course) so that final list is
2107 * topologically sorted. Return the result (GSList @list object is updated, so
2108 * don't use old reference after function call).
2109 *
2110 * On function start @list must be already topologically sorted and for any node
2111 * in the @list the whole subtree of the node must be in the @list as well. The
2112 * simplest way to satisfy this criteria: use only result of
2113 * bdrv_topological_dfs() or NULL as @list parameter.
2114 */
2115static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2116 BlockDriverState *bs)
2117{
2118 BdrvChild *child;
2119 g_autoptr(GHashTable) local_found = NULL;
2120
2121 if (!found) {
2122 assert(!list);
2123 found = local_found = g_hash_table_new(NULL, NULL);
2124 }
2125
2126 if (g_hash_table_contains(found, bs)) {
2127 return list;
2128 }
2129 g_hash_table_add(found, bs);
2130
2131 QLIST_FOREACH(child, &bs->children, next) {
2132 list = bdrv_topological_dfs(list, found, child->bs);
2133 }
2134
2135 return g_slist_prepend(list, bs);
2136}
2137
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002138static void bdrv_child_set_perm_commit(void *opaque)
2139{
2140 BdrvChild *c = opaque;
2141
2142 c->has_backup_perm = false;
2143}
2144
2145static void bdrv_child_set_perm_abort(void *opaque)
2146{
2147 BdrvChild *c = opaque;
2148 /*
2149 * We may have child->has_backup_perm unset at this point, as in case of
2150 * _check_ stage of permission update failure we may _check_ not the whole
2151 * subtree. Still, _abort_ is called on the whole subtree anyway.
2152 */
2153 if (c->has_backup_perm) {
2154 c->perm = c->backup_perm;
2155 c->shared_perm = c->backup_shared_perm;
2156 c->has_backup_perm = false;
2157 }
2158}
2159
2160static TransactionActionDrv bdrv_child_set_pem_drv = {
2161 .abort = bdrv_child_set_perm_abort,
2162 .commit = bdrv_child_set_perm_commit,
2163};
2164
2165/*
2166 * With tran=NULL needs to be followed by direct call to either
2167 * bdrv_child_set_perm_commit() or bdrv_child_set_perm_abort().
2168 *
2169 * With non-NULL tran needs to be followed by tran_abort() or tran_commit()
2170 * instead.
2171 */
2172static void bdrv_child_set_perm_safe(BdrvChild *c, uint64_t perm,
2173 uint64_t shared, Transaction *tran)
2174{
2175 if (!c->has_backup_perm) {
2176 c->has_backup_perm = true;
2177 c->backup_perm = c->perm;
2178 c->backup_shared_perm = c->shared_perm;
2179 }
2180 /*
2181 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2182 * same c twice during check_perm procedure
2183 */
2184
2185 c->perm = perm;
2186 c->shared_perm = shared;
2187
2188 if (tran) {
2189 tran_add(tran, &bdrv_child_set_pem_drv, c);
2190 }
2191}
2192
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002193static void bdrv_drv_set_perm_commit(void *opaque)
2194{
2195 BlockDriverState *bs = opaque;
2196 uint64_t cumulative_perms, cumulative_shared_perms;
2197
2198 if (bs->drv->bdrv_set_perm) {
2199 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2200 &cumulative_shared_perms);
2201 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2202 }
2203}
2204
2205static void bdrv_drv_set_perm_abort(void *opaque)
2206{
2207 BlockDriverState *bs = opaque;
2208
2209 if (bs->drv->bdrv_abort_perm_update) {
2210 bs->drv->bdrv_abort_perm_update(bs);
2211 }
2212}
2213
2214TransactionActionDrv bdrv_drv_set_perm_drv = {
2215 .abort = bdrv_drv_set_perm_abort,
2216 .commit = bdrv_drv_set_perm_commit,
2217};
2218
2219static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2220 uint64_t shared_perm, Transaction *tran,
2221 Error **errp)
2222{
2223 if (!bs->drv) {
2224 return 0;
2225 }
2226
2227 if (bs->drv->bdrv_check_perm) {
2228 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2229 if (ret < 0) {
2230 return ret;
2231 }
2232 }
2233
2234 if (tran) {
2235 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2236 }
2237
2238 return 0;
2239}
2240
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002241typedef struct BdrvReplaceChildState {
2242 BdrvChild *child;
2243 BlockDriverState *old_bs;
2244} BdrvReplaceChildState;
2245
2246static void bdrv_replace_child_commit(void *opaque)
2247{
2248 BdrvReplaceChildState *s = opaque;
2249
2250 bdrv_unref(s->old_bs);
2251}
2252
2253static void bdrv_replace_child_abort(void *opaque)
2254{
2255 BdrvReplaceChildState *s = opaque;
2256 BlockDriverState *new_bs = s->child->bs;
2257
2258 /* old_bs reference is transparently moved from @s to @s->child */
2259 bdrv_replace_child_noperm(s->child, s->old_bs);
2260 bdrv_unref(new_bs);
2261}
2262
2263static TransactionActionDrv bdrv_replace_child_drv = {
2264 .commit = bdrv_replace_child_commit,
2265 .abort = bdrv_replace_child_abort,
2266 .clean = g_free,
2267};
2268
2269/*
2270 * bdrv_replace_child_safe
2271 *
2272 * Note: real unref of old_bs is done only on commit.
2273 */
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002274static void bdrv_replace_child_safe(BdrvChild *child, BlockDriverState *new_bs,
2275 Transaction *tran)
2276{
2277 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2278 *s = (BdrvReplaceChildState) {
2279 .child = child,
2280 .old_bs = child->bs,
2281 };
2282 tran_add(tran, &bdrv_replace_child_drv, s);
2283
2284 if (new_bs) {
2285 bdrv_ref(new_bs);
2286 }
2287 bdrv_replace_child_noperm(child, new_bs);
2288 /* old_bs reference is transparently moved from @child to @s */
2289}
2290
Kevin Wolf33a610c2016-12-15 13:04:20 +01002291/*
2292 * Check whether permissions on this node can be changed in a way that
2293 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
2294 * permissions of all its parents. This involves checking whether all necessary
2295 * permission changes to child nodes can be performed.
2296 *
2297 * A call to this function must always be followed by a call to bdrv_set_perm()
2298 * or bdrv_abort_perm_update().
2299 */
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002300static int bdrv_node_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
2301 uint64_t cumulative_perms,
2302 uint64_t cumulative_shared_perms,
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002303 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002304{
2305 BlockDriver *drv = bs->drv;
2306 BdrvChild *c;
2307 int ret;
2308
2309 /* Write permissions never work with read-only images */
2310 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002311 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002312 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002313 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2314 error_setg(errp, "Block node is read-only");
2315 } else {
2316 uint64_t current_perms, current_shared;
2317 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2318 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2319 error_setg(errp, "Cannot make block node read-only, there is "
2320 "a writer on it");
2321 } else {
2322 error_setg(errp, "Cannot make block node read-only and create "
2323 "a writer on it");
2324 }
2325 }
2326
Kevin Wolf33a610c2016-12-15 13:04:20 +01002327 return -EPERM;
2328 }
2329
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002330 /*
2331 * Unaligned requests will automatically be aligned to bl.request_alignment
2332 * and without RESIZE we can't extend requests to write to space beyond the
2333 * end of the image, so it's required that the image size is aligned.
2334 */
2335 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2336 !(cumulative_perms & BLK_PERM_RESIZE))
2337 {
2338 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2339 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2340 "Image size is not a multiple of request "
2341 "alignment");
2342 return -EPERM;
2343 }
2344 }
2345
Kevin Wolf33a610c2016-12-15 13:04:20 +01002346 /* Check this node */
2347 if (!drv) {
2348 return 0;
2349 }
2350
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002351 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002352 errp);
2353 if (ret < 0) {
2354 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002355 }
2356
Kevin Wolf78e421c2016-12-20 23:25:12 +01002357 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002358 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002359 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002360 return 0;
2361 }
2362
2363 /* Check all children */
2364 QLIST_FOREACH(c, &bs->children, next) {
2365 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002366
Max Reitze5d8a402020-05-13 13:05:44 +02002367 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002368 cumulative_perms, cumulative_shared_perms,
2369 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002370 bdrv_child_set_perm_safe(c, cur_perm, cur_shared, tran);
2371 }
2372
2373 return 0;
2374}
2375
Vladimir Sementsov-Ogievskiy25409802021-04-28 18:18:00 +03002376static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2377 Transaction *tran, Error **errp)
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002378{
2379 int ret;
Vladimir Sementsov-Ogievskiy25409802021-04-28 18:18:00 +03002380 uint64_t cumulative_perms, cumulative_shared_perms;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002381 BlockDriverState *bs;
2382
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002383 for ( ; list; list = list->next) {
2384 bs = list->data;
2385
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002386 if (bdrv_parent_perms_conflict(bs, errp)) {
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002387 return -EINVAL;
2388 }
2389
2390 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2391 &cumulative_shared_perms);
2392
2393 ret = bdrv_node_check_perm(bs, q, cumulative_perms,
2394 cumulative_shared_perms,
Vladimir Sementsov-Ogievskiy9397c142021-04-28 18:17:53 +03002395 tran, errp);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002396 if (ret < 0) {
2397 return ret;
2398 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002399 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002400
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002401 return 0;
2402}
2403
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002404static void bdrv_node_set_perm(BlockDriverState *bs)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002405{
2406 BlockDriver *drv = bs->drv;
2407 BdrvChild *c;
2408
2409 if (!drv) {
2410 return;
2411 }
2412
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002413 bdrv_drv_set_perm_commit(bs);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002414
Kevin Wolf78e421c2016-12-20 23:25:12 +01002415 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002416 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002417 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002418 return;
2419 }
2420
2421 /* Update all children */
2422 QLIST_FOREACH(c, &bs->children, next) {
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002423 bdrv_child_set_perm_commit(c);
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002424 }
2425}
2426
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002427static void bdrv_list_set_perm(GSList *list)
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002428{
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002429 for ( ; list; list = list->next) {
2430 bdrv_node_set_perm((BlockDriverState *)list->data);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002431 }
2432}
2433
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002434static void bdrv_set_perm(BlockDriverState *bs)
2435{
2436 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2437 return bdrv_list_set_perm(list);
2438}
2439
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002440void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2441 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002442{
2443 BdrvChild *c;
2444 uint64_t cumulative_perms = 0;
2445 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2446
2447 QLIST_FOREACH(c, &bs->parents, next_parent) {
2448 cumulative_perms |= c->perm;
2449 cumulative_shared_perms &= c->shared_perm;
2450 }
2451
2452 *perm = cumulative_perms;
2453 *shared_perm = cumulative_shared_perms;
2454}
2455
Fam Zheng51761962017-05-03 00:35:36 +08002456char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002457{
2458 struct perm_name {
2459 uint64_t perm;
2460 const char *name;
2461 } permissions[] = {
2462 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2463 { BLK_PERM_WRITE, "write" },
2464 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2465 { BLK_PERM_RESIZE, "resize" },
2466 { BLK_PERM_GRAPH_MOD, "change children" },
2467 { 0, NULL }
2468 };
2469
Alberto Garciae2a74232020-01-10 18:15:18 +01002470 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002471 struct perm_name *p;
2472
2473 for (p = permissions; p->name; p++) {
2474 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002475 if (result->len > 0) {
2476 g_string_append(result, ", ");
2477 }
2478 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002479 }
2480 }
2481
Alberto Garciae2a74232020-01-10 18:15:18 +01002482 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002483}
2484
Kevin Wolf33a610c2016-12-15 13:04:20 +01002485
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002486static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002487{
2488 int ret;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002489 Transaction *tran = tran_new();
2490 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002491
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002492 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2493 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002494
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002495 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002496}
2497
Kevin Wolf33a610c2016-12-15 13:04:20 +01002498int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2499 Error **errp)
2500{
Max Reitz10467792019-05-22 19:03:51 +02002501 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002502 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002503 int ret;
2504
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002505 bdrv_child_set_perm_safe(c, perm, shared, tran);
2506
2507 ret = bdrv_refresh_perms(c->bs, &local_err);
2508
2509 tran_finalize(tran, ret);
2510
Kevin Wolf33a610c2016-12-15 13:04:20 +01002511 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002512 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2513 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002514 error_propagate(errp, local_err);
2515 } else {
2516 /*
2517 * Our caller may intend to only loosen restrictions and
2518 * does not expect this function to fail. Errors are not
2519 * fatal in such a case, so we can just hide them from our
2520 * caller.
2521 */
2522 error_free(local_err);
2523 ret = 0;
2524 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002525 }
2526
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002527 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002528}
2529
Max Reitzc1087f12019-05-22 19:03:46 +02002530int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2531{
2532 uint64_t parent_perms, parent_shared;
2533 uint64_t perms, shared;
2534
2535 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002536 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002537 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002538
2539 return bdrv_child_try_set_perm(c, perms, shared, errp);
2540}
2541
Max Reitz87278af2020-05-13 13:05:40 +02002542/*
2543 * Default implementation for .bdrv_child_perm() for block filters:
2544 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2545 * filtered child.
2546 */
2547static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002548 BdrvChildRole role,
2549 BlockReopenQueue *reopen_queue,
2550 uint64_t perm, uint64_t shared,
2551 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002552{
Kevin Wolfe444fa82019-08-02 15:59:41 +02002553 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2554 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002555}
2556
Max Reitz70082db2020-05-13 13:05:26 +02002557static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002558 BdrvChildRole role,
2559 BlockReopenQueue *reopen_queue,
2560 uint64_t perm, uint64_t shared,
2561 uint64_t *nperm, uint64_t *nshared)
2562{
Max Reitze5d8a402020-05-13 13:05:44 +02002563 assert(role & BDRV_CHILD_COW);
Max Reitz70082db2020-05-13 13:05:26 +02002564
2565 /*
2566 * We want consistent read from backing files if the parent needs it.
2567 * No other operations are performed on backing files.
2568 */
2569 perm &= BLK_PERM_CONSISTENT_READ;
2570
2571 /*
2572 * If the parent can deal with changing data, we're okay with a
2573 * writable and resizable backing file.
2574 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2575 */
2576 if (shared & BLK_PERM_WRITE) {
2577 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2578 } else {
2579 shared = 0;
2580 }
2581
2582 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2583 BLK_PERM_WRITE_UNCHANGED;
2584
2585 if (bs->open_flags & BDRV_O_INACTIVE) {
2586 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2587 }
2588
2589 *nperm = perm;
2590 *nshared = shared;
2591}
2592
Max Reitz6f838a42020-05-13 13:05:27 +02002593static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002594 BdrvChildRole role,
2595 BlockReopenQueue *reopen_queue,
2596 uint64_t perm, uint64_t shared,
2597 uint64_t *nperm, uint64_t *nshared)
2598{
2599 int flags;
2600
Max Reitze5d8a402020-05-13 13:05:44 +02002601 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002602
2603 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2604
2605 /*
2606 * Apart from the modifications below, the same permissions are
2607 * forwarded and left alone as for filters
2608 */
Max Reitze5d8a402020-05-13 13:05:44 +02002609 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002610 perm, shared, &perm, &shared);
2611
Max Reitzf8890542020-05-13 13:05:28 +02002612 if (role & BDRV_CHILD_METADATA) {
2613 /* Format drivers may touch metadata even if the guest doesn't write */
2614 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2615 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2616 }
2617
2618 /*
2619 * bs->file always needs to be consistent because of the
2620 * metadata. We can never allow other users to resize or write
2621 * to it.
2622 */
2623 if (!(flags & BDRV_O_NO_IO)) {
2624 perm |= BLK_PERM_CONSISTENT_READ;
2625 }
2626 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002627 }
2628
Max Reitzf8890542020-05-13 13:05:28 +02002629 if (role & BDRV_CHILD_DATA) {
2630 /*
2631 * Technically, everything in this block is a subset of the
2632 * BDRV_CHILD_METADATA path taken above, and so this could
2633 * be an "else if" branch. However, that is not obvious, and
2634 * this function is not performance critical, therefore we let
2635 * this be an independent "if".
2636 */
2637
2638 /*
2639 * We cannot allow other users to resize the file because the
2640 * format driver might have some assumptions about the size
2641 * (e.g. because it is stored in metadata, or because the file
2642 * is split into fixed-size data files).
2643 */
2644 shared &= ~BLK_PERM_RESIZE;
2645
2646 /*
2647 * WRITE_UNCHANGED often cannot be performed as such on the
2648 * data file. For example, the qcow2 driver may still need to
2649 * write copied clusters on copy-on-read.
2650 */
2651 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2652 perm |= BLK_PERM_WRITE;
2653 }
2654
2655 /*
2656 * If the data file is written to, the format driver may
2657 * expect to be able to resize it by writing beyond the EOF.
2658 */
2659 if (perm & BLK_PERM_WRITE) {
2660 perm |= BLK_PERM_RESIZE;
2661 }
Max Reitz6f838a42020-05-13 13:05:27 +02002662 }
Max Reitz6f838a42020-05-13 13:05:27 +02002663
2664 if (bs->open_flags & BDRV_O_INACTIVE) {
2665 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2666 }
2667
2668 *nperm = perm;
2669 *nshared = shared;
2670}
2671
Max Reitz2519f542020-05-13 13:05:29 +02002672void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002673 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002674 uint64_t perm, uint64_t shared,
2675 uint64_t *nperm, uint64_t *nshared)
2676{
Max Reitz2519f542020-05-13 13:05:29 +02002677 if (role & BDRV_CHILD_FILTERED) {
2678 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2679 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002680 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002681 perm, shared, nperm, nshared);
2682 } else if (role & BDRV_CHILD_COW) {
2683 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002684 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002685 perm, shared, nperm, nshared);
2686 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002687 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002688 perm, shared, nperm, nshared);
2689 } else {
2690 g_assert_not_reached();
2691 }
2692}
2693
Max Reitz7b1d9c42019-11-08 13:34:51 +01002694uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2695{
2696 static const uint64_t permissions[] = {
2697 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2698 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2699 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2700 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2701 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2702 };
2703
2704 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2705 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2706
2707 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2708
2709 return permissions[qapi_perm];
2710}
2711
Kevin Wolf8ee03992017-03-06 13:45:28 +01002712static void bdrv_replace_child_noperm(BdrvChild *child,
2713 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002714{
2715 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002716 int new_bs_quiesce_counter;
2717 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002718
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002719 assert(!child->frozen);
2720
Fam Zhengbb2614e2017-04-07 14:54:10 +08002721 if (old_bs && new_bs) {
2722 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2723 }
Max Reitzdebc2922019-07-22 15:33:44 +02002724
2725 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2726 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2727
2728 /*
2729 * If the new child node is drained but the old one was not, flush
2730 * all outstanding requests to the old child node.
2731 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002732 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002733 bdrv_parent_drained_begin_single(child, true);
2734 drain_saldo--;
2735 }
2736
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002737 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002738 /* Detach first so that the recursive drain sections coming from @child
2739 * are already gone and we only end the drain sections that came from
2740 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002741 if (child->klass->detach) {
2742 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002743 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002744 QLIST_REMOVE(child, next_parent);
2745 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002746
2747 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002748
2749 if (new_bs) {
2750 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002751
2752 /*
2753 * Detaching the old node may have led to the new node's
2754 * quiesce_counter having been decreased. Not a problem, we
2755 * just need to recognize this here and then invoke
2756 * drained_end appropriately more often.
2757 */
2758 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2759 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002760
Kevin Wolfd736f112017-12-18 16:05:48 +01002761 /* Attach only after starting new drained sections, so that recursive
2762 * drain sections coming from @child don't get an extra .drained_begin
2763 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002764 if (child->klass->attach) {
2765 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002766 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002767 }
Max Reitzdebc2922019-07-22 15:33:44 +02002768
2769 /*
2770 * If the old child node was drained but the new one is not, allow
2771 * requests to come in only after the new node has been attached.
2772 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002773 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002774 bdrv_parent_drained_end_single(child);
2775 drain_saldo++;
2776 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002777}
2778
Kevin Wolf466787f2017-03-08 14:44:07 +01002779/*
2780 * Updates @child to change its reference to point to @new_bs, including
zhaolichange3a6e0d2020-09-17 15:50:20 +08002781 * checking and applying the necessary permission updates both to the old node
Kevin Wolf466787f2017-03-08 14:44:07 +01002782 * and to @new_bs.
2783 *
2784 * NULL is passed as @new_bs for removing the reference before freeing @child.
2785 *
2786 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2787 * function uses bdrv_set_perm() to update the permissions according to the new
2788 * reference that @new_bs gets.
Max Reitz7b99a262019-06-12 16:07:11 +02002789 *
2790 * Callers must ensure that child->frozen is false.
Kevin Wolf466787f2017-03-08 14:44:07 +01002791 */
2792static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
Kevin Wolf8ee03992017-03-06 13:45:28 +01002793{
2794 BlockDriverState *old_bs = child->bs;
Kevin Wolf8ee03992017-03-06 13:45:28 +01002795
Max Reitz7b99a262019-06-12 16:07:11 +02002796 /* Asserts that child->frozen == false */
Kevin Wolf8aecf1d2017-08-03 17:02:57 +02002797 bdrv_replace_child_noperm(child, new_bs);
2798
Max Reitz87ace5f2019-05-22 19:03:49 +02002799 /*
2800 * Start with the new node's permissions. If @new_bs is a (direct
2801 * or indirect) child of @old_bs, we must complete the permission
2802 * update on @new_bs before we loosen the restrictions on @old_bs.
2803 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2804 * updating the permissions of @new_bs, and thus not purely loosen
2805 * restrictions.
2806 */
2807 if (new_bs) {
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002808 bdrv_set_perm(new_bs);
Max Reitz87ace5f2019-05-22 19:03:49 +02002809 }
2810
Kevin Wolf8ee03992017-03-06 13:45:28 +01002811 if (old_bs) {
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002812 /*
2813 * Update permissions for old node. We're just taking a parent away, so
2814 * we're loosening restrictions. Errors of permission update are not
2815 * fatal in this case, ignore them.
2816 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002817 bdrv_refresh_perms(old_bs, NULL);
Kevin Wolfad943dc2019-04-24 18:04:42 +02002818
2819 /* When the parent requiring a non-default AioContext is removed, the
2820 * node moves back to the main AioContext */
2821 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
Kevin Wolf8ee03992017-03-06 13:45:28 +01002822 }
Kevin Wolff54120f2014-05-26 11:09:59 +02002823}
2824
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03002825static void bdrv_child_free(void *opaque)
2826{
2827 BdrvChild *c = opaque;
2828
2829 g_free(c->name);
2830 g_free(c);
2831}
2832
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002833static void bdrv_remove_empty_child(BdrvChild *child)
2834{
2835 assert(!child->bs);
2836 QLIST_SAFE_REMOVE(child, next);
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03002837 bdrv_child_free(child);
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002838}
2839
2840typedef struct BdrvAttachChildCommonState {
2841 BdrvChild **child;
2842 AioContext *old_parent_ctx;
2843 AioContext *old_child_ctx;
2844} BdrvAttachChildCommonState;
2845
2846static void bdrv_attach_child_common_abort(void *opaque)
2847{
2848 BdrvAttachChildCommonState *s = opaque;
2849 BdrvChild *child = *s->child;
2850 BlockDriverState *bs = child->bs;
2851
2852 bdrv_replace_child_noperm(child, NULL);
2853
2854 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2855 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2856 }
2857
2858 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
2859 GSList *ignore = g_slist_prepend(NULL, child);
2860
2861 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2862 &error_abort);
2863 g_slist_free(ignore);
2864 ignore = g_slist_prepend(NULL, child);
2865 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
2866
2867 g_slist_free(ignore);
2868 }
2869
2870 bdrv_unref(bs);
2871 bdrv_remove_empty_child(child);
2872 *s->child = NULL;
2873}
2874
2875static TransactionActionDrv bdrv_attach_child_common_drv = {
2876 .abort = bdrv_attach_child_common_abort,
2877 .clean = g_free,
2878};
2879
2880/*
2881 * Common part of attaching bdrv child to bs or to blk or to job
2882 */
2883static int bdrv_attach_child_common(BlockDriverState *child_bs,
2884 const char *child_name,
2885 const BdrvChildClass *child_class,
2886 BdrvChildRole child_role,
2887 uint64_t perm, uint64_t shared_perm,
2888 void *opaque, BdrvChild **child,
2889 Transaction *tran, Error **errp)
2890{
2891 BdrvChild *new_child;
2892 AioContext *parent_ctx;
2893 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2894
2895 assert(child);
2896 assert(*child == NULL);
2897
2898 new_child = g_new(BdrvChild, 1);
2899 *new_child = (BdrvChild) {
2900 .bs = NULL,
2901 .name = g_strdup(child_name),
2902 .klass = child_class,
2903 .role = child_role,
2904 .perm = perm,
2905 .shared_perm = shared_perm,
2906 .opaque = opaque,
2907 };
2908
2909 /*
2910 * If the AioContexts don't match, first try to move the subtree of
2911 * child_bs into the AioContext of the new parent. If this doesn't work,
2912 * try moving the parent into the AioContext of child_bs instead.
2913 */
2914 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2915 if (child_ctx != parent_ctx) {
2916 Error *local_err = NULL;
2917 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2918
2919 if (ret < 0 && child_class->can_set_aio_ctx) {
2920 GSList *ignore = g_slist_prepend(NULL, new_child);
2921 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2922 NULL))
2923 {
2924 error_free(local_err);
2925 ret = 0;
2926 g_slist_free(ignore);
2927 ignore = g_slist_prepend(NULL, new_child);
2928 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2929 }
2930 g_slist_free(ignore);
2931 }
2932
2933 if (ret < 0) {
2934 error_propagate(errp, local_err);
2935 bdrv_remove_empty_child(new_child);
2936 return ret;
2937 }
2938 }
2939
2940 bdrv_ref(child_bs);
2941 bdrv_replace_child_noperm(new_child, child_bs);
2942
2943 *child = new_child;
2944
2945 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
2946 *s = (BdrvAttachChildCommonState) {
2947 .child = child,
2948 .old_parent_ctx = parent_ctx,
2949 .old_child_ctx = child_ctx,
2950 };
2951 tran_add(tran, &bdrv_attach_child_common_drv, s);
2952
2953 return 0;
2954}
2955
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03002956static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
2957 BlockDriverState *child_bs,
2958 const char *child_name,
2959 const BdrvChildClass *child_class,
2960 BdrvChildRole child_role,
2961 BdrvChild **child,
2962 Transaction *tran,
2963 Error **errp)
2964{
2965 int ret;
2966 uint64_t perm, shared_perm;
2967
2968 assert(parent_bs->drv);
2969
2970 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2971 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2972 perm, shared_perm, &perm, &shared_perm);
2973
2974 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
2975 child_role, perm, shared_perm, parent_bs,
2976 child, tran, errp);
2977 if (ret < 0) {
2978 return ret;
2979 }
2980
2981 QLIST_INSERT_HEAD(&parent_bs->children, *child, next);
2982 /*
2983 * child is removed in bdrv_attach_child_common_abort(), so don't care to
2984 * abort this change separately.
2985 */
2986
2987 return 0;
2988}
2989
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002990static void bdrv_detach_child(BdrvChild *child)
2991{
2992 bdrv_replace_child(child, NULL);
2993 bdrv_remove_empty_child(child);
2994}
2995
Alberto Garciab441dc72019-05-13 16:46:18 +03002996/*
2997 * This function steals the reference to child_bs from the caller.
2998 * That reference is later dropped by bdrv_root_unref_child().
2999 *
3000 * On failure NULL is returned, errp is set and the reference to
3001 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003002 *
3003 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3004 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003005 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003006BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3007 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003008 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003009 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003010 uint64_t perm, uint64_t shared_perm,
3011 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003012{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003013 int ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003014 BdrvChild *child = NULL;
3015 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003016
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003017 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3018 child_role, perm, shared_perm, opaque,
3019 &child, tran, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003020 if (ret < 0) {
Alberto Garciab441dc72019-05-13 16:46:18 +03003021 bdrv_unref(child_bs);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003022 return NULL;
3023 }
3024
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003025 ret = bdrv_refresh_perms(child_bs, errp);
3026 tran_finalize(tran, ret);
Kevin Wolfdf581792015-06-15 11:53:47 +02003027
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003028 bdrv_unref(child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003029 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003030}
3031
Alberto Garciab441dc72019-05-13 16:46:18 +03003032/*
3033 * This function transfers the reference to child_bs from the caller
3034 * to parent_bs. That reference is later dropped by parent_bs on
3035 * bdrv_close() or if someone calls bdrv_unref_child().
3036 *
3037 * On failure NULL is returned, errp is set and the reference to
3038 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003039 *
3040 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3041 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003042 */
Wen Congyang98292c62016-05-10 15:36:38 +08003043BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3044 BlockDriverState *child_bs,
3045 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003046 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003047 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003048 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003049{
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003050 int ret;
3051 BdrvChild *child = NULL;
3052 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003053
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003054 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3055 child_role, &child, tran, errp);
3056 if (ret < 0) {
3057 goto out;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003058 }
3059
Vladimir Sementsov-Ogievskiyaa5a04c2021-04-28 18:17:47 +03003060 ret = bdrv_refresh_perms(parent_bs, errp);
3061 if (ret < 0) {
3062 goto out;
3063 }
3064
3065out:
3066 tran_finalize(tran, ret);
3067
3068 bdrv_unref(child_bs);
3069
Kevin Wolff21d96d2016-03-08 13:47:46 +01003070 return child;
3071}
3072
Max Reitz7b99a262019-06-12 16:07:11 +02003073/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003074void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003075{
Kevin Wolf779020c2015-10-13 14:09:44 +02003076 BlockDriverState *child_bs;
3077
Kevin Wolff21d96d2016-03-08 13:47:46 +01003078 child_bs = child->bs;
3079 bdrv_detach_child(child);
3080 bdrv_unref(child_bs);
3081}
3082
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003083typedef struct BdrvSetInheritsFrom {
3084 BlockDriverState *bs;
3085 BlockDriverState *old_inherits_from;
3086} BdrvSetInheritsFrom;
3087
3088static void bdrv_set_inherits_from_abort(void *opaque)
3089{
3090 BdrvSetInheritsFrom *s = opaque;
3091
3092 s->bs->inherits_from = s->old_inherits_from;
3093}
3094
3095static TransactionActionDrv bdrv_set_inherits_from_drv = {
3096 .abort = bdrv_set_inherits_from_abort,
3097 .clean = g_free,
3098};
3099
3100/* @tran is allowed to be NULL. In this case no rollback is possible */
3101static void bdrv_set_inherits_from(BlockDriverState *bs,
3102 BlockDriverState *new_inherits_from,
3103 Transaction *tran)
3104{
3105 if (tran) {
3106 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3107
3108 *s = (BdrvSetInheritsFrom) {
3109 .bs = bs,
3110 .old_inherits_from = bs->inherits_from,
3111 };
3112
3113 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3114 }
3115
3116 bs->inherits_from = new_inherits_from;
3117}
3118
Max Reitz3cf746b2019-07-03 19:28:07 +02003119/**
3120 * Clear all inherits_from pointers from children and grandchildren of
3121 * @root that point to @root, where necessary.
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003122 * @tran is allowed to be NULL. In this case no rollback is possible
Max Reitz3cf746b2019-07-03 19:28:07 +02003123 */
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003124static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3125 Transaction *tran)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003126{
Max Reitz3cf746b2019-07-03 19:28:07 +02003127 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003128
Max Reitz3cf746b2019-07-03 19:28:07 +02003129 if (child->bs->inherits_from == root) {
3130 /*
3131 * Remove inherits_from only when the last reference between root and
3132 * child->bs goes away.
3133 */
3134 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003135 if (c != child && c->bs == child->bs) {
3136 break;
3137 }
3138 }
3139 if (c == NULL) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003140 bdrv_set_inherits_from(child->bs, NULL, tran);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003141 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003142 }
3143
Max Reitz3cf746b2019-07-03 19:28:07 +02003144 QLIST_FOREACH(c, &child->bs->children, next) {
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003145 bdrv_unset_inherits_from(root, c, tran);
Max Reitz3cf746b2019-07-03 19:28:07 +02003146 }
3147}
3148
Max Reitz7b99a262019-06-12 16:07:11 +02003149/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003150void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3151{
3152 if (child == NULL) {
3153 return;
3154 }
3155
Vladimir Sementsov-Ogievskiy332b3a12021-04-28 18:17:54 +03003156 bdrv_unset_inherits_from(parent, child, NULL);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003157 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003158}
3159
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003160
3161static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3162{
3163 BdrvChild *c;
3164 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003165 if (c->klass->change_media) {
3166 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003167 }
3168 }
3169}
3170
Alberto Garcia0065c452018-10-31 18:16:37 +02003171/* Return true if you can reach parent going through child->inherits_from
3172 * recursively. If parent or child are NULL, return false */
3173static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3174 BlockDriverState *parent)
3175{
3176 while (child && child != parent) {
3177 child = child->inherits_from;
3178 }
3179
3180 return child != NULL;
3181}
3182
Kevin Wolf5db15a52015-09-14 15:33:33 +02003183/*
Max Reitz25191e52020-05-13 13:05:33 +02003184 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3185 * mostly used for COW backing children (role = COW), but also for
3186 * filtered children (role = FILTERED | PRIMARY).
3187 */
3188static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3189{
3190 if (bs->drv && bs->drv->is_filter) {
3191 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3192 } else {
3193 return BDRV_CHILD_COW;
3194 }
3195}
3196
3197/*
Max Reitz9ee413c2019-06-12 18:42:34 +02003198 * Sets the bs->backing link of a BDS. A new reference is created; callers
Kevin Wolf5db15a52015-09-14 15:33:33 +02003199 * which don't need their own reference any more must call bdrv_unref().
3200 */
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003201static int bdrv_set_backing_noperm(BlockDriverState *bs,
3202 BlockDriverState *backing_hd,
3203 Transaction *tran, Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003204{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003205 int ret = 0;
Alberto Garcia0065c452018-10-31 18:16:37 +02003206 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
3207 bdrv_inherits_from_recursive(backing_hd, bs);
3208
Max Reitz9ee413c2019-06-12 18:42:34 +02003209 if (bdrv_is_backing_chain_frozen(bs, child_bs(bs->backing), errp)) {
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003210 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003211 }
3212
Kevin Wolf760e0062015-06-17 14:55:21 +02003213 if (bs->backing) {
Max Reitz7b99a262019-06-12 16:07:11 +02003214 /* Cannot be frozen, we checked that above */
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003215 bdrv_unset_inherits_from(bs, bs->backing, tran);
3216 bdrv_remove_filter_or_cow_child(bs, tran);
Fam Zheng826b6ca2014-05-23 21:29:47 +08003217 }
3218
Fam Zheng8d24cce2014-05-23 21:29:45 +08003219 if (!backing_hd) {
3220 goto out;
3221 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003222
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003223 ret = bdrv_attach_child_noperm(bs, backing_hd, "backing",
3224 &child_of_bds, bdrv_backing_role(bs),
3225 &bs->backing, tran, errp);
3226 if (ret < 0) {
3227 return ret;
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003228 }
3229
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003230
3231 /*
3232 * If backing_hd was already part of bs's backing chain, and
Alberto Garcia0065c452018-10-31 18:16:37 +02003233 * inherits_from pointed recursively to bs then let's update it to
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003234 * point directly to bs (else it will become NULL).
3235 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003236 if (update_inherits_from) {
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003237 bdrv_set_inherits_from(backing_hd, bs, tran);
Alberto Garcia0065c452018-10-31 18:16:37 +02003238 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003239
Fam Zheng8d24cce2014-05-23 21:29:45 +08003240out:
Vladimir Sementsov-Ogievskiy160333e2021-04-28 18:17:56 +03003241 bdrv_refresh_limits(bs, tran, NULL);
3242
3243 return 0;
3244}
3245
3246int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3247 Error **errp)
3248{
3249 int ret;
3250 Transaction *tran = tran_new();
3251
3252 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3253 if (ret < 0) {
3254 goto out;
3255 }
3256
3257 ret = bdrv_refresh_perms(bs, errp);
3258out:
3259 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003260
3261 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003262}
3263
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003264/*
3265 * Opens the backing file for a BlockDriverState if not yet open
3266 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003267 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3268 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3269 * itself, all options starting with "${bdref_key}." are considered part of the
3270 * BlockdevRef.
3271 *
3272 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003273 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003274int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3275 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003276{
Max Reitz6b6833c2019-02-01 20:29:15 +01003277 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003278 char *bdref_key_dot;
3279 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003280 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003281 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003282 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003283 QDict *options;
3284 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003285 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003286
Kevin Wolf760e0062015-06-17 14:55:21 +02003287 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003288 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003289 }
3290
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003291 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003292 if (parent_options == NULL) {
3293 tmp_parent_options = qdict_new();
3294 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003295 }
3296
Paolo Bonzini9156df12012-10-18 16:49:17 +02003297 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003298
3299 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3300 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3301 g_free(bdref_key_dot);
3302
Markus Armbruster129c7d12017-03-30 19:43:12 +02003303 /*
3304 * Caution: while qdict_get_try_str() is fine, getting non-string
3305 * types would require more care. When @parent_options come from
3306 * -blockdev or blockdev_add, its members are typed according to
3307 * the QAPI schema, but when they come from -drive, they're all
3308 * QString.
3309 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003310 reference = qdict_get_try_str(parent_options, bdref_key);
3311 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003312 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003313 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003314 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003315 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003316 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003317 if (qdict_size(options) == 0) {
3318 /* If the user specifies options that do not modify the
3319 * backing file's behavior, we might still consider it the
3320 * implicit backing file. But it's easier this way, and
3321 * just specifying some of the backing BDS's options is
3322 * only possible with -drive anyway (otherwise the QAPI
3323 * schema forces the user to specify everything). */
3324 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3325 }
3326
Max Reitz6b6833c2019-02-01 20:29:15 +01003327 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003328 if (local_err) {
3329 ret = -EINVAL;
3330 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003331 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003332 goto free_exit;
3333 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003334 }
3335
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003336 if (!bs->drv || !bs->drv->supports_backing) {
3337 ret = -EINVAL;
3338 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003339 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003340 goto free_exit;
3341 }
3342
Peter Krempa6bff5972017-10-12 16:14:10 +02003343 if (!reference &&
3344 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003345 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003346 }
3347
Max Reitz6b6833c2019-02-01 20:29:15 +01003348 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003349 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003350 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003351 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003352 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003353 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003354 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003355 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003356
Max Reitz998c2012019-02-01 20:29:08 +01003357 if (implicit_backing) {
3358 bdrv_refresh_filename(backing_hd);
3359 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3360 backing_hd->filename);
3361 }
3362
Kevin Wolf5db15a52015-09-14 15:33:33 +02003363 /* Hook up the backing file link; drop our reference, bs owns the
3364 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003365 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003366 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003367 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003368 goto free_exit;
3369 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003370
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003371 qdict_del(parent_options, bdref_key);
3372
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003373free_exit:
3374 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003375 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003376 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003377}
3378
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003379static BlockDriverState *
3380bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003381 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003382 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003383{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003384 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003385 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003386 char *bdref_key_dot;
3387 const char *reference;
3388
Max Reitzbd86fb92020-05-13 13:05:13 +02003389 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003390
Max Reitzda557aa2013-12-20 19:28:11 +01003391 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3392 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3393 g_free(bdref_key_dot);
3394
Markus Armbruster129c7d12017-03-30 19:43:12 +02003395 /*
3396 * Caution: while qdict_get_try_str() is fine, getting non-string
3397 * types would require more care. When @options come from
3398 * -blockdev or blockdev_add, its members are typed according to
3399 * the QAPI schema, but when they come from -drive, they're all
3400 * QString.
3401 */
Max Reitzda557aa2013-12-20 19:28:11 +01003402 reference = qdict_get_try_str(options, bdref_key);
3403 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003404 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003405 error_setg(errp, "A block device must be specified for \"%s\"",
3406 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003407 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003408 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003409 goto done;
3410 }
3411
Max Reitz5b363932016-05-17 16:41:31 +02003412 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003413 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003414 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003415 goto done;
3416 }
3417
Max Reitzda557aa2013-12-20 19:28:11 +01003418done:
3419 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003420 return bs;
3421}
3422
3423/*
3424 * Opens a disk image whose options are given as BlockdevRef in another block
3425 * device's options.
3426 *
3427 * If allow_none is true, no image will be opened if filename is false and no
3428 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3429 *
3430 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3431 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3432 * itself, all options starting with "${bdref_key}." are considered part of the
3433 * BlockdevRef.
3434 *
3435 * The BlockdevRef will be removed from the options QDict.
3436 */
3437BdrvChild *bdrv_open_child(const char *filename,
3438 QDict *options, const char *bdref_key,
3439 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003440 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003441 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003442 bool allow_none, Error **errp)
3443{
3444 BlockDriverState *bs;
3445
Max Reitzbd86fb92020-05-13 13:05:13 +02003446 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003447 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003448 if (bs == NULL) {
3449 return NULL;
3450 }
3451
Max Reitz258b7762020-05-13 13:05:15 +02003452 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3453 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003454}
3455
Max Reitzbd86fb92020-05-13 13:05:13 +02003456/*
3457 * TODO Future callers may need to specify parent/child_class in order for
3458 * option inheritance to work. Existing callers use it for the root node.
3459 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003460BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3461{
3462 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003463 QObject *obj = NULL;
3464 QDict *qdict = NULL;
3465 const char *reference = NULL;
3466 Visitor *v = NULL;
3467
3468 if (ref->type == QTYPE_QSTRING) {
3469 reference = ref->u.reference;
3470 } else {
3471 BlockdevOptions *options = &ref->u.definition;
3472 assert(ref->type == QTYPE_QDICT);
3473
3474 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003475 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003476 visit_complete(v, &obj);
3477
Max Reitz7dc847e2018-02-24 16:40:29 +01003478 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003479 qdict_flatten(qdict);
3480
3481 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3482 * compatibility with other callers) rather than what we want as the
3483 * real defaults. Apply the defaults here instead. */
3484 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3485 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3486 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003487 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3488
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003489 }
3490
Max Reitz272c02e2020-05-13 13:05:17 +02003491 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003492 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003493 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003494 visit_free(v);
3495 return bs;
3496}
3497
Max Reitz66836182016-05-17 16:41:27 +02003498static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3499 int flags,
3500 QDict *snapshot_options,
3501 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003502{
3503 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003504 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003505 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003506 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003507 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003508 int ret;
3509
3510 /* if snapshot, we create a temporary backing file and open it
3511 instead of opening 'filename' directly */
3512
3513 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003514 total_size = bdrv_getlength(bs);
3515 if (total_size < 0) {
3516 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003517 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003518 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003519
3520 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003521 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003522 if (ret < 0) {
3523 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003524 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003525 }
3526
Max Reitzef810432014-12-02 18:32:42 +01003527 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003528 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003529 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003530 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003531 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003532 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003533 error_prepend(errp, "Could not create temporary overlay '%s': ",
3534 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003535 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003536 }
3537
Kevin Wolf73176be2016-03-07 13:02:15 +01003538 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003539 qdict_put_str(snapshot_options, "file.driver", "file");
3540 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3541 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003542
Max Reitz5b363932016-05-17 16:41:31 +02003543 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003544 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003545 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003546 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003547 }
3548
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003549 ret = bdrv_append(bs_snapshot, bs, errp);
3550 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003551 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003552 goto out;
3553 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003554
3555out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003556 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003557 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003558 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003559}
3560
Max Reitzda557aa2013-12-20 19:28:11 +01003561/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003562 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003563 *
3564 * options is a QDict of options to pass to the block drivers, or NULL for an
3565 * empty set of options. The reference to the QDict belongs to the block layer
3566 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003567 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003568 *
3569 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3570 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003571 *
3572 * The reference parameter may be used to specify an existing block device which
3573 * should be opened. If specified, neither options nor a filename may be given,
3574 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003575 */
Max Reitz5b363932016-05-17 16:41:31 +02003576static BlockDriverState *bdrv_open_inherit(const char *filename,
3577 const char *reference,
3578 QDict *options, int flags,
3579 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003580 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003581 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003582 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003583{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003584 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003585 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003586 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003587 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003588 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003589 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003590 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003591 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003592 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003593 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003594
Max Reitzbd86fb92020-05-13 13:05:13 +02003595 assert(!child_class || !flags);
3596 assert(!child_class == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01003597
Max Reitzddf56362014-02-18 18:33:06 +01003598 if (reference) {
3599 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003600 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003601
Max Reitzddf56362014-02-18 18:33:06 +01003602 if (filename || options_non_empty) {
3603 error_setg(errp, "Cannot reference an existing block device with "
3604 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003605 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003606 }
3607
3608 bs = bdrv_lookup_bs(reference, reference, errp);
3609 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003610 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003611 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003612
Max Reitzddf56362014-02-18 18:33:06 +01003613 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003614 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003615 }
3616
Max Reitz5b363932016-05-17 16:41:31 +02003617 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003618
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003619 /* NULL means an empty set of options */
3620 if (options == NULL) {
3621 options = qdict_new();
3622 }
3623
Kevin Wolf145f5982015-05-08 16:15:03 +02003624 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003625 parse_json_protocol(options, &filename, &local_err);
3626 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003627 goto fail;
3628 }
3629
Kevin Wolf145f5982015-05-08 16:15:03 +02003630 bs->explicit_options = qdict_clone_shallow(options);
3631
Max Reitzbd86fb92020-05-13 13:05:13 +02003632 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003633 bool parent_is_format;
3634
3635 if (parent->drv) {
3636 parent_is_format = parent->drv->is_format;
3637 } else {
3638 /*
3639 * parent->drv is not set yet because this node is opened for
3640 * (potential) format probing. That means that @parent is going
3641 * to be a format node.
3642 */
3643 parent_is_format = true;
3644 }
3645
Kevin Wolfbddcec32015-04-09 18:47:50 +02003646 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003647 child_class->inherit_options(child_role, parent_is_format,
3648 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003649 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003650 }
3651
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003652 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003653 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003654 goto fail;
3655 }
3656
Markus Armbruster129c7d12017-03-30 19:43:12 +02003657 /*
3658 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3659 * Caution: getting a boolean member of @options requires care.
3660 * When @options come from -blockdev or blockdev_add, members are
3661 * typed according to the QAPI schema, but when they come from
3662 * -drive, they're all QString.
3663 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003664 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3665 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3666 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3667 } else {
3668 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003669 }
3670
3671 if (flags & BDRV_O_SNAPSHOT) {
3672 snapshot_options = qdict_new();
3673 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3674 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003675 /* Let bdrv_backing_options() override "read-only" */
3676 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003677 bdrv_inherited_options(BDRV_CHILD_COW, true,
3678 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003679 }
3680
Kevin Wolf62392eb2015-04-24 16:38:02 +02003681 bs->open_flags = flags;
3682 bs->options = options;
3683 options = qdict_clone_shallow(options);
3684
Kevin Wolf76c591b2014-06-04 14:19:44 +02003685 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003686 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003687 drvname = qdict_get_try_str(options, "driver");
3688 if (drvname) {
3689 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003690 if (!drv) {
3691 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003692 goto fail;
3693 }
3694 }
3695
3696 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003697
Markus Armbruster129c7d12017-03-30 19:43:12 +02003698 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003699 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003700 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3701 (backing && *backing == '\0'))
3702 {
Max Reitz4f7be282018-02-24 16:40:33 +01003703 if (backing) {
3704 warn_report("Use of \"backing\": \"\" is deprecated; "
3705 "use \"backing\": null instead");
3706 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003707 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003708 qdict_del(bs->explicit_options, "backing");
3709 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003710 qdict_del(options, "backing");
3711 }
3712
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003713 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003714 * probing, the block drivers will do their own bdrv_open_child() for the
3715 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003716 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003717 BlockDriverState *file_bs;
3718
3719 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003720 &child_of_bds, BDRV_CHILD_IMAGE,
3721 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003722 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003723 goto fail;
3724 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003725 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003726 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3727 * looking at the header to guess the image format. This works even
3728 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003729 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003730 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003731 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003732 if (local_err) {
3733 goto fail;
3734 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003735
Eric Blake46f5ac22017-04-27 16:58:17 -05003736 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003737 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003738 }
3739
Kevin Wolf76c591b2014-06-04 14:19:44 +02003740 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003741 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003742 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003743 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003744 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003745 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003746 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003747 /*
3748 * This option update would logically belong in bdrv_fill_options(),
3749 * but we first need to open bs->file for the probing to work, while
3750 * opening bs->file already requires the (mostly) final set of options
3751 * so that cache mode etc. can be inherited.
3752 *
3753 * Adding the driver later is somewhat ugly, but it's not an option
3754 * that would ever be inherited, so it's correct. We just need to make
3755 * sure to update both bs->options (which has the full effective
3756 * options for bs) and options (which has file.* already removed).
3757 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003758 qdict_put_str(bs->options, "driver", drv->format_name);
3759 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003760 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003761 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003762 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003763 }
3764
Max Reitz53a29512015-03-19 14:53:16 -04003765 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3766 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3767 /* file must be NULL if a protocol BDS is about to be created
3768 * (the inverse results in an error message from bdrv_open_common()) */
3769 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3770
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003771 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003772 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003773 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003774 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003775 }
3776
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003777 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003778 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003779 file = NULL;
3780 }
3781
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003782 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003783 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003784 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003785 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003786 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003787 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003788 }
3789
Alberto Garcia50196d72018-09-06 12:37:03 +03003790 /* Remove all children options and references
3791 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003792 QLIST_FOREACH(child, &bs->children, next) {
3793 char *child_key_dot;
3794 child_key_dot = g_strdup_printf("%s.", child->name);
3795 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3796 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003797 qdict_del(bs->explicit_options, child->name);
3798 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003799 g_free(child_key_dot);
3800 }
3801
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003802 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003803 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003804 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003805 if (flags & BDRV_O_PROTOCOL) {
3806 error_setg(errp, "Block protocol '%s' doesn't support the option "
3807 "'%s'", drv->format_name, entry->key);
3808 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003809 error_setg(errp,
3810 "Block format '%s' does not support the option '%s'",
3811 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003812 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003813
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003814 goto close_and_fail;
3815 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003816
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003817 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003818
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003819 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003820 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003821
3822 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3823 * temporary snapshot afterwards. */
3824 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003825 BlockDriverState *snapshot_bs;
3826 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3827 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003828 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003829 if (local_err) {
3830 goto close_and_fail;
3831 }
Max Reitz5b363932016-05-17 16:41:31 +02003832 /* We are not going to return bs but the overlay on top of it
3833 * (snapshot_bs); thus, we have to drop the strong reference to bs
3834 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3835 * though, because the overlay still has a reference to it. */
3836 bdrv_unref(bs);
3837 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003838 }
3839
Max Reitz5b363932016-05-17 16:41:31 +02003840 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003841
Kevin Wolf8bfea152014-04-11 19:16:36 +02003842fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003843 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003844 qobject_unref(snapshot_options);
3845 qobject_unref(bs->explicit_options);
3846 qobject_unref(bs->options);
3847 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003848 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003849 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003850 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003851 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003852 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003853
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003854close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02003855 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003856 qobject_unref(snapshot_options);
3857 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003858 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003859 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003860}
3861
Max Reitz5b363932016-05-17 16:41:31 +02003862BlockDriverState *bdrv_open(const char *filename, const char *reference,
3863 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02003864{
Max Reitz5b363932016-05-17 16:41:31 +02003865 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02003866 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003867}
3868
Alberto Garciafaf116b2019-03-12 18:48:49 +02003869/* Return true if the NULL-terminated @list contains @str */
3870static bool is_str_in_list(const char *str, const char *const *list)
3871{
3872 if (str && list) {
3873 int i;
3874 for (i = 0; list[i] != NULL; i++) {
3875 if (!strcmp(str, list[i])) {
3876 return true;
3877 }
3878 }
3879 }
3880 return false;
3881}
3882
3883/*
3884 * Check that every option set in @bs->options is also set in
3885 * @new_opts.
3886 *
3887 * Options listed in the common_options list and in
3888 * @bs->drv->mutable_opts are skipped.
3889 *
3890 * Return 0 on success, otherwise return -EINVAL and set @errp.
3891 */
3892static int bdrv_reset_options_allowed(BlockDriverState *bs,
3893 const QDict *new_opts, Error **errp)
3894{
3895 const QDictEntry *e;
3896 /* These options are common to all block drivers and are handled
3897 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3898 const char *const common_options[] = {
3899 "node-name", "discard", "cache.direct", "cache.no-flush",
3900 "read-only", "auto-read-only", "detect-zeroes", NULL
3901 };
3902
3903 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3904 if (!qdict_haskey(new_opts, e->key) &&
3905 !is_str_in_list(e->key, common_options) &&
3906 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3907 error_setg(errp, "Option '%s' cannot be reset "
3908 "to its default value", e->key);
3909 return -EINVAL;
3910 }
3911 }
3912
3913 return 0;
3914}
3915
Jeff Codye971aa12012-09-20 15:13:19 -04003916/*
Alberto Garciacb828c32019-03-12 18:48:47 +02003917 * Returns true if @child can be reached recursively from @bs
3918 */
3919static bool bdrv_recurse_has_child(BlockDriverState *bs,
3920 BlockDriverState *child)
3921{
3922 BdrvChild *c;
3923
3924 if (bs == child) {
3925 return true;
3926 }
3927
3928 QLIST_FOREACH(c, &bs->children, next) {
3929 if (bdrv_recurse_has_child(c->bs, child)) {
3930 return true;
3931 }
3932 }
3933
3934 return false;
3935}
3936
3937/*
Jeff Codye971aa12012-09-20 15:13:19 -04003938 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3939 * reopen of multiple devices.
3940 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003941 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04003942 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3943 * be created and initialized. This newly created BlockReopenQueue should be
3944 * passed back in for subsequent calls that are intended to be of the same
3945 * atomic 'set'.
3946 *
3947 * bs is the BlockDriverState to add to the reopen queue.
3948 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003949 * options contains the changed options for the associated bs
3950 * (the BlockReopenQueue takes ownership)
3951 *
Jeff Codye971aa12012-09-20 15:13:19 -04003952 * flags contains the open flags for the associated bs
3953 *
3954 * returns a pointer to bs_queue, which is either the newly allocated
3955 * bs_queue, or the existing bs_queue being used.
3956 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01003957 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04003958 */
Kevin Wolf28518102015-05-08 17:07:31 +02003959static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3960 BlockDriverState *bs,
3961 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003962 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02003963 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02003964 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02003965 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02003966 int parent_flags,
3967 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04003968{
3969 assert(bs != NULL);
3970
3971 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02003972 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003973 QDict *old_options, *explicit_options, *options_copy;
3974 int flags;
3975 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02003976
Kevin Wolf1a63a902017-12-06 20:24:44 +01003977 /* Make sure that the caller remembered to use a drained section. This is
3978 * important to avoid graph changes between the recursive queuing here and
3979 * bdrv_reopen_multiple(). */
3980 assert(bs->quiesce_counter > 0);
3981
Jeff Codye971aa12012-09-20 15:13:19 -04003982 if (bs_queue == NULL) {
3983 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003984 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04003985 }
3986
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003987 if (!options) {
3988 options = qdict_new();
3989 }
3990
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003991 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003992 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003993 if (bs == bs_entry->state.bs) {
3994 break;
3995 }
3996 }
3997
Kevin Wolf28518102015-05-08 17:07:31 +02003998 /*
3999 * Precedence of options:
4000 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004001 * 2. Retained from explicitly set options of bs
4002 * 3. Inherited from parent node
4003 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004004 */
4005
Kevin Wolf145f5982015-05-08 16:15:03 +02004006 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004007 if (bs_entry || keep_old_opts) {
4008 old_options = qdict_clone_shallow(bs_entry ?
4009 bs_entry->state.explicit_options :
4010 bs->explicit_options);
4011 bdrv_join_options(bs, options, old_options);
4012 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004013 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004014
4015 explicit_options = qdict_clone_shallow(options);
4016
Kevin Wolf28518102015-05-08 17:07:31 +02004017 /* Inherit from parent node */
4018 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004019 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004020 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004021 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004022 } else {
4023 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004024 }
4025
Alberto Garcia077e8e22019-03-12 18:48:44 +02004026 if (keep_old_opts) {
4027 /* Old values are used for options that aren't set yet */
4028 old_options = qdict_clone_shallow(bs->options);
4029 bdrv_join_options(bs, options, old_options);
4030 qobject_unref(old_options);
4031 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004032
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004033 /* We have the final set of options so let's update the flags */
4034 options_copy = qdict_clone_shallow(options);
4035 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4036 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4037 update_flags_from_options(&flags, opts);
4038 qemu_opts_del(opts);
4039 qobject_unref(options_copy);
4040
Kevin Wolffd452022017-08-03 17:02:59 +02004041 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004042 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004043 if (flags & BDRV_O_RDWR) {
4044 flags |= BDRV_O_ALLOW_RDWR;
4045 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004046
Kevin Wolf1857c972017-09-14 14:53:46 +02004047 if (!bs_entry) {
4048 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004049 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004050 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004051 qobject_unref(bs_entry->state.options);
4052 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004053 }
4054
4055 bs_entry->state.bs = bs;
4056 bs_entry->state.options = options;
4057 bs_entry->state.explicit_options = explicit_options;
4058 bs_entry->state.flags = flags;
4059
Alberto Garcia85466322019-03-12 18:48:45 +02004060 /*
4061 * If keep_old_opts is false then it means that unspecified
4062 * options must be reset to their original value. We don't allow
4063 * resetting 'backing' but we need to know if the option is
4064 * missing in order to decide if we have to return an error.
4065 */
4066 if (!keep_old_opts) {
4067 bs_entry->state.backing_missing =
4068 !qdict_haskey(options, "backing") &&
4069 !qdict_haskey(options, "backing.driver");
4070 }
4071
Kevin Wolf67251a32015-04-09 18:54:04 +02004072 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004073 QDict *new_child_options = NULL;
4074 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004075
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004076 /* reopen can only change the options of block devices that were
4077 * implicitly created and inherited options. For other (referenced)
4078 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004079 if (child->bs->inherits_from != bs) {
4080 continue;
4081 }
4082
Alberto Garcia85466322019-03-12 18:48:45 +02004083 /* Check if the options contain a child reference */
4084 if (qdict_haskey(options, child->name)) {
4085 const char *childref = qdict_get_try_str(options, child->name);
4086 /*
4087 * The current child must not be reopened if the child
4088 * reference is null or points to a different node.
4089 */
4090 if (g_strcmp0(childref, child->bs->node_name)) {
4091 continue;
4092 }
4093 /*
4094 * If the child reference points to the current child then
4095 * reopen it with its existing set of options (note that
4096 * it can still inherit new options from the parent).
4097 */
4098 child_keep_old = true;
4099 } else {
4100 /* Extract child options ("child-name.*") */
4101 char *child_key_dot = g_strdup_printf("%s.", child->name);
4102 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4103 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4104 g_free(child_key_dot);
4105 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004106
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004107 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004108 child->klass, child->role, bs->drv->is_format,
4109 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004110 }
4111
Jeff Codye971aa12012-09-20 15:13:19 -04004112 return bs_queue;
4113}
4114
Kevin Wolf28518102015-05-08 17:07:31 +02004115BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4116 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004117 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004118{
Max Reitz3cdc69d2020-05-13 13:05:18 +02004119 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4120 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004121}
4122
Jeff Codye971aa12012-09-20 15:13:19 -04004123/*
4124 * Reopen multiple BlockDriverStates atomically & transactionally.
4125 *
4126 * The queue passed in (bs_queue) must have been built up previous
4127 * via bdrv_reopen_queue().
4128 *
4129 * Reopens all BDS specified in the queue, with the appropriate
4130 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004131 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004132 * data cleaned up.
4133 *
4134 * If all devices prepare successfully, then the changes are committed
4135 * to all devices.
4136 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004137 * All affected nodes must be drained between bdrv_reopen_queue() and
4138 * bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004139 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004140int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004141{
4142 int ret = -1;
4143 BlockReopenQueueEntry *bs_entry, *next;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004144 Transaction *tran = tran_new();
4145 g_autoptr(GHashTable) found = NULL;
4146 g_autoptr(GSList) refresh_list = NULL;
Jeff Codye971aa12012-09-20 15:13:19 -04004147
4148 assert(bs_queue != NULL);
4149
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004150 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Vladimir Sementsov-Ogievskiya2aabf82021-04-28 18:17:57 +03004151 ret = bdrv_flush(bs_entry->state.bs);
4152 if (ret < 0) {
4153 error_setg_errno(errp, -ret, "Error flushing drive");
4154 goto cleanup;
4155 }
4156 }
4157
4158 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004159 assert(bs_entry->state.bs->quiesce_counter > 0);
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004160 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4161 if (ret < 0) {
4162 goto abort;
Jeff Codye971aa12012-09-20 15:13:19 -04004163 }
4164 bs_entry->prepared = true;
4165 }
4166
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004167 found = g_hash_table_new(NULL, NULL);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004168 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004169 BDRVReopenState *state = &bs_entry->state;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004170
4171 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4172 if (state->old_backing_bs) {
4173 refresh_list = bdrv_topological_dfs(refresh_list, found,
4174 state->old_backing_bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004175 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004176 }
4177
4178 /*
4179 * Note that file-posix driver rely on permission update done during reopen
4180 * (even if no permission changed), because it wants "new" permissions for
4181 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4182 * in raw_reopen_prepare() which is called with "old" permissions.
4183 */
4184 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4185 if (ret < 0) {
4186 goto abort;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004187 }
4188
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004189 /*
4190 * If we reach this point, we have success and just need to apply the
4191 * changes.
4192 *
4193 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4194 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4195 * children are usually goes after parents in reopen-queue, so go from last
4196 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004197 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004198 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Jeff Codye971aa12012-09-20 15:13:19 -04004199 bdrv_reopen_commit(&bs_entry->state);
4200 }
4201
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004202 tran_commit(tran);
4203
4204 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4205 BlockDriverState *bs = bs_entry->state.bs;
4206
4207 if (bs->drv->bdrv_reopen_commit_post) {
4208 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4209 }
4210 }
4211
Jeff Codye971aa12012-09-20 15:13:19 -04004212 ret = 0;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004213 goto cleanup;
4214
4215abort:
4216 tran_abort(tran);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004217 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004218 if (bs_entry->prepared) {
4219 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004220 }
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004221 qobject_unref(bs_entry->state.explicit_options);
4222 qobject_unref(bs_entry->state.options);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004223 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004224
Jeff Codye971aa12012-09-20 15:13:19 -04004225cleanup:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004226 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Jeff Codye971aa12012-09-20 15:13:19 -04004227 g_free(bs_entry);
4228 }
4229 g_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004230
Jeff Codye971aa12012-09-20 15:13:19 -04004231 return ret;
4232}
4233
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004234int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4235 Error **errp)
4236{
4237 int ret;
4238 BlockReopenQueue *queue;
4239 QDict *opts = qdict_new();
4240
4241 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4242
4243 bdrv_subtree_drained_begin(bs);
Alberto Garcia077e8e22019-03-12 18:48:44 +02004244 queue = bdrv_reopen_queue(NULL, bs, opts, true);
Alberto Garcia5019aec2019-03-12 18:48:50 +02004245 ret = bdrv_reopen_multiple(queue, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004246 bdrv_subtree_drained_end(bs);
4247
4248 return ret;
4249}
4250
Kevin Wolf1de6b452020-03-06 15:14:13 +01004251static bool bdrv_reopen_can_attach(BlockDriverState *parent,
4252 BdrvChild *child,
4253 BlockDriverState *new_child,
4254 Error **errp)
4255{
4256 AioContext *parent_ctx = bdrv_get_aio_context(parent);
4257 AioContext *child_ctx = bdrv_get_aio_context(new_child);
4258 GSList *ignore;
4259 bool ret;
4260
4261 ignore = g_slist_prepend(NULL, child);
4262 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
4263 g_slist_free(ignore);
4264 if (ret) {
4265 return ret;
4266 }
4267
4268 ignore = g_slist_prepend(NULL, child);
4269 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
4270 g_slist_free(ignore);
4271 return ret;
4272}
4273
Jeff Codye971aa12012-09-20 15:13:19 -04004274/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004275 * Take a BDRVReopenState and check if the value of 'backing' in the
4276 * reopen_state->options QDict is valid or not.
4277 *
4278 * If 'backing' is missing from the QDict then return 0.
4279 *
4280 * If 'backing' contains the node name of the backing file of
4281 * reopen_state->bs then return 0.
4282 *
4283 * If 'backing' contains a different node name (or is null) then check
4284 * whether the current backing file can be replaced with the new one.
4285 * If that's the case then reopen_state->replace_backing_bs is set to
4286 * true and reopen_state->new_backing_bs contains a pointer to the new
4287 * backing BlockDriverState (or NULL).
4288 *
4289 * Return 0 on success, otherwise return < 0 and set @errp.
4290 */
4291static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004292 Transaction *set_backings_tran,
Alberto Garciacb828c32019-03-12 18:48:47 +02004293 Error **errp)
4294{
4295 BlockDriverState *bs = reopen_state->bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004296 BlockDriverState *overlay_bs, *below_bs, *new_backing_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004297 QObject *value;
4298 const char *str;
4299
4300 value = qdict_get(reopen_state->options, "backing");
4301 if (value == NULL) {
4302 return 0;
4303 }
4304
4305 switch (qobject_type(value)) {
4306 case QTYPE_QNULL:
4307 new_backing_bs = NULL;
4308 break;
4309 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004310 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciacb828c32019-03-12 18:48:47 +02004311 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4312 if (new_backing_bs == NULL) {
4313 return -EINVAL;
4314 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4315 error_setg(errp, "Making '%s' a backing file of '%s' "
4316 "would create a cycle", str, bs->node_name);
4317 return -EINVAL;
4318 }
4319 break;
4320 default:
4321 /* 'backing' does not allow any other data type */
4322 g_assert_not_reached();
4323 }
4324
4325 /*
Kevin Wolf1de6b452020-03-06 15:14:13 +01004326 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4327 * bdrv_reopen_commit() won't fail.
Alberto Garciacb828c32019-03-12 18:48:47 +02004328 */
4329 if (new_backing_bs) {
Kevin Wolf1de6b452020-03-06 15:14:13 +01004330 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004331 return -EINVAL;
4332 }
4333 }
4334
4335 /*
Max Reitz1d42f482019-06-12 17:24:39 +02004336 * Ensure that @bs can really handle backing files, because we are
4337 * about to give it one (or swap the existing one)
4338 */
4339 if (bs->drv->is_filter) {
4340 /* Filters always have a file or a backing child */
4341 if (!bs->backing) {
4342 error_setg(errp, "'%s' is a %s filter node that does not support a "
4343 "backing child", bs->node_name, bs->drv->format_name);
4344 return -EINVAL;
4345 }
4346 } else if (!bs->drv->supports_backing) {
4347 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
4348 "files", bs->drv->format_name, bs->node_name);
4349 return -EINVAL;
4350 }
4351
4352 /*
Alberto Garciacb828c32019-03-12 18:48:47 +02004353 * Find the "actual" backing file by skipping all links that point
4354 * to an implicit node, if any (e.g. a commit filter node).
Max Reitz1d42f482019-06-12 17:24:39 +02004355 * We cannot use any of the bdrv_skip_*() functions here because
4356 * those return the first explicit node, while we are looking for
4357 * its overlay here.
Alberto Garciacb828c32019-03-12 18:48:47 +02004358 */
4359 overlay_bs = bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004360 for (below_bs = bdrv_filter_or_cow_bs(overlay_bs);
4361 below_bs && below_bs->implicit;
4362 below_bs = bdrv_filter_or_cow_bs(overlay_bs))
4363 {
4364 overlay_bs = below_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004365 }
4366
4367 /* If we want to replace the backing file we need some extra checks */
Max Reitz1d42f482019-06-12 17:24:39 +02004368 if (new_backing_bs != bdrv_filter_or_cow_bs(overlay_bs)) {
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004369 int ret;
4370
Alberto Garciacb828c32019-03-12 18:48:47 +02004371 /* Check for implicit nodes between bs and its backing file */
4372 if (bs != overlay_bs) {
4373 error_setg(errp, "Cannot change backing link if '%s' has "
4374 "an implicit backing file", bs->node_name);
4375 return -EPERM;
4376 }
Max Reitz1d42f482019-06-12 17:24:39 +02004377 /*
4378 * Check if the backing link that we want to replace is frozen.
4379 * Note that
4380 * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4381 * because we know that overlay_bs == bs, and that @bs
4382 * either is a filter that uses ->backing or a COW format BDS
4383 * with bs->drv->supports_backing == true.
4384 */
4385 if (bdrv_is_backing_chain_frozen(overlay_bs,
4386 child_bs(overlay_bs->backing), errp))
4387 {
Alberto Garciacb828c32019-03-12 18:48:47 +02004388 return -EPERM;
4389 }
4390 reopen_state->replace_backing_bs = true;
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004391 reopen_state->old_backing_bs = bs->backing ? bs->backing->bs : NULL;
4392 ret = bdrv_set_backing_noperm(bs, new_backing_bs, set_backings_tran,
4393 errp);
4394 if (ret < 0) {
4395 return ret;
Alberto Garciacb828c32019-03-12 18:48:47 +02004396 }
4397 }
4398
4399 return 0;
4400}
4401
4402/*
Jeff Codye971aa12012-09-20 15:13:19 -04004403 * Prepares a BlockDriverState for reopen. All changes are staged in the
4404 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4405 * the block driver layer .bdrv_reopen_prepare()
4406 *
4407 * bs is the BlockDriverState to reopen
4408 * flags are the new open flags
4409 * queue is the reopen queue
4410 *
4411 * Returns 0 on success, non-zero on error. On error errp will be set
4412 * as well.
4413 *
4414 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4415 * It is the responsibility of the caller to then call the abort() or
4416 * commit() for any other BDS that have been left in a prepare() state
4417 *
4418 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004419static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004420 BlockReopenQueue *queue,
4421 Transaction *set_backings_tran, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004422{
4423 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004424 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004425 Error *local_err = NULL;
4426 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004427 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004428 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004429 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004430 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004431 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004432
4433 assert(reopen_state != NULL);
4434 assert(reopen_state->bs->drv != NULL);
4435 drv = reopen_state->bs->drv;
4436
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004437 /* This function and each driver's bdrv_reopen_prepare() remove
4438 * entries from reopen_state->options as they are processed, so
4439 * we need to make a copy of the original QDict. */
4440 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4441
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004442 /* Process generic block layer options */
4443 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004444 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004445 ret = -EINVAL;
4446 goto error;
4447 }
4448
Alberto Garciae6d79c42018-11-12 16:00:47 +02004449 /* This was already called in bdrv_reopen_queue_child() so the flags
4450 * are up-to-date. This time we simply want to remove the options from
4451 * QemuOpts in order to indicate that they have been processed. */
4452 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004453 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004454 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004455
Alberto Garcia415bbca2018-10-03 13:23:13 +03004456 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004457 if (discard != NULL) {
4458 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4459 error_setg(errp, "Invalid discard option");
4460 ret = -EINVAL;
4461 goto error;
4462 }
4463 }
4464
Alberto Garcia543770b2018-09-06 12:37:09 +03004465 reopen_state->detect_zeroes =
4466 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4467 if (local_err) {
4468 error_propagate(errp, local_err);
4469 ret = -EINVAL;
4470 goto error;
4471 }
4472
Alberto Garcia57f9db92018-09-06 12:37:06 +03004473 /* All other options (including node-name and driver) must be unchanged.
4474 * Put them back into the QDict, so that they are checked at the end
4475 * of this function. */
4476 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004477
Jeff Cody3d8ce172017-04-07 16:55:30 -04004478 /* If we are to stay read-only, do not allow permission change
4479 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4480 * not set, or if the BDS still has copy_on_read enabled */
4481 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004482 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004483 if (local_err) {
4484 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004485 goto error;
4486 }
4487
Jeff Codye971aa12012-09-20 15:13:19 -04004488 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004489 /*
4490 * If a driver-specific option is missing, it means that we
4491 * should reset it to its default value.
4492 * But not all options allow that, so we need to check it first.
4493 */
4494 ret = bdrv_reset_options_allowed(reopen_state->bs,
4495 reopen_state->options, errp);
4496 if (ret) {
4497 goto error;
4498 }
4499
Jeff Codye971aa12012-09-20 15:13:19 -04004500 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4501 if (ret) {
4502 if (local_err != NULL) {
4503 error_propagate(errp, local_err);
4504 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004505 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004506 error_setg(errp, "failed while preparing to reopen image '%s'",
4507 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004508 }
4509 goto error;
4510 }
4511 } else {
4512 /* It is currently mandatory to have a bdrv_reopen_prepare()
4513 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004514 error_setg(errp, "Block format '%s' used by node '%s' "
4515 "does not support reopening files", drv->format_name,
4516 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004517 ret = -1;
4518 goto error;
4519 }
4520
Max Reitz9ad08c42018-11-16 17:45:24 +01004521 drv_prepared = true;
4522
Alberto Garciabacd9b82019-03-12 18:48:46 +02004523 /*
4524 * We must provide the 'backing' option if the BDS has a backing
4525 * file or if the image file has a backing file name as part of
4526 * its metadata. Otherwise the 'backing' option can be omitted.
4527 */
4528 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004529 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004530 error_setg(errp, "backing is missing for '%s'",
4531 reopen_state->bs->node_name);
4532 ret = -EINVAL;
4533 goto error;
4534 }
4535
Alberto Garciacb828c32019-03-12 18:48:47 +02004536 /*
4537 * Allow changing the 'backing' option. The new value can be
4538 * either a reference to an existing node (using its node name)
4539 * or NULL to simply detach the current backing file.
4540 */
Vladimir Sementsov-Ogievskiy72373e42021-04-28 18:17:58 +03004541 ret = bdrv_reopen_parse_backing(reopen_state, set_backings_tran, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004542 if (ret < 0) {
4543 goto error;
4544 }
4545 qdict_del(reopen_state->options, "backing");
4546
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004547 /* Options that are not handled are only okay if they are unchanged
4548 * compared to the old state. It is expected that some options are only
4549 * used for the initial open, but not reopen (e.g. filename) */
4550 if (qdict_size(reopen_state->options)) {
4551 const QDictEntry *entry = qdict_first(reopen_state->options);
4552
4553 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004554 QObject *new = entry->value;
4555 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004556
Alberto Garciadb905282018-09-06 12:37:05 +03004557 /* Allow child references (child_name=node_name) as long as they
4558 * point to the current child (i.e. everything stays the same). */
4559 if (qobject_type(new) == QTYPE_QSTRING) {
4560 BdrvChild *child;
4561 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4562 if (!strcmp(child->name, entry->key)) {
4563 break;
4564 }
4565 }
4566
4567 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004568 if (!strcmp(child->bs->node_name,
4569 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004570 continue; /* Found child with this name, skip option */
4571 }
4572 }
4573 }
4574
Max Reitz54fd1b02017-11-14 19:01:26 +01004575 /*
4576 * TODO: When using -drive to specify blockdev options, all values
4577 * will be strings; however, when using -blockdev, blockdev-add or
4578 * filenames using the json:{} pseudo-protocol, they will be
4579 * correctly typed.
4580 * In contrast, reopening options are (currently) always strings
4581 * (because you can only specify them through qemu-io; all other
4582 * callers do not specify any options).
4583 * Therefore, when using anything other than -drive to create a BDS,
4584 * this cannot detect non-string options as unchanged, because
4585 * qobject_is_equal() always returns false for objects of different
4586 * type. In the future, this should be remedied by correctly typing
4587 * all options. For now, this is not too big of an issue because
4588 * the user can simply omit options which cannot be changed anyway,
4589 * so they will stay unchanged.
4590 */
4591 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004592 error_setg(errp, "Cannot change the option '%s'", entry->key);
4593 ret = -EINVAL;
4594 goto error;
4595 }
4596 } while ((entry = qdict_next(reopen_state->options, entry)));
4597 }
4598
Jeff Codye971aa12012-09-20 15:13:19 -04004599 ret = 0;
4600
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004601 /* Restore the original reopen_state->options QDict */
4602 qobject_unref(reopen_state->options);
4603 reopen_state->options = qobject_ref(orig_reopen_opts);
4604
Jeff Codye971aa12012-09-20 15:13:19 -04004605error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004606 if (ret < 0 && drv_prepared) {
4607 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4608 * call drv->bdrv_reopen_abort() before signaling an error
4609 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4610 * when the respective bdrv_reopen_prepare() has failed) */
4611 if (drv->bdrv_reopen_abort) {
4612 drv->bdrv_reopen_abort(reopen_state);
4613 }
4614 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004615 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004616 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004617 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004618 return ret;
4619}
4620
4621/*
4622 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4623 * makes them final by swapping the staging BlockDriverState contents into
4624 * the active BlockDriverState contents.
4625 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004626static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004627{
4628 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004629 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004630 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004631
4632 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004633 bs = reopen_state->bs;
4634 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004635 assert(drv != NULL);
4636
4637 /* If there are any driver level actions to take */
4638 if (drv->bdrv_reopen_commit) {
4639 drv->bdrv_reopen_commit(reopen_state);
4640 }
4641
4642 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004643 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004644 qobject_unref(bs->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004645
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004646 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004647 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004648 bs->open_flags = reopen_state->flags;
4649 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
Alberto Garcia543770b2018-09-06 12:37:09 +03004650 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004651
Alberto Garciacb828c32019-03-12 18:48:47 +02004652 if (reopen_state->replace_backing_bs) {
4653 qdict_del(bs->explicit_options, "backing");
4654 qdict_del(bs->options, "backing");
4655 }
4656
Alberto Garcia50196d72018-09-06 12:37:03 +03004657 /* Remove child references from bs->options and bs->explicit_options.
4658 * Child options were already removed in bdrv_reopen_queue_child() */
4659 QLIST_FOREACH(child, &bs->children, next) {
4660 qdict_del(bs->explicit_options, child->name);
4661 qdict_del(bs->options, child->name);
4662 }
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03004663 bdrv_refresh_limits(bs, NULL, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004664}
4665
4666/*
4667 * Abort the reopen, and delete and free the staged changes in
4668 * reopen_state
4669 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004670static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004671{
4672 BlockDriver *drv;
4673
4674 assert(reopen_state != NULL);
4675 drv = reopen_state->bs->drv;
4676 assert(drv != NULL);
4677
4678 if (drv->bdrv_reopen_abort) {
4679 drv->bdrv_reopen_abort(reopen_state);
4680 }
4681}
4682
4683
Max Reitz64dff522016-01-29 16:36:10 +01004684static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004685{
Max Reitz33384422014-06-20 21:57:33 +02004686 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004687 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004688
Max Reitz30f55fb2016-05-17 16:41:32 +02004689 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004690
Paolo Bonzinifc272912015-12-23 11:48:24 +01004691 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004692 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004693 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004694
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004695 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004696 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004697 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004698 bs->drv->bdrv_close(bs);
4699 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004700 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004701 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004702
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004703 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004704 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004705 }
4706
Alberto Garciadd4118c2019-05-13 16:46:17 +03004707 bs->backing = NULL;
4708 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004709 g_free(bs->opaque);
4710 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004711 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004712 bs->backing_file[0] = '\0';
4713 bs->backing_format[0] = '\0';
4714 bs->total_sectors = 0;
4715 bs->encrypted = false;
4716 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004717 qobject_unref(bs->options);
4718 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004719 bs->options = NULL;
4720 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004721 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004722 bs->full_open_options = NULL;
4723
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004724 bdrv_release_named_dirty_bitmaps(bs);
4725 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4726
Max Reitz33384422014-06-20 21:57:33 +02004727 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4728 g_free(ban);
4729 }
4730 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004731 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004732
4733 /*
4734 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4735 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4736 * gets called.
4737 */
4738 if (bs->quiesce_counter) {
4739 bdrv_drain_all_end_quiesce(bs);
4740 }
bellardb3380822004-03-14 21:38:54 +00004741}
4742
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004743void bdrv_close_all(void)
4744{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004745 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004746
Max Reitzca9bd242016-01-29 16:36:14 +01004747 /* Drop references from requests still in flight, such as canceled block
4748 * jobs whose AIO context has not been polled yet */
4749 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004750
Max Reitzca9bd242016-01-29 16:36:14 +01004751 blk_remove_all_bs();
4752 blockdev_close_all_bdrv_states();
4753
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004754 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004755}
4756
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004757static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004758{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004759 GQueue *queue;
4760 GHashTable *found;
4761 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004762
Max Reitzbd86fb92020-05-13 13:05:13 +02004763 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004764 return false;
4765 }
4766
Max Reitzec9f10f2018-06-13 20:18:15 +02004767 /* If the child @c belongs to the BDS @to, replacing the current
4768 * c->bs by @to would mean to create a loop.
4769 *
4770 * Such a case occurs when appending a BDS to a backing chain.
4771 * For instance, imagine the following chain:
4772 *
4773 * guest device -> node A -> further backing chain...
4774 *
4775 * Now we create a new BDS B which we want to put on top of this
4776 * chain, so we first attach A as its backing node:
4777 *
4778 * node B
4779 * |
4780 * v
4781 * guest device -> node A -> further backing chain...
4782 *
4783 * Finally we want to replace A by B. When doing that, we want to
4784 * replace all pointers to A by pointers to B -- except for the
4785 * pointer from B because (1) that would create a loop, and (2)
4786 * that pointer should simply stay intact:
4787 *
4788 * guest device -> node B
4789 * |
4790 * v
4791 * node A -> further backing chain...
4792 *
4793 * In general, when replacing a node A (c->bs) by a node B (@to),
4794 * if A is a child of B, that means we cannot replace A by B there
4795 * because that would create a loop. Silently detaching A from B
4796 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004797 * place there is the most sensible choice.
4798 *
4799 * We would also create a loop in any cases where @c is only
4800 * indirectly referenced by @to. Prevent this by returning false
4801 * if @c is found (by breadth-first search) anywhere in the whole
4802 * subtree of @to.
4803 */
4804
4805 ret = true;
4806 found = g_hash_table_new(NULL, NULL);
4807 g_hash_table_add(found, to);
4808 queue = g_queue_new();
4809 g_queue_push_tail(queue, to);
4810
4811 while (!g_queue_is_empty(queue)) {
4812 BlockDriverState *v = g_queue_pop_head(queue);
4813 BdrvChild *c2;
4814
4815 QLIST_FOREACH(c2, &v->children, next) {
4816 if (c2 == c) {
4817 ret = false;
4818 break;
4819 }
4820
4821 if (g_hash_table_contains(found, c2->bs)) {
4822 continue;
4823 }
4824
4825 g_queue_push_tail(queue, c2->bs);
4826 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004827 }
4828 }
4829
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004830 g_queue_free(queue);
4831 g_hash_table_destroy(found);
4832
4833 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004834}
4835
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004836typedef struct BdrvRemoveFilterOrCowChild {
4837 BdrvChild *child;
4838 bool is_backing;
4839} BdrvRemoveFilterOrCowChild;
4840
4841static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
4842{
4843 BdrvRemoveFilterOrCowChild *s = opaque;
4844 BlockDriverState *parent_bs = s->child->opaque;
4845
4846 QLIST_INSERT_HEAD(&parent_bs->children, s->child, next);
4847 if (s->is_backing) {
4848 parent_bs->backing = s->child;
4849 } else {
4850 parent_bs->file = s->child;
4851 }
4852
4853 /*
4854 * We don't have to restore child->bs here to undo bdrv_replace_child()
4855 * because that function is transactionable and it registered own completion
4856 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
4857 * called automatically.
4858 */
4859}
4860
4861static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
4862{
4863 BdrvRemoveFilterOrCowChild *s = opaque;
4864
4865 bdrv_child_free(s->child);
4866}
4867
4868static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
4869 .abort = bdrv_remove_filter_or_cow_child_abort,
4870 .commit = bdrv_remove_filter_or_cow_child_commit,
4871 .clean = g_free,
4872};
4873
4874/*
4875 * A function to remove backing-chain child of @bs if exists: cow child for
4876 * format nodes (always .backing) and filter child for filters (may be .file or
4877 * .backing)
4878 */
Vladimir Sementsov-Ogievskiy46541ee2021-04-28 18:17:50 +03004879static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
4880 Transaction *tran)
4881{
4882 BdrvRemoveFilterOrCowChild *s;
4883 BdrvChild *child = bdrv_filter_or_cow_child(bs);
4884
4885 if (!child) {
4886 return;
4887 }
4888
4889 if (child->bs) {
4890 bdrv_replace_child_safe(child, NULL, tran);
4891 }
4892
4893 s = g_new(BdrvRemoveFilterOrCowChild, 1);
4894 *s = (BdrvRemoveFilterOrCowChild) {
4895 .child = child,
4896 .is_backing = (child == bs->backing),
4897 };
4898 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
4899
4900 QLIST_SAFE_REMOVE(child, next);
4901 if (s->is_backing) {
4902 bs->backing = NULL;
4903 } else {
4904 bs->file = NULL;
4905 }
4906}
4907
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004908static int bdrv_replace_node_noperm(BlockDriverState *from,
4909 BlockDriverState *to,
4910 bool auto_skip, Transaction *tran,
4911 Error **errp)
4912{
4913 BdrvChild *c, *next;
4914
4915 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4916 assert(c->bs == from);
4917 if (!should_update_child(c, to)) {
4918 if (auto_skip) {
4919 continue;
4920 }
4921 error_setg(errp, "Should not change '%s' link to '%s'",
4922 c->name, from->node_name);
4923 return -EINVAL;
4924 }
4925 if (c->frozen) {
4926 error_setg(errp, "Cannot change '%s' link to '%s'",
4927 c->name, from->node_name);
4928 return -EPERM;
4929 }
4930 bdrv_replace_child_safe(c, to, tran);
4931 }
4932
4933 return 0;
4934}
4935
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004936/*
4937 * With auto_skip=true bdrv_replace_node_common skips updating from parents
4938 * if it creates a parent-child relation loop or if parent is block-job.
4939 *
4940 * With auto_skip=false the error is returned if from has a parent which should
4941 * not be updated.
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004942 *
4943 * With @detach_subchain=true @to must be in a backing chain of @from. In this
4944 * case backing link of the cow-parent of @to is removed.
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004945 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004946static int bdrv_replace_node_common(BlockDriverState *from,
4947 BlockDriverState *to,
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004948 bool auto_skip, bool detach_subchain,
4949 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004950{
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004951 Transaction *tran = tran_new();
4952 g_autoptr(GHashTable) found = NULL;
4953 g_autoptr(GSList) refresh_list = NULL;
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004954 BlockDriverState *to_cow_parent;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004955 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004956
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004957 if (detach_subchain) {
4958 assert(bdrv_chain_contains(from, to));
4959 assert(from != to);
4960 for (to_cow_parent = from;
4961 bdrv_filter_or_cow_bs(to_cow_parent) != to;
4962 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
4963 {
4964 ;
4965 }
4966 }
4967
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004968 /* Make sure that @from doesn't go away until we have successfully attached
4969 * all of its parents to @to. */
4970 bdrv_ref(from);
4971
Kevin Wolff871abd2019-05-21 19:00:25 +02004972 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01004973 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02004974 bdrv_drained_begin(from);
4975
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004976 /*
4977 * Do the replacement without permission update.
4978 * Replacement may influence the permissions, we should calculate new
4979 * permissions based on new graph. If we fail, we'll roll-back the
4980 * replacement.
4981 */
Vladimir Sementsov-Ogievskiy117caba2021-04-28 18:17:48 +03004982 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
4983 if (ret < 0) {
4984 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004985 }
4986
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03004987 if (detach_subchain) {
4988 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
4989 }
4990
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004991 found = g_hash_table_new(NULL, NULL);
4992
4993 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
4994 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
4995
4996 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004997 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004998 goto out;
4999 }
5000
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005001 ret = 0;
5002
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005003out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005004 tran_finalize(tran, ret);
5005
Kevin Wolff871abd2019-05-21 19:00:25 +02005006 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005007 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005008
5009 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005010}
5011
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005012int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5013 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005014{
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005015 return bdrv_replace_node_common(from, to, true, false, errp);
5016}
5017
5018int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5019{
5020 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5021 errp);
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005022}
5023
Jeff Cody8802d1f2012-02-28 15:54:06 -05005024/*
5025 * Add new bs contents at the top of an image chain while the chain is
5026 * live, while keeping required fields on the top layer.
5027 *
5028 * This will modify the BlockDriverState fields, and swap contents
5029 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5030 *
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005031 * bs_new must not be attached to a BlockBackend and must not have backing
5032 * child.
Jeff Codyf6801b82012-03-27 16:30:19 -04005033 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005034 * This function does not create any image files.
5035 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005036int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5037 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005038{
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005039 int ret;
5040 Transaction *tran = tran_new();
5041
5042 assert(!bs_new->backing);
5043
5044 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5045 &child_of_bds, bdrv_backing_role(bs_new),
5046 &bs_new->backing, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005047 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005048 goto out;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005049 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005050
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005051 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005052 if (ret < 0) {
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005053 goto out;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005054 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005055
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005056 ret = bdrv_refresh_perms(bs_new, errp);
5057out:
5058 tran_finalize(tran, ret);
5059
Vladimir Sementsov-Ogievskiy1e4c7972021-04-28 18:17:55 +03005060 bdrv_refresh_limits(bs_top, NULL, NULL);
Vladimir Sementsov-Ogievskiy2272edc2021-04-28 18:17:49 +03005061
5062 return ret;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005063}
5064
Fam Zheng4f6fd342013-08-23 09:14:47 +08005065static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005066{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005067 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005068 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02005069
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005070 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005071 if (bs->node_name[0] != '\0') {
5072 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5073 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005074 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5075
Anton Kuchin30c321f2019-05-07 11:12:56 +03005076 bdrv_close(bs);
5077
Anthony Liguori7267c092011-08-20 22:09:37 -05005078 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005079}
5080
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005081BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *node_options,
5082 int flags, Error **errp)
5083{
5084 BlockDriverState *new_node_bs;
5085 Error *local_err = NULL;
5086
5087 new_node_bs = bdrv_open(NULL, NULL, node_options, flags, errp);
5088 if (new_node_bs == NULL) {
5089 error_prepend(errp, "Could not create node: ");
5090 return NULL;
5091 }
5092
5093 bdrv_drained_begin(bs);
5094 bdrv_replace_node(bs, new_node_bs, &local_err);
5095 bdrv_drained_end(bs);
5096
5097 if (local_err) {
5098 bdrv_unref(new_node_bs);
5099 error_propagate(errp, local_err);
5100 return NULL;
5101 }
5102
5103 return new_node_bs;
5104}
5105
aliguorie97fc192009-04-21 23:11:50 +00005106/*
5107 * Run consistency checks on an image
5108 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005109 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005110 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005111 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005112 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005113int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5114 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005115{
Max Reitz908bcd52014-08-07 22:47:55 +02005116 if (bs->drv == NULL) {
5117 return -ENOMEDIUM;
5118 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005119 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005120 return -ENOTSUP;
5121 }
5122
Kevin Wolfe076f332010-06-29 11:43:13 +02005123 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005124 return bs->drv->bdrv_co_check(bs, res, fix);
5125}
5126
Kevin Wolf756e6732010-01-12 12:55:17 +01005127/*
5128 * Return values:
5129 * 0 - success
5130 * -EINVAL - backing format specified, but no file
5131 * -ENOSPC - can't update the backing file because no space is left in the
5132 * image file header
5133 * -ENOTSUP - format driver doesn't support changing the backing file
5134 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005135int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5136 const char *backing_fmt, bool warn)
Kevin Wolf756e6732010-01-12 12:55:17 +01005137{
5138 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005139 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005140
Max Reitzd470ad42017-11-10 21:31:09 +01005141 if (!drv) {
5142 return -ENOMEDIUM;
5143 }
5144
Paolo Bonzini5f377792012-04-12 14:01:01 +02005145 /* Backing file format doesn't make sense without a backing file */
5146 if (backing_fmt && !backing_file) {
5147 return -EINVAL;
5148 }
5149
Eric Blakee54ee1b2020-07-06 15:39:53 -05005150 if (warn && backing_file && !backing_fmt) {
5151 warn_report("Deprecated use of backing file without explicit "
5152 "backing format, use of this image requires "
5153 "potentially unsafe format probing");
5154 }
5155
Kevin Wolf756e6732010-01-12 12:55:17 +01005156 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005157 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005158 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005159 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005160 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005161
5162 if (ret == 0) {
5163 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5164 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005165 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5166 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005167 }
5168 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005169}
5170
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005171/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005172 * Finds the first non-filter node above bs in the chain between
5173 * active and bs. The returned node is either an immediate parent of
5174 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005175 *
5176 * Returns NULL if bs is not found in active's image chain,
5177 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005178 *
5179 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005180 */
5181BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5182 BlockDriverState *bs)
5183{
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005184 bs = bdrv_skip_filters(bs);
5185 active = bdrv_skip_filters(active);
5186
5187 while (active) {
5188 BlockDriverState *next = bdrv_backing_chain_next(active);
5189 if (bs == next) {
5190 return active;
5191 }
5192 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005193 }
5194
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005195 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005196}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005197
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005198/* Given a BDS, searches for the base layer. */
5199BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5200{
5201 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005202}
5203
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005204/*
Max Reitz7b99a262019-06-12 16:07:11 +02005205 * Return true if at least one of the COW (backing) and filter links
5206 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005207 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005208 */
5209bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5210 Error **errp)
5211{
5212 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005213 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005214
Max Reitz7b99a262019-06-12 16:07:11 +02005215 for (i = bs; i != base; i = child_bs(child)) {
5216 child = bdrv_filter_or_cow_child(i);
5217
5218 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005219 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005220 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005221 return true;
5222 }
5223 }
5224
5225 return false;
5226}
5227
5228/*
Max Reitz7b99a262019-06-12 16:07:11 +02005229 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005230 * If any of the links is already frozen the operation is aborted and
5231 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005232 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005233 * Returns 0 on success. On failure returns < 0 and sets @errp.
5234 */
5235int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5236 Error **errp)
5237{
5238 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005239 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005240
5241 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5242 return -EPERM;
5243 }
5244
Max Reitz7b99a262019-06-12 16:07:11 +02005245 for (i = bs; i != base; i = child_bs(child)) {
5246 child = bdrv_filter_or_cow_child(i);
5247 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005248 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005249 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005250 return -EPERM;
5251 }
5252 }
5253
Max Reitz7b99a262019-06-12 16:07:11 +02005254 for (i = bs; i != base; i = child_bs(child)) {
5255 child = bdrv_filter_or_cow_child(i);
5256 if (child) {
5257 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005258 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005259 }
5260
5261 return 0;
5262}
5263
5264/*
Max Reitz7b99a262019-06-12 16:07:11 +02005265 * Unfreeze all COW (backing) and filter links between @bs and @base.
5266 * The caller must ensure that all links are frozen before using this
5267 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005268 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005269 */
5270void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5271{
5272 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005273 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005274
Max Reitz7b99a262019-06-12 16:07:11 +02005275 for (i = bs; i != base; i = child_bs(child)) {
5276 child = bdrv_filter_or_cow_child(i);
5277 if (child) {
5278 assert(child->frozen);
5279 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005280 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005281 }
5282}
5283
5284/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005285 * Drops images above 'base' up to and including 'top', and sets the image
5286 * above 'top' to have base as its backing file.
5287 *
5288 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5289 * information in 'bs' can be properly updated.
5290 *
5291 * E.g., this will convert the following chain:
5292 * bottom <- base <- intermediate <- top <- active
5293 *
5294 * to
5295 *
5296 * bottom <- base <- active
5297 *
5298 * It is allowed for bottom==base, in which case it converts:
5299 *
5300 * base <- intermediate <- top <- active
5301 *
5302 * to
5303 *
5304 * base <- active
5305 *
Jeff Cody54e26902014-06-25 15:40:10 -04005306 * If backing_file_str is non-NULL, it will be used when modifying top's
5307 * overlay image metadata.
5308 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005309 * Error conditions:
5310 * if active == top, that is considered an error
5311 *
5312 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005313int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5314 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005315{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005316 BlockDriverState *explicit_top = top;
5317 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005318 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005319 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005320 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005321 g_autoptr(GSList) updated_children = NULL;
5322 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005323
Kevin Wolf6858eba2017-06-29 19:32:21 +02005324 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005325 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005326
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005327 if (!top->drv || !base->drv) {
5328 goto exit;
5329 }
5330
Kevin Wolf5db15a52015-09-14 15:33:33 +02005331 /* Make sure that base is in the backing chain of top */
5332 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005333 goto exit;
5334 }
5335
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005336 /* If 'base' recursively inherits from 'top' then we should set
5337 * base->inherits_from to top->inherits_from after 'top' and all
5338 * other intermediate nodes have been dropped.
5339 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5340 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005341 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005342 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5343
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005344 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolfbde70712017-06-27 20:36:18 +02005345 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
5346 * we've figured out how they should work. */
Max Reitzf30c66b2019-02-01 20:29:05 +01005347 if (!backing_file_str) {
5348 bdrv_refresh_filename(base);
5349 backing_file_str = base->filename;
5350 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005351
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005352 QLIST_FOREACH(c, &top->parents, next_parent) {
5353 updated_children = g_slist_prepend(updated_children, c);
5354 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005355
Vladimir Sementsov-Ogievskiy3108a152021-04-28 18:17:51 +03005356 /*
5357 * It seems correct to pass detach_subchain=true here, but it triggers
5358 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5359 * another drained section, which modify the graph (for example, removing
5360 * the child, which we keep in updated_children list). So, it's a TODO.
5361 *
5362 * Note, bug triggered if pass detach_subchain=true here and run
5363 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5364 * That's a FIXME.
5365 */
5366 bdrv_replace_node_common(top, base, false, false, &local_err);
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005367 if (local_err) {
5368 error_report_err(local_err);
5369 goto exit;
5370 }
5371
5372 for (p = updated_children; p; p = p->next) {
5373 c = p->data;
5374
Max Reitzbd86fb92020-05-13 13:05:13 +02005375 if (c->klass->update_filename) {
5376 ret = c->klass->update_filename(c, base, backing_file_str,
5377 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005378 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005379 /*
5380 * TODO: Actually, we want to rollback all previous iterations
5381 * of this loop, and (which is almost impossible) previous
5382 * bdrv_replace_node()...
5383 *
5384 * Note, that c->klass->update_filename may lead to permission
5385 * update, so it's a bad idea to call it inside permission
5386 * update transaction of bdrv_replace_node.
5387 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005388 error_report_err(local_err);
5389 goto exit;
5390 }
5391 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005392 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005393
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005394 if (update_inherits_from) {
5395 base->inherits_from = explicit_top->inherits_from;
5396 }
5397
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005398 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005399exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005400 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005401 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005402 return ret;
5403}
5404
bellard83f64092006-08-01 16:21:11 +00005405/**
Max Reitz081e4652019-06-12 18:14:13 +02005406 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5407 * sums the size of all data-bearing children. (This excludes backing
5408 * children.)
5409 */
5410static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5411{
5412 BdrvChild *child;
5413 int64_t child_size, sum = 0;
5414
5415 QLIST_FOREACH(child, &bs->children, next) {
5416 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5417 BDRV_CHILD_FILTERED))
5418 {
5419 child_size = bdrv_get_allocated_file_size(child->bs);
5420 if (child_size < 0) {
5421 return child_size;
5422 }
5423 sum += child_size;
5424 }
5425 }
5426
5427 return sum;
5428}
5429
5430/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005431 * Length of a allocated file in bytes. Sparse files are counted by actual
5432 * allocated space. Return < 0 if error or unknown.
5433 */
5434int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5435{
5436 BlockDriver *drv = bs->drv;
5437 if (!drv) {
5438 return -ENOMEDIUM;
5439 }
5440 if (drv->bdrv_get_allocated_file_size) {
5441 return drv->bdrv_get_allocated_file_size(bs);
5442 }
Max Reitz081e4652019-06-12 18:14:13 +02005443
5444 if (drv->bdrv_file_open) {
5445 /*
5446 * Protocol drivers default to -ENOTSUP (most of their data is
5447 * not stored in any of their children (if they even have any),
5448 * so there is no generic way to figure it out).
5449 */
5450 return -ENOTSUP;
5451 } else if (drv->is_filter) {
5452 /* Filter drivers default to the size of their filtered child */
5453 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5454 } else {
5455 /* Other drivers default to summing their children's sizes */
5456 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005457 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005458}
5459
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005460/*
5461 * bdrv_measure:
5462 * @drv: Format driver
5463 * @opts: Creation options for new image
5464 * @in_bs: Existing image containing data for new image (may be NULL)
5465 * @errp: Error object
5466 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5467 * or NULL on error
5468 *
5469 * Calculate file size required to create a new image.
5470 *
5471 * If @in_bs is given then space for allocated clusters and zero clusters
5472 * from that image are included in the calculation. If @opts contains a
5473 * backing file that is shared by @in_bs then backing clusters may be omitted
5474 * from the calculation.
5475 *
5476 * If @in_bs is NULL then the calculation includes no allocated clusters
5477 * unless a preallocation option is given in @opts.
5478 *
5479 * Note that @in_bs may use a different BlockDriver from @drv.
5480 *
5481 * If an error occurs the @errp pointer is set.
5482 */
5483BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5484 BlockDriverState *in_bs, Error **errp)
5485{
5486 if (!drv->bdrv_measure) {
5487 error_setg(errp, "Block driver '%s' does not support size measurement",
5488 drv->format_name);
5489 return NULL;
5490 }
5491
5492 return drv->bdrv_measure(opts, in_bs, errp);
5493}
5494
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005495/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005496 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005497 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005498int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005499{
5500 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005501
bellard83f64092006-08-01 16:21:11 +00005502 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005503 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005504
Kevin Wolfb94a2612013-10-29 12:18:58 +01005505 if (drv->has_variable_length) {
5506 int ret = refresh_total_sectors(bs, bs->total_sectors);
5507 if (ret < 0) {
5508 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005509 }
bellard83f64092006-08-01 16:21:11 +00005510 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005511 return bs->total_sectors;
5512}
5513
5514/**
5515 * Return length in bytes on success, -errno on error.
5516 * The length is always a multiple of BDRV_SECTOR_SIZE.
5517 */
5518int64_t bdrv_getlength(BlockDriverState *bs)
5519{
5520 int64_t ret = bdrv_nb_sectors(bs);
5521
Eric Blake122860b2020-11-05 09:51:22 -06005522 if (ret < 0) {
5523 return ret;
5524 }
5525 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5526 return -EFBIG;
5527 }
5528 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005529}
5530
bellard19cb3732006-08-19 11:45:59 +00005531/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005532void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005533{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005534 int64_t nb_sectors = bdrv_nb_sectors(bs);
5535
5536 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005537}
bellardcf989512004-02-16 21:56:36 +00005538
Eric Blake54115412016-06-23 16:37:26 -06005539bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005540{
5541 return bs->sg;
5542}
5543
Max Reitzae23f782019-06-12 22:57:15 +02005544/**
5545 * Return whether the given node supports compressed writes.
5546 */
5547bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5548{
5549 BlockDriverState *filtered;
5550
5551 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5552 return false;
5553 }
5554
5555 filtered = bdrv_filter_bs(bs);
5556 if (filtered) {
5557 /*
5558 * Filters can only forward compressed writes, so we have to
5559 * check the child.
5560 */
5561 return bdrv_supports_compressed_writes(filtered);
5562 }
5563
5564 return true;
5565}
5566
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005567const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005568{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005569 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005570}
5571
Stefan Hajnocziada42402014-08-27 12:08:55 +01005572static int qsort_strcmp(const void *a, const void *b)
5573{
Max Reitzceff5bd2016-10-12 22:49:05 +02005574 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005575}
5576
ths5fafdf22007-09-16 21:08:06 +00005577void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005578 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005579{
5580 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005581 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005582 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005583 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005584
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005585 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005586 if (drv->format_name) {
5587 bool found = false;
5588 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005589
5590 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5591 continue;
5592 }
5593
Jeff Codye855e4f2014-04-28 18:29:54 -04005594 while (formats && i && !found) {
5595 found = !strcmp(formats[--i], drv->format_name);
5596 }
5597
5598 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005599 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005600 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005601 }
5602 }
bellardea2384d2004-08-01 21:59:26 +00005603 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005604
Max Reitzeb0df692016-10-12 22:49:06 +02005605 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5606 const char *format_name = block_driver_modules[i].format_name;
5607
5608 if (format_name) {
5609 bool found = false;
5610 int j = count;
5611
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005612 if (use_bdrv_whitelist &&
5613 !bdrv_format_is_whitelisted(format_name, read_only)) {
5614 continue;
5615 }
5616
Max Reitzeb0df692016-10-12 22:49:06 +02005617 while (formats && j && !found) {
5618 found = !strcmp(formats[--j], format_name);
5619 }
5620
5621 if (!found) {
5622 formats = g_renew(const char *, formats, count + 1);
5623 formats[count++] = format_name;
5624 }
5625 }
5626 }
5627
Stefan Hajnocziada42402014-08-27 12:08:55 +01005628 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5629
5630 for (i = 0; i < count; i++) {
5631 it(opaque, formats[i]);
5632 }
5633
Jeff Codye855e4f2014-04-28 18:29:54 -04005634 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005635}
5636
Benoît Canetdc364f42014-01-23 21:31:32 +01005637/* This function is to find a node in the bs graph */
5638BlockDriverState *bdrv_find_node(const char *node_name)
5639{
5640 BlockDriverState *bs;
5641
5642 assert(node_name);
5643
5644 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5645 if (!strcmp(node_name, bs->node_name)) {
5646 return bs;
5647 }
5648 }
5649 return NULL;
5650}
5651
Benoît Canetc13163f2014-01-23 21:31:34 +01005652/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005653BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5654 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005655{
Eric Blake9812e712020-10-27 00:05:47 -05005656 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005657 BlockDriverState *bs;
5658
5659 list = NULL;
5660 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005661 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005662 if (!info) {
5663 qapi_free_BlockDeviceInfoList(list);
5664 return NULL;
5665 }
Eric Blake9812e712020-10-27 00:05:47 -05005666 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005667 }
5668
5669 return list;
5670}
5671
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005672typedef struct XDbgBlockGraphConstructor {
5673 XDbgBlockGraph *graph;
5674 GHashTable *graph_nodes;
5675} XDbgBlockGraphConstructor;
5676
5677static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5678{
5679 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5680
5681 gr->graph = g_new0(XDbgBlockGraph, 1);
5682 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5683
5684 return gr;
5685}
5686
5687static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5688{
5689 XDbgBlockGraph *graph = gr->graph;
5690
5691 g_hash_table_destroy(gr->graph_nodes);
5692 g_free(gr);
5693
5694 return graph;
5695}
5696
5697static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5698{
5699 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5700
5701 if (ret != 0) {
5702 return ret;
5703 }
5704
5705 /*
5706 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5707 * answer of g_hash_table_lookup.
5708 */
5709 ret = g_hash_table_size(gr->graph_nodes) + 1;
5710 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5711
5712 return ret;
5713}
5714
5715static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5716 XDbgBlockGraphNodeType type, const char *name)
5717{
5718 XDbgBlockGraphNode *n;
5719
5720 n = g_new0(XDbgBlockGraphNode, 1);
5721
5722 n->id = xdbg_graph_node_num(gr, node);
5723 n->type = type;
5724 n->name = g_strdup(name);
5725
Eric Blake9812e712020-10-27 00:05:47 -05005726 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005727}
5728
5729static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5730 const BdrvChild *child)
5731{
Max Reitzcdb1cec2019-11-08 13:34:52 +01005732 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005733 XDbgBlockGraphEdge *edge;
5734
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005735 edge = g_new0(XDbgBlockGraphEdge, 1);
5736
5737 edge->parent = xdbg_graph_node_num(gr, parent);
5738 edge->child = xdbg_graph_node_num(gr, child->bs);
5739 edge->name = g_strdup(child->name);
5740
Max Reitzcdb1cec2019-11-08 13:34:52 +01005741 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5742 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5743
5744 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005745 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005746 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01005747 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005748 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005749 }
5750 }
5751
Eric Blake9812e712020-10-27 00:05:47 -05005752 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005753}
5754
5755
5756XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5757{
5758 BlockBackend *blk;
5759 BlockJob *job;
5760 BlockDriverState *bs;
5761 BdrvChild *child;
5762 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5763
5764 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5765 char *allocated_name = NULL;
5766 const char *name = blk_name(blk);
5767
5768 if (!*name) {
5769 name = allocated_name = blk_get_attached_dev_id(blk);
5770 }
5771 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5772 name);
5773 g_free(allocated_name);
5774 if (blk_root(blk)) {
5775 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5776 }
5777 }
5778
5779 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5780 GSList *el;
5781
5782 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5783 job->job.id);
5784 for (el = job->nodes; el; el = el->next) {
5785 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5786 }
5787 }
5788
5789 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5790 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5791 bs->node_name);
5792 QLIST_FOREACH(child, &bs->children, next) {
5793 xdbg_graph_add_edge(gr, bs, child);
5794 }
5795 }
5796
5797 return xdbg_graph_finalize(gr);
5798}
5799
Benoît Canet12d3ba82014-01-23 21:31:35 +01005800BlockDriverState *bdrv_lookup_bs(const char *device,
5801 const char *node_name,
5802 Error **errp)
5803{
Markus Armbruster7f06d472014-10-07 13:59:12 +02005804 BlockBackend *blk;
5805 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005806
Benoît Canet12d3ba82014-01-23 21:31:35 +01005807 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02005808 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005809
Markus Armbruster7f06d472014-10-07 13:59:12 +02005810 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005811 bs = blk_bs(blk);
5812 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02005813 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02005814 }
5815
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005816 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005817 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005818 }
5819
Benoît Canetdd67fa52014-02-12 17:15:06 +01005820 if (node_name) {
5821 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005822
Benoît Canetdd67fa52014-02-12 17:15:06 +01005823 if (bs) {
5824 return bs;
5825 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005826 }
5827
Connor Kuehl785ec4b2021-03-05 09:19:28 -06005828 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01005829 device ? device : "",
5830 node_name ? node_name : "");
5831 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005832}
5833
Jeff Cody5a6684d2014-06-25 15:40:09 -04005834/* If 'base' is in the same chain as 'top', return true. Otherwise,
5835 * return false. If either argument is NULL, return false. */
5836bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5837{
5838 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005839 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04005840 }
5841
5842 return top != NULL;
5843}
5844
Fam Zheng04df7652014-10-31 11:32:54 +08005845BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5846{
5847 if (!bs) {
5848 return QTAILQ_FIRST(&graph_bdrv_states);
5849 }
5850 return QTAILQ_NEXT(bs, node_list);
5851}
5852
Kevin Wolf0f122642018-03-28 18:29:18 +02005853BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5854{
5855 if (!bs) {
5856 return QTAILQ_FIRST(&all_bdrv_states);
5857 }
5858 return QTAILQ_NEXT(bs, bs_list);
5859}
5860
Fam Zheng20a9e772014-10-31 11:32:55 +08005861const char *bdrv_get_node_name(const BlockDriverState *bs)
5862{
5863 return bs->node_name;
5864}
5865
Kevin Wolf1f0c4612016-03-22 18:38:44 +01005866const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005867{
5868 BdrvChild *c;
5869 const char *name;
5870
5871 /* If multiple parents have a name, just pick the first one. */
5872 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005873 if (c->klass->get_name) {
5874 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005875 if (name && *name) {
5876 return name;
5877 }
5878 }
5879 }
5880
5881 return NULL;
5882}
5883
Markus Armbruster7f06d472014-10-07 13:59:12 +02005884/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02005885const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005886{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005887 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00005888}
5889
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005890/* This can be used to identify nodes that might not have a device
5891 * name associated. Since node and device names live in the same
5892 * namespace, the result is unambiguous. The exception is if both are
5893 * absent, then this returns an empty (non-null) string. */
5894const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5895{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005896 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005897}
5898
Markus Armbrusterc8433282012-06-05 16:49:24 +02005899int bdrv_get_flags(BlockDriverState *bs)
5900{
5901 return bs->open_flags;
5902}
5903
Peter Lieven3ac21622013-06-28 12:47:42 +02005904int bdrv_has_zero_init_1(BlockDriverState *bs)
5905{
5906 return 1;
5907}
5908
Kevin Wolff2feebb2010-04-14 17:30:35 +02005909int bdrv_has_zero_init(BlockDriverState *bs)
5910{
Max Reitz93393e62019-06-12 17:03:38 +02005911 BlockDriverState *filtered;
5912
Max Reitzd470ad42017-11-10 21:31:09 +01005913 if (!bs->drv) {
5914 return 0;
5915 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005916
Paolo Bonzini11212d82013-09-04 19:00:27 +02005917 /* If BS is a copy on write image, it is initialized to
5918 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02005919 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02005920 return 0;
5921 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02005922 if (bs->drv->bdrv_has_zero_init) {
5923 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02005924 }
Max Reitz93393e62019-06-12 17:03:38 +02005925
5926 filtered = bdrv_filter_bs(bs);
5927 if (filtered) {
5928 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005929 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005930
Peter Lieven3ac21622013-06-28 12:47:42 +02005931 /* safe default */
5932 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02005933}
5934
Peter Lieven4ce78692013-10-24 12:06:54 +02005935bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5936{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03005937 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02005938 return false;
5939 }
5940
Eric Blakee24d8132018-01-26 13:34:39 -06005941 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02005942}
5943
ths5fafdf22007-09-16 21:08:06 +00005944void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00005945 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00005946{
Kevin Wolf3574c602011-10-26 11:02:11 +02005947 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00005948}
5949
bellardfaea38e2006-08-05 21:31:00 +00005950int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5951{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005952 int ret;
bellardfaea38e2006-08-05 21:31:00 +00005953 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005954 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5955 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00005956 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005957 }
5958 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02005959 BlockDriverState *filtered = bdrv_filter_bs(bs);
5960 if (filtered) {
5961 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005962 }
bellardfaea38e2006-08-05 21:31:00 +00005963 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005964 }
bellardfaea38e2006-08-05 21:31:00 +00005965 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005966 ret = drv->bdrv_get_info(bs, bdi);
5967 if (ret < 0) {
5968 return ret;
5969 }
5970
5971 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
5972 return -EINVAL;
5973 }
5974
5975 return 0;
bellardfaea38e2006-08-05 21:31:00 +00005976}
5977
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005978ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5979 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02005980{
5981 BlockDriver *drv = bs->drv;
5982 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005983 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02005984 }
5985 return NULL;
5986}
5987
Anton Nefedovd9245592019-09-23 15:17:37 +03005988BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5989{
5990 BlockDriver *drv = bs->drv;
5991 if (!drv || !drv->bdrv_get_specific_stats) {
5992 return NULL;
5993 }
5994 return drv->bdrv_get_specific_stats(bs);
5995}
5996
Eric Blakea31939e2015-11-18 01:52:54 -07005997void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005998{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005999 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006000 return;
6001 }
6002
Kevin Wolfbf736fe2013-06-05 15:17:55 +02006003 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006004}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006005
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006006static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01006007{
6008 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02006009 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006010 }
6011
6012 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006013 assert(bs->drv->bdrv_debug_remove_breakpoint);
6014 return bs;
6015 }
6016
6017 return NULL;
6018}
6019
6020int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6021 const char *tag)
6022{
6023 bs = bdrv_find_debug_node(bs);
6024 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006025 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6026 }
6027
6028 return -ENOTSUP;
6029}
6030
Fam Zheng4cc70e92013-11-20 10:01:54 +08006031int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6032{
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006033 bs = bdrv_find_debug_node(bs);
6034 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006035 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6036 }
6037
6038 return -ENOTSUP;
6039}
6040
Kevin Wolf41c695c2012-12-06 14:32:58 +01006041int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6042{
Max Reitz938789e2014-03-10 23:44:08 +01006043 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006044 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006045 }
6046
6047 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6048 return bs->drv->bdrv_debug_resume(bs, tag);
6049 }
6050
6051 return -ENOTSUP;
6052}
6053
6054bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6055{
6056 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006057 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006058 }
6059
6060 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6061 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6062 }
6063
6064 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006065}
6066
Jeff Codyb1b1d782012-10-16 15:49:09 -04006067/* backing_file can either be relative, or absolute, or a protocol. If it is
6068 * relative, it must be relative to the chain. So, passing in bs->filename
6069 * from a BDS as backing_file should not be done, as that may be relative to
6070 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006071BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6072 const char *backing_file)
6073{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006074 char *filename_full = NULL;
6075 char *backing_file_full = NULL;
6076 char *filename_tmp = NULL;
6077 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006078 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006079 BlockDriverState *curr_bs = NULL;
6080 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006081 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006082
6083 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006084 return NULL;
6085 }
6086
Jeff Codyb1b1d782012-10-16 15:49:09 -04006087 filename_full = g_malloc(PATH_MAX);
6088 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006089
6090 is_protocol = path_has_protocol(backing_file);
6091
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006092 /*
6093 * Being largely a legacy function, skip any filters here
6094 * (because filters do not have normal filenames, so they cannot
6095 * match anyway; and allowing json:{} filenames is a bit out of
6096 * scope).
6097 */
6098 for (curr_bs = bdrv_skip_filters(bs);
6099 bdrv_cow_child(curr_bs) != NULL;
6100 curr_bs = bs_below)
6101 {
6102 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006103
Max Reitz0b877d02018-08-01 20:34:11 +02006104 if (bdrv_backing_overridden(curr_bs)) {
6105 /*
6106 * If the backing file was overridden, we can only compare
6107 * directly against the backing node's filename.
6108 */
6109
6110 if (!filenames_refreshed) {
6111 /*
6112 * This will automatically refresh all of the
6113 * filenames in the rest of the backing chain, so we
6114 * only need to do this once.
6115 */
6116 bdrv_refresh_filename(bs_below);
6117 filenames_refreshed = true;
6118 }
6119
6120 if (strcmp(backing_file, bs_below->filename) == 0) {
6121 retval = bs_below;
6122 break;
6123 }
6124 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6125 /*
6126 * If either of the filename paths is actually a protocol, then
6127 * compare unmodified paths; otherwise make paths relative.
6128 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006129 char *backing_file_full_ret;
6130
Jeff Codyb1b1d782012-10-16 15:49:09 -04006131 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006132 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006133 break;
6134 }
Jeff Cody418661e2017-01-25 20:08:20 -05006135 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006136 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6137 NULL);
6138 if (backing_file_full_ret) {
6139 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6140 g_free(backing_file_full_ret);
6141 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006142 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006143 break;
6144 }
Jeff Cody418661e2017-01-25 20:08:20 -05006145 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006146 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006147 /* If not an absolute filename path, make it relative to the current
6148 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006149 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6150 NULL);
6151 /* We are going to compare canonicalized absolute pathnames */
6152 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6153 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006154 continue;
6155 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006156 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006157
6158 /* We need to make sure the backing filename we are comparing against
6159 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006160 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6161 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6162 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006163 continue;
6164 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006165 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006166
6167 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006168 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006169 break;
6170 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006171 }
6172 }
6173
Jeff Codyb1b1d782012-10-16 15:49:09 -04006174 g_free(filename_full);
6175 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006176 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006177}
6178
bellardea2384d2004-08-01 21:59:26 +00006179void bdrv_init(void)
6180{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006181 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006182}
pbrookce1a14d2006-08-07 02:38:06 +00006183
Markus Armbrustereb852012009-10-27 18:41:44 +01006184void bdrv_init_with_whitelist(void)
6185{
6186 use_bdrv_whitelist = 1;
6187 bdrv_init();
6188}
6189
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03006190int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006191{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006192 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006193 Error *local_err = NULL;
6194 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006195 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006196
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006197 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006198 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006199 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006200
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006201 QLIST_FOREACH(child, &bs->children, next) {
Paolo Bonzini2b148f32018-03-01 17:36:18 +01006202 bdrv_co_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006203 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006204 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006205 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006206 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006207 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006208
Kevin Wolfdafe0962017-11-16 13:00:01 +01006209 /*
6210 * Update permissions, they may differ for inactive nodes.
6211 *
6212 * Note that the required permissions of inactive images are always a
6213 * subset of the permissions required after activating the image. This
6214 * allows us to just get the permissions upfront without restricting
6215 * drv->bdrv_invalidate_cache().
6216 *
6217 * It also means that in error cases, we don't have to try and revert to
6218 * the old permissions (which is an operation that could fail, too). We can
6219 * just keep the extended permissions for the next time that an activation
6220 * of the image is tried.
6221 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006222 if (bs->open_flags & BDRV_O_INACTIVE) {
6223 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006224 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006225 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006226 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006227 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006228 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006229
Kevin Wolf7bb49412019-12-17 15:06:38 +01006230 if (bs->drv->bdrv_co_invalidate_cache) {
6231 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6232 if (local_err) {
6233 bs->open_flags |= BDRV_O_INACTIVE;
6234 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006235 return -EINVAL;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006236 }
6237 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006238
Kevin Wolf7bb49412019-12-17 15:06:38 +01006239 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6240 bdrv_dirty_bitmap_skip_store(bm, false);
6241 }
6242
6243 ret = refresh_total_sectors(bs, bs->total_sectors);
6244 if (ret < 0) {
6245 bs->open_flags |= BDRV_O_INACTIVE;
6246 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006247 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006248 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006249 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006250
6251 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006252 if (parent->klass->activate) {
6253 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006254 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006255 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006256 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006257 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006258 }
6259 }
6260 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006261
6262 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006263}
6264
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006265void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006266{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006267 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006268 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006269
Kevin Wolf88be7b42016-05-20 18:49:07 +02006270 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006271 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006272 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006273
6274 aio_context_acquire(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006275 ret = bdrv_invalidate_cache(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006276 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006277 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006278 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006279 return;
6280 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006281 }
6282}
6283
Kevin Wolf9e372712018-11-23 15:11:14 +01006284static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6285{
6286 BdrvChild *parent;
6287
6288 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006289 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006290 BlockDriverState *parent_bs = parent->opaque;
6291 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6292 return true;
6293 }
6294 }
6295 }
6296
6297 return false;
6298}
6299
6300static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006301{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006302 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006303 int ret;
6304
Max Reitzd470ad42017-11-10 21:31:09 +01006305 if (!bs->drv) {
6306 return -ENOMEDIUM;
6307 }
6308
Kevin Wolf9e372712018-11-23 15:11:14 +01006309 /* Make sure that we don't inactivate a child before its parent.
6310 * It will be covered by recursion from the yet active parent. */
6311 if (bdrv_has_bds_parent(bs, true)) {
6312 return 0;
6313 }
6314
6315 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6316
6317 /* Inactivate this node */
6318 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006319 ret = bs->drv->bdrv_inactivate(bs);
6320 if (ret < 0) {
6321 return ret;
6322 }
6323 }
6324
Kevin Wolf9e372712018-11-23 15:11:14 +01006325 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006326 if (parent->klass->inactivate) {
6327 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006328 if (ret < 0) {
6329 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006330 }
6331 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006332 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006333
Kevin Wolf9e372712018-11-23 15:11:14 +01006334 bs->open_flags |= BDRV_O_INACTIVE;
6335
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006336 /*
6337 * Update permissions, they may differ for inactive nodes.
6338 * We only tried to loosen restrictions, so errors are not fatal, ignore
6339 * them.
6340 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006341 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006342
6343 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006344 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006345 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006346 if (ret < 0) {
6347 return ret;
6348 }
6349 }
6350
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006351 return 0;
6352}
6353
6354int bdrv_inactivate_all(void)
6355{
Max Reitz79720af2016-03-16 19:54:44 +01006356 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006357 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006358 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006359 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006360
Kevin Wolf88be7b42016-05-20 18:49:07 +02006361 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006362 AioContext *aio_context = bdrv_get_aio_context(bs);
6363
6364 if (!g_slist_find(aio_ctxs, aio_context)) {
6365 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6366 aio_context_acquire(aio_context);
6367 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006368 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006369
Kevin Wolf9e372712018-11-23 15:11:14 +01006370 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6371 /* Nodes with BDS parents are covered by recursion from the last
6372 * parent that gets inactivated. Don't inactivate them a second
6373 * time if that has already happened. */
6374 if (bdrv_has_bds_parent(bs, false)) {
6375 continue;
6376 }
6377 ret = bdrv_inactivate_recurse(bs);
6378 if (ret < 0) {
6379 bdrv_next_cleanup(&it);
6380 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006381 }
6382 }
6383
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006384out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006385 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6386 AioContext *aio_context = ctx->data;
6387 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006388 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006389 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006390
6391 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006392}
6393
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006394/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006395/* removable device support */
6396
6397/**
6398 * Return TRUE if the media is present
6399 */
Max Reitze031f752015-10-19 17:53:11 +02006400bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006401{
6402 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006403 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006404
Max Reitze031f752015-10-19 17:53:11 +02006405 if (!drv) {
6406 return false;
6407 }
Max Reitz28d7a782015-10-19 17:53:13 +02006408 if (drv->bdrv_is_inserted) {
6409 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006410 }
Max Reitz28d7a782015-10-19 17:53:13 +02006411 QLIST_FOREACH(child, &bs->children, next) {
6412 if (!bdrv_is_inserted(child->bs)) {
6413 return false;
6414 }
6415 }
6416 return true;
bellard19cb3732006-08-19 11:45:59 +00006417}
6418
6419/**
bellard19cb3732006-08-19 11:45:59 +00006420 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6421 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006422void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006423{
6424 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006425
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006426 if (drv && drv->bdrv_eject) {
6427 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006428 }
bellard19cb3732006-08-19 11:45:59 +00006429}
6430
bellard19cb3732006-08-19 11:45:59 +00006431/**
6432 * Lock or unlock the media (if it is locked, the user won't be able
6433 * to eject it manually).
6434 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006435void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006436{
6437 BlockDriver *drv = bs->drv;
6438
Markus Armbruster025e8492011-09-06 18:58:47 +02006439 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006440
Markus Armbruster025e8492011-09-06 18:58:47 +02006441 if (drv && drv->bdrv_lock_medium) {
6442 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006443 }
6444}
ths985a03b2007-12-24 16:10:43 +00006445
Fam Zheng9fcb0252013-08-23 09:14:46 +08006446/* Get a reference to bs */
6447void bdrv_ref(BlockDriverState *bs)
6448{
6449 bs->refcnt++;
6450}
6451
6452/* Release a previously grabbed reference to bs.
6453 * If after releasing, reference count is zero, the BlockDriverState is
6454 * deleted. */
6455void bdrv_unref(BlockDriverState *bs)
6456{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006457 if (!bs) {
6458 return;
6459 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006460 assert(bs->refcnt > 0);
6461 if (--bs->refcnt == 0) {
6462 bdrv_delete(bs);
6463 }
6464}
6465
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006466struct BdrvOpBlocker {
6467 Error *reason;
6468 QLIST_ENTRY(BdrvOpBlocker) list;
6469};
6470
6471bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6472{
6473 BdrvOpBlocker *blocker;
6474 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6475 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6476 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006477 error_propagate_prepend(errp, error_copy(blocker->reason),
6478 "Node '%s' is busy: ",
6479 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006480 return true;
6481 }
6482 return false;
6483}
6484
6485void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6486{
6487 BdrvOpBlocker *blocker;
6488 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6489
Markus Armbruster5839e532014-08-19 10:31:08 +02006490 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006491 blocker->reason = reason;
6492 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6493}
6494
6495void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6496{
6497 BdrvOpBlocker *blocker, *next;
6498 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6499 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6500 if (blocker->reason == reason) {
6501 QLIST_REMOVE(blocker, list);
6502 g_free(blocker);
6503 }
6504 }
6505}
6506
6507void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6508{
6509 int i;
6510 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6511 bdrv_op_block(bs, i, reason);
6512 }
6513}
6514
6515void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6516{
6517 int i;
6518 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6519 bdrv_op_unblock(bs, i, reason);
6520 }
6521}
6522
6523bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6524{
6525 int i;
6526
6527 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6528 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6529 return false;
6530 }
6531 }
6532 return true;
6533}
6534
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006535void bdrv_img_create(const char *filename, const char *fmt,
6536 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006537 char *options, uint64_t img_size, int flags, bool quiet,
6538 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006539{
Chunyan Liu83d05212014-06-05 17:20:51 +08006540 QemuOptsList *create_opts = NULL;
6541 QemuOpts *opts = NULL;
6542 const char *backing_fmt, *backing_file;
6543 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006544 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006545 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006546 int ret = 0;
6547
6548 /* Find driver and parse its options */
6549 drv = bdrv_find_format(fmt);
6550 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006551 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006552 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006553 }
6554
Max Reitzb65a5e12015-02-05 13:58:12 -05006555 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006556 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006557 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006558 }
6559
Max Reitzc6149722014-12-02 18:32:45 +01006560 if (!drv->create_opts) {
6561 error_setg(errp, "Format driver '%s' does not support image creation",
6562 drv->format_name);
6563 return;
6564 }
6565
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006566 if (!proto_drv->create_opts) {
6567 error_setg(errp, "Protocol driver '%s' does not support image creation",
6568 proto_drv->format_name);
6569 return;
6570 }
6571
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006572 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006573 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006574 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006575
Chunyan Liu83d05212014-06-05 17:20:51 +08006576 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006577
6578 /* Parse -o options */
6579 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006580 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006581 goto out;
6582 }
6583 }
6584
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006585 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6586 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6587 } else if (img_size != UINT64_C(-1)) {
6588 error_setg(errp, "The image size must be specified only once");
6589 goto out;
6590 }
6591
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006592 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006593 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006594 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006595 error_setg(errp, "Backing file not supported for file format '%s'",
6596 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006597 goto out;
6598 }
6599 }
6600
6601 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006602 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006603 error_setg(errp, "Backing file format not supported for file "
6604 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006605 goto out;
6606 }
6607 }
6608
Chunyan Liu83d05212014-06-05 17:20:51 +08006609 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6610 if (backing_file) {
6611 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006612 error_setg(errp, "Error: Trying to create an image with the "
6613 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006614 goto out;
6615 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006616 if (backing_file[0] == '\0') {
6617 error_setg(errp, "Expected backing file name, got empty string");
6618 goto out;
6619 }
Jes Sorensen792da932010-12-16 13:52:17 +01006620 }
6621
Chunyan Liu83d05212014-06-05 17:20:51 +08006622 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006623
John Snow6e6e55f2017-07-17 20:34:22 -04006624 /* The size for the image must always be specified, unless we have a backing
6625 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006626 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006627 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6628 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006629 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006630 int back_flags;
6631 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006632
Max Reitz645ae7d2019-02-01 20:29:14 +01006633 full_backing =
6634 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6635 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006636 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006637 goto out;
6638 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006639 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006640
6641 /* backing files always opened read-only */
6642 back_flags = flags;
6643 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6644
Fam Zhengcc954f02017-12-15 16:04:45 +08006645 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006646 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006647 qdict_put_str(backing_options, "driver", backing_fmt);
6648 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006649 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006650
6651 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6652 &local_err);
6653 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006654 if (!bs) {
6655 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006656 goto out;
6657 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006658 if (!backing_fmt) {
6659 warn_report("Deprecated use of backing file without explicit "
6660 "backing format (detected format of %s)",
6661 bs->drv->format_name);
6662 if (bs->drv != &bdrv_raw) {
6663 /*
6664 * A probe of raw deserves the most attention:
6665 * leaving the backing format out of the image
6666 * will ensure bs->probed is set (ensuring we
6667 * don't accidentally commit into the backing
6668 * file), and allow more spots to warn the users
6669 * to fix their toolchain when opening this image
6670 * later. For other images, we can safely record
6671 * the format that we probed.
6672 */
6673 backing_fmt = bs->drv->format_name;
6674 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
6675 NULL);
6676 }
6677 }
John Snow6e6e55f2017-07-17 20:34:22 -04006678 if (size == -1) {
6679 /* Opened BS, have no size */
6680 size = bdrv_getlength(bs);
6681 if (size < 0) {
6682 error_setg_errno(errp, -size, "Could not get size of '%s'",
6683 backing_file);
6684 bdrv_unref(bs);
6685 goto out;
6686 }
6687 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6688 }
6689 bdrv_unref(bs);
6690 }
Eric Blaked9f059a2020-07-06 15:39:54 -05006691 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6692 } else if (backing_file && !backing_fmt) {
6693 warn_report("Deprecated use of unopened backing file without "
6694 "explicit backing format, use of this image requires "
6695 "potentially unsafe format probing");
6696 }
John Snow6e6e55f2017-07-17 20:34:22 -04006697
6698 if (size == -1) {
6699 error_setg(errp, "Image creation needs a size parameter");
6700 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006701 }
6702
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006703 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02006704 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08006705 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006706 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05006707 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006708 }
Chunyan Liu83d05212014-06-05 17:20:51 +08006709
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006710 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08006711
Max Reitzcc84d902013-09-06 17:14:26 +02006712 if (ret == -EFBIG) {
6713 /* This is generally a better message than whatever the driver would
6714 * deliver (especially because of the cluster_size_hint), since that
6715 * is most probably not much different from "image too large". */
6716 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08006717 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02006718 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006719 }
Max Reitzcc84d902013-09-06 17:14:26 +02006720 error_setg(errp, "The image size is too large for file format '%s'"
6721 "%s", fmt, cluster_size_hint);
6722 error_free(local_err);
6723 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006724 }
6725
6726out:
Chunyan Liu83d05212014-06-05 17:20:51 +08006727 qemu_opts_del(opts);
6728 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03006729 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006730}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006731
6732AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6733{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00006734 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006735}
6736
Kevin Wolfe336fd42020-10-05 17:58:53 +02006737AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6738{
6739 Coroutine *self = qemu_coroutine_self();
6740 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6741 AioContext *new_ctx;
6742
6743 /*
6744 * Increase bs->in_flight to ensure that this operation is completed before
6745 * moving the node to a different AioContext. Read new_ctx only afterwards.
6746 */
6747 bdrv_inc_in_flight(bs);
6748
6749 new_ctx = bdrv_get_aio_context(bs);
6750 aio_co_reschedule_self(new_ctx);
6751 return old_ctx;
6752}
6753
6754void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6755{
6756 aio_co_reschedule_self(old_ctx);
6757 bdrv_dec_in_flight(bs);
6758}
6759
Kevin Wolf18c6ac12020-10-05 17:58:54 +02006760void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6761{
6762 AioContext *ctx = bdrv_get_aio_context(bs);
6763
6764 /* In the main thread, bs->aio_context won't change concurrently */
6765 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6766
6767 /*
6768 * We're in coroutine context, so we already hold the lock of the main
6769 * loop AioContext. Don't lock it twice to avoid deadlocks.
6770 */
6771 assert(qemu_in_coroutine());
6772 if (ctx != qemu_get_aio_context()) {
6773 aio_context_acquire(ctx);
6774 }
6775}
6776
6777void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6778{
6779 AioContext *ctx = bdrv_get_aio_context(bs);
6780
6781 assert(qemu_in_coroutine());
6782 if (ctx != qemu_get_aio_context()) {
6783 aio_context_release(ctx);
6784 }
6785}
6786
Fam Zheng052a7572017-04-10 20:09:25 +08006787void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6788{
6789 aio_co_enter(bdrv_get_aio_context(bs), co);
6790}
6791
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006792static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6793{
6794 QLIST_REMOVE(ban, list);
6795 g_free(ban);
6796}
6797
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006798static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006799{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006800 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006801
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006802 assert(!bs->walking_aio_notifiers);
6803 bs->walking_aio_notifiers = true;
6804 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6805 if (baf->deleted) {
6806 bdrv_do_remove_aio_context_notifier(baf);
6807 } else {
6808 baf->detach_aio_context(baf->opaque);
6809 }
Max Reitz33384422014-06-20 21:57:33 +02006810 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006811 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6812 * remove remaining aio notifiers if we aren't called again.
6813 */
6814 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02006815
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006816 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006817 bs->drv->bdrv_detach_aio_context(bs);
6818 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006819
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006820 if (bs->quiesce_counter) {
6821 aio_enable_external(bs->aio_context);
6822 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006823 bs->aio_context = NULL;
6824}
6825
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006826static void bdrv_attach_aio_context(BlockDriverState *bs,
6827 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006828{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006829 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006830
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006831 if (bs->quiesce_counter) {
6832 aio_disable_external(new_context);
6833 }
6834
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006835 bs->aio_context = new_context;
6836
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006837 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006838 bs->drv->bdrv_attach_aio_context(bs, new_context);
6839 }
Max Reitz33384422014-06-20 21:57:33 +02006840
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006841 assert(!bs->walking_aio_notifiers);
6842 bs->walking_aio_notifiers = true;
6843 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6844 if (ban->deleted) {
6845 bdrv_do_remove_aio_context_notifier(ban);
6846 } else {
6847 ban->attached_aio_context(new_context, ban->opaque);
6848 }
Max Reitz33384422014-06-20 21:57:33 +02006849 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006850 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006851}
6852
Kevin Wolf42a65f02019-05-07 18:31:38 +02006853/*
6854 * Changes the AioContext used for fd handlers, timers, and BHs by this
6855 * BlockDriverState and all its children and parents.
6856 *
Max Reitz43eaaae2019-07-22 15:30:54 +02006857 * Must be called from the main AioContext.
6858 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02006859 * The caller must own the AioContext lock for the old AioContext of bs, but it
6860 * must not own the AioContext lock for new_context (unless new_context is the
6861 * same as the current context of bs).
6862 *
6863 * @ignore will accumulate all visited BdrvChild object. The caller is
6864 * responsible for freeing the list afterwards.
6865 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02006866void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6867 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006868{
Max Reitze037c092019-07-19 11:26:14 +02006869 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006870 GSList *children_to_process = NULL;
6871 GSList *parents_to_process = NULL;
6872 GSList *entry;
6873 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02006874
Max Reitz43eaaae2019-07-22 15:30:54 +02006875 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6876
Max Reitze037c092019-07-19 11:26:14 +02006877 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03006878 return;
6879 }
6880
Kevin Wolfd70d5952019-02-08 16:53:37 +01006881 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02006882
6883 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006884 if (g_slist_find(*ignore, child)) {
6885 continue;
6886 }
6887 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006888 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02006889 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006890
6891 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6892 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006893 continue;
6894 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006895 *ignore = g_slist_prepend(*ignore, parent);
6896 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02006897 }
6898
Sergio Lopez722d8e72021-02-01 13:50:31 +01006899 for (entry = children_to_process;
6900 entry != NULL;
6901 entry = g_slist_next(entry)) {
6902 child = entry->data;
6903 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6904 }
6905 g_slist_free(children_to_process);
6906
6907 for (entry = parents_to_process;
6908 entry != NULL;
6909 entry = g_slist_next(entry)) {
6910 parent = entry->data;
6911 assert(parent->klass->set_aio_ctx);
6912 parent->klass->set_aio_ctx(parent, new_context, ignore);
6913 }
6914 g_slist_free(parents_to_process);
6915
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006916 bdrv_detach_aio_context(bs);
6917
Max Reitze037c092019-07-19 11:26:14 +02006918 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02006919 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006920 aio_context_acquire(new_context);
6921 }
6922
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006923 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02006924
6925 /*
6926 * If this function was recursively called from
6927 * bdrv_set_aio_context_ignore(), there may be nodes in the
6928 * subtree that have not yet been moved to the new AioContext.
6929 * Release the old one so bdrv_drained_end() can poll them.
6930 */
Max Reitz43eaaae2019-07-22 15:30:54 +02006931 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006932 aio_context_release(old_context);
6933 }
6934
Kevin Wolfd70d5952019-02-08 16:53:37 +01006935 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02006936
Max Reitz43eaaae2019-07-22 15:30:54 +02006937 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006938 aio_context_acquire(old_context);
6939 }
Max Reitz43eaaae2019-07-22 15:30:54 +02006940 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006941 aio_context_release(new_context);
6942 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006943}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02006944
Kevin Wolf5d231842019-05-06 19:17:56 +02006945static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6946 GSList **ignore, Error **errp)
6947{
6948 if (g_slist_find(*ignore, c)) {
6949 return true;
6950 }
6951 *ignore = g_slist_prepend(*ignore, c);
6952
Max Reitzbd86fb92020-05-13 13:05:13 +02006953 /*
6954 * A BdrvChildClass that doesn't handle AioContext changes cannot
6955 * tolerate any AioContext changes
6956 */
6957 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006958 char *user = bdrv_child_user_desc(c);
6959 error_setg(errp, "Changing iothreads is not supported by %s", user);
6960 g_free(user);
6961 return false;
6962 }
Max Reitzbd86fb92020-05-13 13:05:13 +02006963 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006964 assert(!errp || *errp);
6965 return false;
6966 }
6967 return true;
6968}
6969
6970bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6971 GSList **ignore, Error **errp)
6972{
6973 if (g_slist_find(*ignore, c)) {
6974 return true;
6975 }
6976 *ignore = g_slist_prepend(*ignore, c);
6977 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6978}
6979
6980/* @ignore will accumulate all visited BdrvChild object. The caller is
6981 * responsible for freeing the list afterwards. */
6982bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6983 GSList **ignore, Error **errp)
6984{
6985 BdrvChild *c;
6986
6987 if (bdrv_get_aio_context(bs) == ctx) {
6988 return true;
6989 }
6990
6991 QLIST_FOREACH(c, &bs->parents, next_parent) {
6992 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6993 return false;
6994 }
6995 }
6996 QLIST_FOREACH(c, &bs->children, next) {
6997 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6998 return false;
6999 }
7000 }
7001
7002 return true;
7003}
7004
7005int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7006 BdrvChild *ignore_child, Error **errp)
7007{
7008 GSList *ignore;
7009 bool ret;
7010
7011 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7012 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7013 g_slist_free(ignore);
7014
7015 if (!ret) {
7016 return -EPERM;
7017 }
7018
Kevin Wolf53a7d042019-05-06 19:17:59 +02007019 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7020 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7021 g_slist_free(ignore);
7022
Kevin Wolf5d231842019-05-06 19:17:56 +02007023 return 0;
7024}
7025
7026int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7027 Error **errp)
7028{
7029 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7030}
7031
Max Reitz33384422014-06-20 21:57:33 +02007032void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7033 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7034 void (*detach_aio_context)(void *opaque), void *opaque)
7035{
7036 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7037 *ban = (BdrvAioNotifier){
7038 .attached_aio_context = attached_aio_context,
7039 .detach_aio_context = detach_aio_context,
7040 .opaque = opaque
7041 };
7042
7043 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7044}
7045
7046void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7047 void (*attached_aio_context)(AioContext *,
7048 void *),
7049 void (*detach_aio_context)(void *),
7050 void *opaque)
7051{
7052 BdrvAioNotifier *ban, *ban_next;
7053
7054 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7055 if (ban->attached_aio_context == attached_aio_context &&
7056 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007057 ban->opaque == opaque &&
7058 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007059 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007060 if (bs->walking_aio_notifiers) {
7061 ban->deleted = true;
7062 } else {
7063 bdrv_do_remove_aio_context_notifier(ban);
7064 }
Max Reitz33384422014-06-20 21:57:33 +02007065 return;
7066 }
7067 }
7068
7069 abort();
7070}
7071
Max Reitz77485432014-10-27 11:12:50 +01007072int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007073 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007074 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007075 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007076{
Max Reitzd470ad42017-11-10 21:31:09 +01007077 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007078 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007079 return -ENOMEDIUM;
7080 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007081 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007082 error_setg(errp, "Block driver '%s' does not support option amendment",
7083 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007084 return -ENOTSUP;
7085 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007086 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7087 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007088}
Benoît Canetf6186f42013-10-02 14:33:48 +02007089
Max Reitz5d69b5a2020-02-18 11:34:41 +01007090/*
7091 * This function checks whether the given @to_replace is allowed to be
7092 * replaced by a node that always shows the same data as @bs. This is
7093 * used for example to verify whether the mirror job can replace
7094 * @to_replace by the target mirrored from @bs.
7095 * To be replaceable, @bs and @to_replace may either be guaranteed to
7096 * always show the same data (because they are only connected through
7097 * filters), or some driver may allow replacing one of its children
7098 * because it can guarantee that this child's data is not visible at
7099 * all (for example, for dissenting quorum children that have no other
7100 * parents).
7101 */
7102bool bdrv_recurse_can_replace(BlockDriverState *bs,
7103 BlockDriverState *to_replace)
7104{
Max Reitz93393e62019-06-12 17:03:38 +02007105 BlockDriverState *filtered;
7106
Max Reitz5d69b5a2020-02-18 11:34:41 +01007107 if (!bs || !bs->drv) {
7108 return false;
7109 }
7110
7111 if (bs == to_replace) {
7112 return true;
7113 }
7114
7115 /* See what the driver can do */
7116 if (bs->drv->bdrv_recurse_can_replace) {
7117 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7118 }
7119
7120 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007121 filtered = bdrv_filter_bs(bs);
7122 if (filtered) {
7123 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007124 }
7125
7126 /* Safe default */
7127 return false;
7128}
7129
Max Reitz810803a2020-02-18 11:34:44 +01007130/*
7131 * Check whether the given @node_name can be replaced by a node that
7132 * has the same data as @parent_bs. If so, return @node_name's BDS;
7133 * NULL otherwise.
7134 *
7135 * @node_name must be a (recursive) *child of @parent_bs (or this
7136 * function will return NULL).
7137 *
7138 * The result (whether the node can be replaced or not) is only valid
7139 * for as long as no graph or permission changes occur.
7140 */
Wen Congyange12f3782015-07-17 10:12:22 +08007141BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7142 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007143{
7144 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007145 AioContext *aio_context;
7146
Benoît Canet09158f02014-06-27 18:25:25 +02007147 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007148 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007149 return NULL;
7150 }
7151
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007152 aio_context = bdrv_get_aio_context(to_replace_bs);
7153 aio_context_acquire(aio_context);
7154
Benoît Canet09158f02014-06-27 18:25:25 +02007155 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007156 to_replace_bs = NULL;
7157 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007158 }
7159
7160 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7161 * most non filter in order to prevent data corruption.
7162 * Another benefit is that this tests exclude backing files which are
7163 * blocked by the backing blockers.
7164 */
Max Reitz810803a2020-02-18 11:34:44 +01007165 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7166 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7167 "because it cannot be guaranteed that doing so would not "
7168 "lead to an abrupt change of visible data",
7169 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007170 to_replace_bs = NULL;
7171 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007172 }
7173
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007174out:
7175 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007176 return to_replace_bs;
7177}
Ming Lei448ad912014-07-04 18:04:33 +08007178
Max Reitz97e2f022019-02-01 20:29:27 +01007179/**
7180 * Iterates through the list of runtime option keys that are said to
7181 * be "strong" for a BDS. An option is called "strong" if it changes
7182 * a BDS's data. For example, the null block driver's "size" and
7183 * "read-zeroes" options are strong, but its "latency-ns" option is
7184 * not.
7185 *
7186 * If a key returned by this function ends with a dot, all options
7187 * starting with that prefix are strong.
7188 */
7189static const char *const *strong_options(BlockDriverState *bs,
7190 const char *const *curopt)
7191{
7192 static const char *const global_options[] = {
7193 "driver", "filename", NULL
7194 };
7195
7196 if (!curopt) {
7197 return &global_options[0];
7198 }
7199
7200 curopt++;
7201 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7202 curopt = bs->drv->strong_runtime_opts;
7203 }
7204
7205 return (curopt && *curopt) ? curopt : NULL;
7206}
7207
7208/**
7209 * Copies all strong runtime options from bs->options to the given
7210 * QDict. The set of strong option keys is determined by invoking
7211 * strong_options().
7212 *
7213 * Returns true iff any strong option was present in bs->options (and
7214 * thus copied to the target QDict) with the exception of "filename"
7215 * and "driver". The caller is expected to use this value to decide
7216 * whether the existence of strong options prevents the generation of
7217 * a plain filename.
7218 */
7219static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7220{
7221 bool found_any = false;
7222 const char *const *option_name = NULL;
7223
7224 if (!bs->drv) {
7225 return false;
7226 }
7227
7228 while ((option_name = strong_options(bs, option_name))) {
7229 bool option_given = false;
7230
7231 assert(strlen(*option_name) > 0);
7232 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7233 QObject *entry = qdict_get(bs->options, *option_name);
7234 if (!entry) {
7235 continue;
7236 }
7237
7238 qdict_put_obj(d, *option_name, qobject_ref(entry));
7239 option_given = true;
7240 } else {
7241 const QDictEntry *entry;
7242 for (entry = qdict_first(bs->options); entry;
7243 entry = qdict_next(bs->options, entry))
7244 {
7245 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7246 qdict_put_obj(d, qdict_entry_key(entry),
7247 qobject_ref(qdict_entry_value(entry)));
7248 option_given = true;
7249 }
7250 }
7251 }
7252
7253 /* While "driver" and "filename" need to be included in a JSON filename,
7254 * their existence does not prohibit generation of a plain filename. */
7255 if (!found_any && option_given &&
7256 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7257 {
7258 found_any = true;
7259 }
7260 }
7261
Max Reitz62a01a272019-02-01 20:29:34 +01007262 if (!qdict_haskey(d, "driver")) {
7263 /* Drivers created with bdrv_new_open_driver() may not have a
7264 * @driver option. Add it here. */
7265 qdict_put_str(d, "driver", bs->drv->format_name);
7266 }
7267
Max Reitz97e2f022019-02-01 20:29:27 +01007268 return found_any;
7269}
7270
Max Reitz90993622019-02-01 20:29:09 +01007271/* Note: This function may return false positives; it may return true
7272 * even if opening the backing file specified by bs's image header
7273 * would result in exactly bs->backing. */
Max Reitz0b877d02018-08-01 20:34:11 +02007274bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007275{
7276 if (bs->backing) {
7277 return strcmp(bs->auto_backing_file,
7278 bs->backing->bs->filename);
7279 } else {
7280 /* No backing BDS, so if the image header reports any backing
7281 * file, it must have been suppressed */
7282 return bs->auto_backing_file[0] != '\0';
7283 }
7284}
7285
Max Reitz91af7012014-07-18 20:24:56 +02007286/* Updates the following BDS fields:
7287 * - exact_filename: A filename which may be used for opening a block device
7288 * which (mostly) equals the given BDS (even without any
7289 * other options; so reading and writing must return the same
7290 * results, but caching etc. may be different)
7291 * - full_open_options: Options which, when given when opening a block device
7292 * (without a filename), result in a BDS (mostly)
7293 * equalling the given one
7294 * - filename: If exact_filename is set, it is copied here. Otherwise,
7295 * full_open_options is converted to a JSON object, prefixed with
7296 * "json:" (for use through the JSON pseudo protocol) and put here.
7297 */
7298void bdrv_refresh_filename(BlockDriverState *bs)
7299{
7300 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007301 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007302 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007303 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007304 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007305 bool generate_json_filename; /* Whether our default implementation should
7306 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007307
7308 if (!drv) {
7309 return;
7310 }
7311
Max Reitze24518e2019-02-01 20:29:06 +01007312 /* This BDS's file name may depend on any of its children's file names, so
7313 * refresh those first */
7314 QLIST_FOREACH(child, &bs->children, next) {
7315 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007316 }
7317
Max Reitzbb808d52019-02-01 20:29:07 +01007318 if (bs->implicit) {
7319 /* For implicit nodes, just copy everything from the single child */
7320 child = QLIST_FIRST(&bs->children);
7321 assert(QLIST_NEXT(child, next) == NULL);
7322
7323 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7324 child->bs->exact_filename);
7325 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7326
Pan Nengyuancb895612020-01-16 16:56:00 +08007327 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007328 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7329
7330 return;
7331 }
7332
Max Reitz90993622019-02-01 20:29:09 +01007333 backing_overridden = bdrv_backing_overridden(bs);
7334
7335 if (bs->open_flags & BDRV_O_NO_IO) {
7336 /* Without I/O, the backing file does not change anything.
7337 * Therefore, in such a case (primarily qemu-img), we can
7338 * pretend the backing file has not been overridden even if
7339 * it technically has been. */
7340 backing_overridden = false;
7341 }
7342
Max Reitz97e2f022019-02-01 20:29:27 +01007343 /* Gather the options QDict */
7344 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007345 generate_json_filename = append_strong_runtime_options(opts, bs);
7346 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007347
7348 if (drv->bdrv_gather_child_options) {
7349 /* Some block drivers may not want to present all of their children's
7350 * options, or name them differently from BdrvChild.name */
7351 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7352 } else {
7353 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007354 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007355 /* We can skip the backing BDS if it has not been overridden */
7356 continue;
7357 }
7358
7359 qdict_put(opts, child->name,
7360 qobject_ref(child->bs->full_open_options));
7361 }
7362
7363 if (backing_overridden && !bs->backing) {
7364 /* Force no backing file */
7365 qdict_put_null(opts, "backing");
7366 }
7367 }
7368
7369 qobject_unref(bs->full_open_options);
7370 bs->full_open_options = opts;
7371
Max Reitz52f72d62019-06-12 17:43:03 +02007372 primary_child_bs = bdrv_primary_bs(bs);
7373
Max Reitz998b3a12019-02-01 20:29:28 +01007374 if (drv->bdrv_refresh_filename) {
7375 /* Obsolete information is of no use here, so drop the old file name
7376 * information before refreshing it */
7377 bs->exact_filename[0] = '\0';
7378
7379 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007380 } else if (primary_child_bs) {
7381 /*
7382 * Try to reconstruct valid information from the underlying
7383 * file -- this only works for format nodes (filter nodes
7384 * cannot be probed and as such must be selected by the user
7385 * either through an options dict, or through a special
7386 * filename which the filter driver must construct in its
7387 * .bdrv_refresh_filename() implementation).
7388 */
Max Reitz998b3a12019-02-01 20:29:28 +01007389
7390 bs->exact_filename[0] = '\0';
7391
Max Reitzfb695c72019-02-01 20:29:29 +01007392 /*
7393 * We can use the underlying file's filename if:
7394 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007395 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007396 * - the file is a protocol BDS, and
7397 * - opening that file (as this BDS's format) will automatically create
7398 * the BDS tree we have right now, that is:
7399 * - the user did not significantly change this BDS's behavior with
7400 * some explicit (strong) options
7401 * - no non-file child of this BDS has been overridden by the user
7402 * Both of these conditions are represented by generate_json_filename.
7403 */
Max Reitz52f72d62019-06-12 17:43:03 +02007404 if (primary_child_bs->exact_filename[0] &&
7405 primary_child_bs->drv->bdrv_file_open &&
7406 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007407 {
Max Reitz52f72d62019-06-12 17:43:03 +02007408 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007409 }
7410 }
7411
Max Reitz91af7012014-07-18 20:24:56 +02007412 if (bs->exact_filename[0]) {
7413 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007414 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007415 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007416 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007417 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007418 /* Give user a hint if we truncated things. */
7419 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7420 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007421 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007422 }
7423}
Wen Congyange06018a2016-05-10 15:36:37 +08007424
Max Reitz1e89d0f2019-02-01 20:29:18 +01007425char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7426{
7427 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007428 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007429
7430 if (!drv) {
7431 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7432 return NULL;
7433 }
7434
7435 if (drv->bdrv_dirname) {
7436 return drv->bdrv_dirname(bs, errp);
7437 }
7438
Max Reitz52f72d62019-06-12 17:43:03 +02007439 child_bs = bdrv_primary_bs(bs);
7440 if (child_bs) {
7441 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007442 }
7443
7444 bdrv_refresh_filename(bs);
7445 if (bs->exact_filename[0] != '\0') {
7446 return path_combine(bs->exact_filename, "");
7447 }
7448
7449 error_setg(errp, "Cannot generate a base directory for %s nodes",
7450 drv->format_name);
7451 return NULL;
7452}
7453
Wen Congyange06018a2016-05-10 15:36:37 +08007454/*
7455 * Hot add/remove a BDS's child. So the user can take a child offline when
7456 * it is broken and take a new child online
7457 */
7458void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7459 Error **errp)
7460{
7461
7462 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7463 error_setg(errp, "The node %s does not support adding a child",
7464 bdrv_get_device_or_node_name(parent_bs));
7465 return;
7466 }
7467
7468 if (!QLIST_EMPTY(&child_bs->parents)) {
7469 error_setg(errp, "The node %s already has a parent",
7470 child_bs->node_name);
7471 return;
7472 }
7473
7474 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7475}
7476
7477void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7478{
7479 BdrvChild *tmp;
7480
7481 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7482 error_setg(errp, "The node %s does not support removing a child",
7483 bdrv_get_device_or_node_name(parent_bs));
7484 return;
7485 }
7486
7487 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7488 if (tmp == child) {
7489 break;
7490 }
7491 }
7492
7493 if (!tmp) {
7494 error_setg(errp, "The node %s does not have a child named %s",
7495 bdrv_get_device_or_node_name(parent_bs),
7496 bdrv_get_device_or_node_name(child->bs));
7497 return;
7498 }
7499
7500 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7501}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007502
7503int bdrv_make_empty(BdrvChild *c, Error **errp)
7504{
7505 BlockDriver *drv = c->bs->drv;
7506 int ret;
7507
7508 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7509
7510 if (!drv->bdrv_make_empty) {
7511 error_setg(errp, "%s does not support emptying nodes",
7512 drv->format_name);
7513 return -ENOTSUP;
7514 }
7515
7516 ret = drv->bdrv_make_empty(c->bs);
7517 if (ret < 0) {
7518 error_setg_errno(errp, -ret, "Failed to empty %s",
7519 c->bs->filename);
7520 return ret;
7521 }
7522
7523 return 0;
7524}
Max Reitz9a6fc882019-05-31 15:23:11 +02007525
7526/*
7527 * Return the child that @bs acts as an overlay for, and from which data may be
7528 * copied in COW or COR operations. Usually this is the backing file.
7529 */
7530BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7531{
7532 if (!bs || !bs->drv) {
7533 return NULL;
7534 }
7535
7536 if (bs->drv->is_filter) {
7537 return NULL;
7538 }
7539
7540 if (!bs->backing) {
7541 return NULL;
7542 }
7543
7544 assert(bs->backing->role & BDRV_CHILD_COW);
7545 return bs->backing;
7546}
7547
7548/*
7549 * If @bs acts as a filter for exactly one of its children, return
7550 * that child.
7551 */
7552BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7553{
7554 BdrvChild *c;
7555
7556 if (!bs || !bs->drv) {
7557 return NULL;
7558 }
7559
7560 if (!bs->drv->is_filter) {
7561 return NULL;
7562 }
7563
7564 /* Only one of @backing or @file may be used */
7565 assert(!(bs->backing && bs->file));
7566
7567 c = bs->backing ?: bs->file;
7568 if (!c) {
7569 return NULL;
7570 }
7571
7572 assert(c->role & BDRV_CHILD_FILTERED);
7573 return c;
7574}
7575
7576/*
7577 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7578 * whichever is non-NULL.
7579 *
7580 * Return NULL if both are NULL.
7581 */
7582BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7583{
7584 BdrvChild *cow_child = bdrv_cow_child(bs);
7585 BdrvChild *filter_child = bdrv_filter_child(bs);
7586
7587 /* Filter nodes cannot have COW backing files */
7588 assert(!(cow_child && filter_child));
7589
7590 return cow_child ?: filter_child;
7591}
7592
7593/*
7594 * Return the primary child of this node: For filters, that is the
7595 * filtered child. For other nodes, that is usually the child storing
7596 * metadata.
7597 * (A generally more helpful description is that this is (usually) the
7598 * child that has the same filename as @bs.)
7599 *
7600 * Drivers do not necessarily have a primary child; for example quorum
7601 * does not.
7602 */
7603BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7604{
7605 BdrvChild *c, *found = NULL;
7606
7607 QLIST_FOREACH(c, &bs->children, next) {
7608 if (c->role & BDRV_CHILD_PRIMARY) {
7609 assert(!found);
7610 found = c;
7611 }
7612 }
7613
7614 return found;
7615}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007616
7617static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7618 bool stop_on_explicit_filter)
7619{
7620 BdrvChild *c;
7621
7622 if (!bs) {
7623 return NULL;
7624 }
7625
7626 while (!(stop_on_explicit_filter && !bs->implicit)) {
7627 c = bdrv_filter_child(bs);
7628 if (!c) {
7629 /*
7630 * A filter that is embedded in a working block graph must
7631 * have a child. Assert this here so this function does
7632 * not return a filter node that is not expected by the
7633 * caller.
7634 */
7635 assert(!bs->drv || !bs->drv->is_filter);
7636 break;
7637 }
7638 bs = c->bs;
7639 }
7640 /*
7641 * Note that this treats nodes with bs->drv == NULL as not being
7642 * filters (bs->drv == NULL should be replaced by something else
7643 * anyway).
7644 * The advantage of this behavior is that this function will thus
7645 * always return a non-NULL value (given a non-NULL @bs).
7646 */
7647
7648 return bs;
7649}
7650
7651/*
7652 * Return the first BDS that has not been added implicitly or that
7653 * does not have a filtered child down the chain starting from @bs
7654 * (including @bs itself).
7655 */
7656BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7657{
7658 return bdrv_do_skip_filters(bs, true);
7659}
7660
7661/*
7662 * Return the first BDS that does not have a filtered child down the
7663 * chain starting from @bs (including @bs itself).
7664 */
7665BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7666{
7667 return bdrv_do_skip_filters(bs, false);
7668}
7669
7670/*
7671 * For a backing chain, return the first non-filter backing image of
7672 * the first non-filter image.
7673 */
7674BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7675{
7676 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7677}