blob: 4d5c60f2aeb3311463970a3bd183643d2e37beca [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-Ogievskiyb0defa82021-04-28 18:17:38 +030052#include "qemu/transactions.h"
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +030053#include "block/coroutines.h"
bellardfc01f7e2003-06-30 10:03:06 +000054
Juan Quintela71e72a12009-07-27 16:12:56 +020055#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000056#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000057#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000058#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000059#include <sys/disk.h>
60#endif
blueswir1c5e97232009-03-07 20:06:23 +000061#endif
bellard7674e7b2005-04-26 21:59:26 +000062
aliguori49dc7682009-03-08 16:26:59 +000063#ifdef _WIN32
64#include <windows.h>
65#endif
66
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010067#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
68
Benoît Canetdc364f42014-01-23 21:31:32 +010069static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
70 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
71
Max Reitz2c1d04e2016-01-29 16:36:11 +010072static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
73 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
74
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010075static QLIST_HEAD(, BlockDriver) bdrv_drivers =
76 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000077
Max Reitz5b363932016-05-17 16:41:31 +020078static BlockDriverState *bdrv_open_inherit(const char *filename,
79 const char *reference,
80 QDict *options, int flags,
81 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +020082 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +020083 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +020084 Error **errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +020085
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +030086static void bdrv_replace_child_noperm(BdrvChild *child,
87 BlockDriverState *new_bs);
88
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +030089static int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue
90 *queue, Error **errp);
91static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
92static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
93
Markus Armbrustereb852012009-10-27 18:41:44 +010094/* If non-zero, use only whitelisted block drivers */
95static int use_bdrv_whitelist;
96
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000097#ifdef _WIN32
98static int is_windows_drive_prefix(const char *filename)
99{
100 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
101 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
102 filename[1] == ':');
103}
104
105int is_windows_drive(const char *filename)
106{
107 if (is_windows_drive_prefix(filename) &&
108 filename[2] == '\0')
109 return 1;
110 if (strstart(filename, "\\\\.\\", NULL) ||
111 strstart(filename, "//./", NULL))
112 return 1;
113 return 0;
114}
115#endif
116
Kevin Wolf339064d2013-11-28 10:23:32 +0100117size_t bdrv_opt_mem_align(BlockDriverState *bs)
118{
119 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300120 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800121 return MAX(4096, qemu_real_host_page_size);
Kevin Wolf339064d2013-11-28 10:23:32 +0100122 }
123
124 return bs->bl.opt_mem_alignment;
125}
126
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300127size_t bdrv_min_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);
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300132 }
133
134 return bs->bl.min_mem_alignment;
135}
136
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000137/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100138int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000139{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200140 const char *p;
141
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000142#ifdef _WIN32
143 if (is_windows_drive(path) ||
144 is_windows_drive_prefix(path)) {
145 return 0;
146 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200147 p = path + strcspn(path, ":/\\");
148#else
149 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000150#endif
151
Paolo Bonzini947995c2012-05-08 16:51:48 +0200152 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000153}
154
bellard83f64092006-08-01 16:21:11 +0000155int path_is_absolute(const char *path)
156{
bellard21664422007-01-07 18:22:37 +0000157#ifdef _WIN32
158 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200159 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000160 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200161 }
162 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000163#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200164 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000165#endif
bellard83f64092006-08-01 16:21:11 +0000166}
167
Max Reitz009b03a2019-02-01 20:29:13 +0100168/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000169 path to it by considering it is relative to base_path. URL are
170 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100171char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000172{
Max Reitz009b03a2019-02-01 20:29:13 +0100173 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000174 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100175 char *result;
bellard83f64092006-08-01 16:21:11 +0000176 int len;
177
bellard83f64092006-08-01 16:21:11 +0000178 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100179 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000180 }
Max Reitz009b03a2019-02-01 20:29:13 +0100181
182 if (path_has_protocol(base_path)) {
183 protocol_stripped = strchr(base_path, ':');
184 if (protocol_stripped) {
185 protocol_stripped++;
186 }
187 }
188 p = protocol_stripped ?: base_path;
189
190 p1 = strrchr(base_path, '/');
191#ifdef _WIN32
192 {
193 const char *p2;
194 p2 = strrchr(base_path, '\\');
195 if (!p1 || p2 > p1) {
196 p1 = p2;
197 }
198 }
199#endif
200 if (p1) {
201 p1++;
202 } else {
203 p1 = base_path;
204 }
205 if (p1 > p) {
206 p = p1;
207 }
208 len = p - base_path;
209
210 result = g_malloc(len + strlen(filename) + 1);
211 memcpy(result, base_path, len);
212 strcpy(result + len, filename);
213
214 return result;
215}
216
Max Reitz03c320d2017-05-22 21:52:16 +0200217/*
218 * Helper function for bdrv_parse_filename() implementations to remove optional
219 * protocol prefixes (especially "file:") from a filename and for putting the
220 * stripped filename into the options QDict if there is such a prefix.
221 */
222void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
223 QDict *options)
224{
225 if (strstart(filename, prefix, &filename)) {
226 /* Stripping the explicit protocol prefix may result in a protocol
227 * prefix being (wrongly) detected (if the filename contains a colon) */
228 if (path_has_protocol(filename)) {
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100229 GString *fat_filename;
Max Reitz03c320d2017-05-22 21:52:16 +0200230
231 /* This means there is some colon before the first slash; therefore,
232 * this cannot be an absolute path */
233 assert(!path_is_absolute(filename));
234
235 /* And we can thus fix the protocol detection issue by prefixing it
236 * by "./" */
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100237 fat_filename = g_string_new("./");
238 g_string_append(fat_filename, filename);
Max Reitz03c320d2017-05-22 21:52:16 +0200239
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100240 assert(!path_has_protocol(fat_filename->str));
Max Reitz03c320d2017-05-22 21:52:16 +0200241
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100242 qdict_put(options, "filename",
243 qstring_from_gstring(fat_filename));
Max Reitz03c320d2017-05-22 21:52:16 +0200244 } else {
245 /* If no protocol prefix was detected, we can use the shortened
246 * filename as-is */
247 qdict_put_str(options, "filename", filename);
248 }
249 }
250}
251
252
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200253/* Returns whether the image file is opened as read-only. Note that this can
254 * return false and writing to the image file is still not possible because the
255 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400256bool bdrv_is_read_only(BlockDriverState *bs)
257{
258 return bs->read_only;
259}
260
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200261int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
262 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400263{
Jeff Codye2b82472017-04-07 16:55:26 -0400264 /* Do not set read_only if copy_on_read is enabled */
265 if (bs->copy_on_read && read_only) {
266 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
267 bdrv_get_device_or_node_name(bs));
268 return -EINVAL;
269 }
270
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400271 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200272 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
273 !ignore_allow_rdw)
274 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400275 error_setg(errp, "Node '%s' is read only",
276 bdrv_get_device_or_node_name(bs));
277 return -EPERM;
278 }
279
Jeff Cody45803a02017-04-07 16:55:29 -0400280 return 0;
281}
282
Kevin Wolfeaa24102018-10-12 11:27:41 +0200283/*
284 * Called by a driver that can only provide a read-only image.
285 *
286 * Returns 0 if the node is already read-only or it could switch the node to
287 * read-only because BDRV_O_AUTO_RDONLY is set.
288 *
289 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
290 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
291 * is not NULL, it is used as the error message for the Error object.
292 */
293int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
294 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400295{
296 int ret = 0;
297
Kevin Wolfeaa24102018-10-12 11:27:41 +0200298 if (!(bs->open_flags & BDRV_O_RDWR)) {
299 return 0;
300 }
301 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
302 goto fail;
303 }
304
305 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400306 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200307 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400308 }
309
Kevin Wolfeaa24102018-10-12 11:27:41 +0200310 bs->read_only = true;
311 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200312
Jeff Codye2b82472017-04-07 16:55:26 -0400313 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200314
315fail:
316 error_setg(errp, "%s", errmsg ?: "Image is read-only");
317 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400318}
319
Max Reitz645ae7d2019-02-01 20:29:14 +0100320/*
321 * If @backing is empty, this function returns NULL without setting
322 * @errp. In all other cases, NULL will only be returned with @errp
323 * set.
324 *
325 * Therefore, a return value of NULL without @errp set means that
326 * there is no backing file; if @errp is set, there is one but its
327 * absolute filename cannot be generated.
328 */
329char *bdrv_get_full_backing_filename_from_filename(const char *backed,
330 const char *backing,
331 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100332{
Max Reitz645ae7d2019-02-01 20:29:14 +0100333 if (backing[0] == '\0') {
334 return NULL;
335 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
336 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100337 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
338 error_setg(errp, "Cannot use relative backing file names for '%s'",
339 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100340 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100341 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100342 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100343 }
344}
345
Max Reitz9f4793d2019-02-01 20:29:16 +0100346/*
347 * If @filename is empty or NULL, this function returns NULL without
348 * setting @errp. In all other cases, NULL will only be returned with
349 * @errp set.
350 */
351static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
352 const char *filename, Error **errp)
353{
Max Reitz8df68612019-02-01 20:29:23 +0100354 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100355
Max Reitz8df68612019-02-01 20:29:23 +0100356 if (!filename || filename[0] == '\0') {
357 return NULL;
358 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
359 return g_strdup(filename);
360 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100361
Max Reitz8df68612019-02-01 20:29:23 +0100362 dir = bdrv_dirname(relative_to, errp);
363 if (!dir) {
364 return NULL;
365 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100366
Max Reitz8df68612019-02-01 20:29:23 +0100367 full_name = g_strconcat(dir, filename, NULL);
368 g_free(dir);
369 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100370}
371
Max Reitz6b6833c2019-02-01 20:29:15 +0100372char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200373{
Max Reitz9f4793d2019-02-01 20:29:16 +0100374 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200375}
376
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100377void bdrv_register(BlockDriver *bdrv)
378{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100379 assert(bdrv->format_name);
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100380 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000381}
bellardb3380822004-03-14 21:38:54 +0000382
Markus Armbrustere4e99862014-10-07 13:59:03 +0200383BlockDriverState *bdrv_new(void)
384{
385 BlockDriverState *bs;
386 int i;
387
Markus Armbruster5839e532014-08-19 10:31:08 +0200388 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800389 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800390 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
391 QLIST_INIT(&bs->op_blockers[i]);
392 }
Stefan Hajnoczid616b222013-06-24 17:13:10 +0200393 notifier_with_return_list_init(&bs->before_write_notifiers);
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200394 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200395 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800396 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200397 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200398
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300399 qemu_co_queue_init(&bs->flush_queue);
400
Kevin Wolf0f122642018-03-28 18:29:18 +0200401 for (i = 0; i < bdrv_drain_all_count; i++) {
402 bdrv_drained_begin(bs);
403 }
404
Max Reitz2c1d04e2016-01-29 16:36:11 +0100405 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
406
bellardb3380822004-03-14 21:38:54 +0000407 return bs;
408}
409
Marc Mari88d88792016-08-12 09:27:03 -0400410static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000411{
412 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400413
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100414 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
415 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000416 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100417 }
bellardea2384d2004-08-01 21:59:26 +0000418 }
Marc Mari88d88792016-08-12 09:27:03 -0400419
bellardea2384d2004-08-01 21:59:26 +0000420 return NULL;
421}
422
Marc Mari88d88792016-08-12 09:27:03 -0400423BlockDriver *bdrv_find_format(const char *format_name)
424{
425 BlockDriver *drv1;
426 int i;
427
428 drv1 = bdrv_do_find_format(format_name);
429 if (drv1) {
430 return drv1;
431 }
432
433 /* The driver isn't registered, maybe we need to load a module */
434 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
435 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
436 block_module_load_one(block_driver_modules[i].library_name);
437 break;
438 }
439 }
440
441 return bdrv_do_find_format(format_name);
442}
443
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300444static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100445{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800446 static const char *whitelist_rw[] = {
447 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200448 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800449 };
450 static const char *whitelist_ro[] = {
451 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200452 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100453 };
454 const char **p;
455
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800456 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100457 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800458 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100459
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800460 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300461 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100462 return 1;
463 }
464 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800465 if (read_only) {
466 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300467 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800468 return 1;
469 }
470 }
471 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100472 return 0;
473}
474
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300475int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
476{
477 return bdrv_format_is_whitelisted(drv->format_name, read_only);
478}
479
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000480bool bdrv_uses_whitelist(void)
481{
482 return use_bdrv_whitelist;
483}
484
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800485typedef struct CreateCo {
486 BlockDriver *drv;
487 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800488 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800489 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200490 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800491} CreateCo;
492
493static void coroutine_fn bdrv_create_co_entry(void *opaque)
494{
Max Reitzcc84d902013-09-06 17:14:26 +0200495 Error *local_err = NULL;
496 int ret;
497
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800498 CreateCo *cco = opaque;
499 assert(cco->drv);
500
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200501 ret = cco->drv->bdrv_co_create_opts(cco->drv,
502 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300503 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200504 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800505}
506
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200507int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800508 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000509{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800510 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200511
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800512 Coroutine *co;
513 CreateCo cco = {
514 .drv = drv,
515 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800516 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800517 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200518 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800519 };
520
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100521 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200522 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300523 ret = -ENOTSUP;
524 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800525 }
526
527 if (qemu_in_coroutine()) {
528 /* Fast-path if already in coroutine context */
529 bdrv_create_co_entry(&cco);
530 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200531 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
532 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800533 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200534 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800535 }
536 }
537
538 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200539 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100540 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200541 error_propagate(errp, cco.err);
542 } else {
543 error_setg_errno(errp, -ret, "Could not create image");
544 }
545 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800546
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300547out:
548 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800549 return ret;
bellardea2384d2004-08-01 21:59:26 +0000550}
551
Max Reitzfd171462020-01-22 17:45:29 +0100552/**
553 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
554 * least the given @minimum_size.
555 *
556 * On success, return @blk's actual length.
557 * Otherwise, return -errno.
558 */
559static int64_t create_file_fallback_truncate(BlockBackend *blk,
560 int64_t minimum_size, Error **errp)
561{
562 Error *local_err = NULL;
563 int64_t size;
564 int ret;
565
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200566 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
567 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100568 if (ret < 0 && ret != -ENOTSUP) {
569 error_propagate(errp, local_err);
570 return ret;
571 }
572
573 size = blk_getlength(blk);
574 if (size < 0) {
575 error_free(local_err);
576 error_setg_errno(errp, -size,
577 "Failed to inquire the new image file's length");
578 return size;
579 }
580
581 if (size < minimum_size) {
582 /* Need to grow the image, but we failed to do that */
583 error_propagate(errp, local_err);
584 return -ENOTSUP;
585 }
586
587 error_free(local_err);
588 local_err = NULL;
589
590 return size;
591}
592
593/**
594 * Helper function for bdrv_create_file_fallback(): Zero the first
595 * sector to remove any potentially pre-existing image header.
596 */
597static int create_file_fallback_zero_first_sector(BlockBackend *blk,
598 int64_t current_size,
599 Error **errp)
600{
601 int64_t bytes_to_clear;
602 int ret;
603
604 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
605 if (bytes_to_clear) {
606 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
607 if (ret < 0) {
608 error_setg_errno(errp, -ret,
609 "Failed to clear the new image's first sector");
610 return ret;
611 }
612 }
613
614 return 0;
615}
616
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200617/**
618 * Simple implementation of bdrv_co_create_opts for protocol drivers
619 * which only support creation via opening a file
620 * (usually existing raw storage device)
621 */
622int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
623 const char *filename,
624 QemuOpts *opts,
625 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100626{
627 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100628 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100629 int64_t size = 0;
630 char *buf = NULL;
631 PreallocMode prealloc;
632 Error *local_err = NULL;
633 int ret;
634
635 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
636 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
637 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
638 PREALLOC_MODE_OFF, &local_err);
639 g_free(buf);
640 if (local_err) {
641 error_propagate(errp, local_err);
642 return -EINVAL;
643 }
644
645 if (prealloc != PREALLOC_MODE_OFF) {
646 error_setg(errp, "Unsupported preallocation mode '%s'",
647 PreallocMode_str(prealloc));
648 return -ENOTSUP;
649 }
650
Max Reitzeeea1fa2020-02-25 16:56:18 +0100651 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100652 qdict_put_str(options, "driver", drv->format_name);
653
654 blk = blk_new_open(filename, NULL, options,
655 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
656 if (!blk) {
657 error_prepend(errp, "Protocol driver '%s' does not support image "
658 "creation, and opening the image failed: ",
659 drv->format_name);
660 return -EINVAL;
661 }
662
663 size = create_file_fallback_truncate(blk, size, errp);
664 if (size < 0) {
665 ret = size;
666 goto out;
667 }
668
669 ret = create_file_fallback_zero_first_sector(blk, size, errp);
670 if (ret < 0) {
671 goto out;
672 }
673
674 ret = 0;
675out:
676 blk_unref(blk);
677 return ret;
678}
679
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800680int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200681{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100682 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200683 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100684 QDict *qdict;
685 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200686
Max Reitzb65a5e12015-02-05 13:58:12 -0500687 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200688 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000689 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200690 }
691
Stefano Garzarella729222a2021-03-08 17:12:32 +0100692 if (!drv->create_opts) {
693 error_setg(errp, "Driver '%s' does not support image creation",
694 drv->format_name);
695 return -ENOTSUP;
696 }
697
698 /*
699 * 'opts' contains a QemuOptsList with a combination of format and protocol
700 * default values.
701 *
702 * The format properly removes its options, but the default values remain
703 * in 'opts->list'. So if the protocol has options with the same name
704 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
705 * of the format, since for overlapping options, the format wins.
706 *
707 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
708 * only the set options, and then convert it back to QemuOpts, using the
709 * create_opts of the protocol. So the new QemuOpts, will contain only the
710 * protocol defaults.
711 */
712 qdict = qemu_opts_to_qdict(opts, NULL);
713 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
714 if (protocol_opts == NULL) {
715 ret = -EINVAL;
716 goto out;
717 }
718
719 ret = bdrv_create(drv, filename, protocol_opts, errp);
720out:
721 qemu_opts_del(protocol_opts);
722 qobject_unref(qdict);
723 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200724}
725
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300726int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
727{
728 Error *local_err = NULL;
729 int ret;
730
731 assert(bs != NULL);
732
733 if (!bs->drv) {
734 error_setg(errp, "Block node '%s' is not opened", bs->filename);
735 return -ENOMEDIUM;
736 }
737
738 if (!bs->drv->bdrv_co_delete_file) {
739 error_setg(errp, "Driver '%s' does not support image deletion",
740 bs->drv->format_name);
741 return -ENOTSUP;
742 }
743
744 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
745 if (ret < 0) {
746 error_propagate(errp, local_err);
747 }
748
749 return ret;
750}
751
Maxim Levitskya890f082020-12-17 19:09:03 +0200752void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
753{
754 Error *local_err = NULL;
755 int ret;
756
757 if (!bs) {
758 return;
759 }
760
761 ret = bdrv_co_delete_file(bs, &local_err);
762 /*
763 * ENOTSUP will happen if the block driver doesn't support
764 * the 'bdrv_co_delete_file' interface. This is a predictable
765 * scenario and shouldn't be reported back to the user.
766 */
767 if (ret == -ENOTSUP) {
768 error_free(local_err);
769 } else if (ret < 0) {
770 error_report_err(local_err);
771 }
772}
773
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100774/**
775 * Try to get @bs's logical and physical block size.
776 * On success, store them in @bsz struct and return 0.
777 * On failure return -errno.
778 * @bs must not be empty.
779 */
780int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
781{
782 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200783 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100784
785 if (drv && drv->bdrv_probe_blocksizes) {
786 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200787 } else if (filtered) {
788 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100789 }
790
791 return -ENOTSUP;
792}
793
794/**
795 * Try to get @bs's geometry (cyls, heads, sectors).
796 * On success, store them in @geo struct and return 0.
797 * On failure return -errno.
798 * @bs must not be empty.
799 */
800int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
801{
802 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200803 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100804
805 if (drv && drv->bdrv_probe_geometry) {
806 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200807 } else if (filtered) {
808 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100809 }
810
811 return -ENOTSUP;
812}
813
Jim Meyeringeba25052012-05-28 09:27:54 +0200814/*
815 * Create a uniquely-named empty temporary file.
816 * Return 0 upon success, otherwise a negative errno value.
817 */
818int get_tmp_filename(char *filename, int size)
819{
bellardd5249392004-08-03 21:14:23 +0000820#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000821 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200822 /* GetTempFileName requires that its output buffer (4th param)
823 have length MAX_PATH or greater. */
824 assert(size >= MAX_PATH);
825 return (GetTempPath(MAX_PATH, temp_dir)
826 && GetTempFileName(temp_dir, "qem", 0, filename)
827 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000828#else
bellardea2384d2004-08-01 21:59:26 +0000829 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000830 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000831 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530832 if (!tmpdir) {
833 tmpdir = "/var/tmp";
834 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200835 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
836 return -EOVERFLOW;
837 }
bellardea2384d2004-08-01 21:59:26 +0000838 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800839 if (fd < 0) {
840 return -errno;
841 }
842 if (close(fd) != 0) {
843 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200844 return -errno;
845 }
846 return 0;
bellardd5249392004-08-03 21:14:23 +0000847#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200848}
bellardea2384d2004-08-01 21:59:26 +0000849
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200850/*
851 * Detect host devices. By convention, /dev/cdrom[N] is always
852 * recognized as a host CDROM.
853 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200854static BlockDriver *find_hdev_driver(const char *filename)
855{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200856 int score_max = 0, score;
857 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200858
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100859 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200860 if (d->bdrv_probe_device) {
861 score = d->bdrv_probe_device(filename);
862 if (score > score_max) {
863 score_max = score;
864 drv = d;
865 }
866 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200867 }
868
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200869 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200870}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200871
Marc Mari88d88792016-08-12 09:27:03 -0400872static BlockDriver *bdrv_do_find_protocol(const char *protocol)
873{
874 BlockDriver *drv1;
875
876 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
877 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
878 return drv1;
879 }
880 }
881
882 return NULL;
883}
884
Kevin Wolf98289622013-07-10 15:47:39 +0200885BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500886 bool allow_protocol_prefix,
887 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200888{
889 BlockDriver *drv1;
890 char protocol[128];
891 int len;
892 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400893 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200894
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200895 /* TODO Drivers without bdrv_file_open must be specified explicitly */
896
Christoph Hellwig39508e72010-06-23 12:25:17 +0200897 /*
898 * XXX(hch): we really should not let host device detection
899 * override an explicit protocol specification, but moving this
900 * later breaks access to device names with colons in them.
901 * Thanks to the brain-dead persistent naming schemes on udev-
902 * based Linux systems those actually are quite common.
903 */
904 drv1 = find_hdev_driver(filename);
905 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200906 return drv1;
907 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200908
Kevin Wolf98289622013-07-10 15:47:39 +0200909 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100910 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200911 }
Kevin Wolf98289622013-07-10 15:47:39 +0200912
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000913 p = strchr(filename, ':');
914 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200915 len = p - filename;
916 if (len > sizeof(protocol) - 1)
917 len = sizeof(protocol) - 1;
918 memcpy(protocol, filename, len);
919 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400920
921 drv1 = bdrv_do_find_protocol(protocol);
922 if (drv1) {
923 return drv1;
924 }
925
926 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
927 if (block_driver_modules[i].protocol_name &&
928 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
929 block_module_load_one(block_driver_modules[i].library_name);
930 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200931 }
932 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500933
Marc Mari88d88792016-08-12 09:27:03 -0400934 drv1 = bdrv_do_find_protocol(protocol);
935 if (!drv1) {
936 error_setg(errp, "Unknown protocol '%s'", protocol);
937 }
938 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200939}
940
Markus Armbrusterc6684242014-11-20 16:27:10 +0100941/*
942 * Guess image format by probing its contents.
943 * This is not a good idea when your image is raw (CVE-2008-2004), but
944 * we do it anyway for backward compatibility.
945 *
946 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100947 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
948 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100949 * @filename is its filename.
950 *
951 * For all block drivers, call the bdrv_probe() method to get its
952 * probing score.
953 * Return the first block driver with the highest probing score.
954 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100955BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
956 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100957{
958 int score_max = 0, score;
959 BlockDriver *drv = NULL, *d;
960
961 QLIST_FOREACH(d, &bdrv_drivers, list) {
962 if (d->bdrv_probe) {
963 score = d->bdrv_probe(buf, buf_size, filename);
964 if (score > score_max) {
965 score_max = score;
966 drv = d;
967 }
968 }
969 }
970
971 return drv;
972}
973
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100974static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200975 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000976{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100977 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100978 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100979 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700980
Kevin Wolf08a00552010-06-01 18:37:31 +0200981 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100982 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100983 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200984 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700985 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700986
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100987 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +0000988 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200989 error_setg_errno(errp, -ret, "Could not read image for determining its "
990 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +0200991 *pdrv = NULL;
992 return ret;
bellard83f64092006-08-01 16:21:11 +0000993 }
994
Markus Armbrusterc6684242014-11-20 16:27:10 +0100995 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +0200996 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200997 error_setg(errp, "Could not determine image format: No compatible "
998 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +0200999 ret = -ENOENT;
1000 }
1001 *pdrv = drv;
1002 return ret;
bellardea2384d2004-08-01 21:59:26 +00001003}
1004
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001005/**
1006 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001007 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001008 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001009int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001010{
1011 BlockDriver *drv = bs->drv;
1012
Max Reitzd470ad42017-11-10 21:31:09 +01001013 if (!drv) {
1014 return -ENOMEDIUM;
1015 }
1016
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001017 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001018 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001019 return 0;
1020
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001021 /* query actual device if possible, otherwise just trust the hint */
1022 if (drv->bdrv_getlength) {
1023 int64_t length = drv->bdrv_getlength(bs);
1024 if (length < 0) {
1025 return length;
1026 }
Fam Zheng7e382002013-11-06 19:48:06 +08001027 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001028 }
1029
1030 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001031
1032 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1033 return -EFBIG;
1034 }
1035
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001036 return 0;
1037}
1038
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001039/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001040 * Combines a QDict of new block driver @options with any missing options taken
1041 * from @old_options, so that leaving out an option defaults to its old value.
1042 */
1043static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1044 QDict *old_options)
1045{
1046 if (bs->drv && bs->drv->bdrv_join_options) {
1047 bs->drv->bdrv_join_options(options, old_options);
1048 } else {
1049 qdict_join(options, old_options, false);
1050 }
1051}
1052
Alberto Garcia543770b2018-09-06 12:37:09 +03001053static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1054 int open_flags,
1055 Error **errp)
1056{
1057 Error *local_err = NULL;
1058 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1059 BlockdevDetectZeroesOptions detect_zeroes =
1060 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1061 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1062 g_free(value);
1063 if (local_err) {
1064 error_propagate(errp, local_err);
1065 return detect_zeroes;
1066 }
1067
1068 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1069 !(open_flags & BDRV_O_UNMAP))
1070 {
1071 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1072 "without setting discard operation to unmap");
1073 }
1074
1075 return detect_zeroes;
1076}
1077
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001078/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001079 * Set open flags for aio engine
1080 *
1081 * Return 0 on success, -1 if the engine specified is invalid
1082 */
1083int bdrv_parse_aio(const char *mode, int *flags)
1084{
1085 if (!strcmp(mode, "threads")) {
1086 /* do nothing, default */
1087 } else if (!strcmp(mode, "native")) {
1088 *flags |= BDRV_O_NATIVE_AIO;
1089#ifdef CONFIG_LINUX_IO_URING
1090 } else if (!strcmp(mode, "io_uring")) {
1091 *flags |= BDRV_O_IO_URING;
1092#endif
1093 } else {
1094 return -1;
1095 }
1096
1097 return 0;
1098}
1099
1100/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001101 * Set open flags for a given discard mode
1102 *
1103 * Return 0 on success, -1 if the discard mode was invalid.
1104 */
1105int bdrv_parse_discard_flags(const char *mode, int *flags)
1106{
1107 *flags &= ~BDRV_O_UNMAP;
1108
1109 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1110 /* do nothing */
1111 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1112 *flags |= BDRV_O_UNMAP;
1113 } else {
1114 return -1;
1115 }
1116
1117 return 0;
1118}
1119
1120/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001121 * Set open flags for a given cache mode
1122 *
1123 * Return 0 on success, -1 if the cache mode was invalid.
1124 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001125int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001126{
1127 *flags &= ~BDRV_O_CACHE_MASK;
1128
1129 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001130 *writethrough = false;
1131 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001132 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001133 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001134 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001135 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001136 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001137 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001138 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001139 *flags |= BDRV_O_NO_FLUSH;
1140 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001141 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001142 } else {
1143 return -1;
1144 }
1145
1146 return 0;
1147}
1148
Kevin Wolfb5411552017-01-17 15:56:16 +01001149static char *bdrv_child_get_parent_desc(BdrvChild *c)
1150{
1151 BlockDriverState *parent = c->opaque;
1152 return g_strdup(bdrv_get_device_or_node_name(parent));
1153}
1154
Kevin Wolf20018e12016-05-23 18:46:59 +02001155static void bdrv_child_cb_drained_begin(BdrvChild *child)
1156{
1157 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001158 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001159}
1160
Kevin Wolf89bd0302018-03-22 14:11:20 +01001161static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1162{
1163 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001164 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001165}
1166
Max Reitze037c092019-07-19 11:26:14 +02001167static void bdrv_child_cb_drained_end(BdrvChild *child,
1168 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001169{
1170 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001171 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001172}
1173
Kevin Wolf38701b62017-05-04 18:52:39 +02001174static int bdrv_child_cb_inactivate(BdrvChild *child)
1175{
1176 BlockDriverState *bs = child->opaque;
1177 assert(bs->open_flags & BDRV_O_INACTIVE);
1178 return 0;
1179}
1180
Kevin Wolf5d231842019-05-06 19:17:56 +02001181static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1182 GSList **ignore, Error **errp)
1183{
1184 BlockDriverState *bs = child->opaque;
1185 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1186}
1187
Kevin Wolf53a7d042019-05-06 19:17:59 +02001188static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1189 GSList **ignore)
1190{
1191 BlockDriverState *bs = child->opaque;
1192 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1193}
1194
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001195/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001196 * Returns the options and flags that a temporary snapshot should get, based on
1197 * the originally requested flags (the originally requested image will have
1198 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001199 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001200static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1201 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001202{
Kevin Wolf73176be2016-03-07 13:02:15 +01001203 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1204
1205 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001206 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1207 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001208
Kevin Wolf3f486862019-04-04 17:04:43 +02001209 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001210 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001211 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001212
Kevin Wolf41869042016-06-16 12:59:30 +02001213 /* aio=native doesn't work for cache.direct=off, so disable it for the
1214 * temporary snapshot */
1215 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001216}
1217
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001218static void bdrv_backing_attach(BdrvChild *c)
1219{
1220 BlockDriverState *parent = c->opaque;
1221 BlockDriverState *backing_hd = c->bs;
1222
1223 assert(!parent->backing_blocker);
1224 error_setg(&parent->backing_blocker,
1225 "node is used as backing hd of '%s'",
1226 bdrv_get_device_or_node_name(parent));
1227
Max Reitzf30c66b2019-02-01 20:29:05 +01001228 bdrv_refresh_filename(backing_hd);
1229
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001230 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001231
1232 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1233 /* Otherwise we won't be able to commit or stream */
1234 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1235 parent->backing_blocker);
1236 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1237 parent->backing_blocker);
1238 /*
1239 * We do backup in 3 ways:
1240 * 1. drive backup
1241 * The target bs is new opened, and the source is top BDS
1242 * 2. blockdev backup
1243 * Both the source and the target are top BDSes.
1244 * 3. internal backup(used for block replication)
1245 * Both the source and the target are backing file
1246 *
1247 * In case 1 and 2, neither the source nor the target is the backing file.
1248 * In case 3, we will block the top BDS, so there is only one block job
1249 * for the top BDS and its backing chain.
1250 */
1251 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1252 parent->backing_blocker);
1253 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1254 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001255}
Kevin Wolfd736f112017-12-18 16:05:48 +01001256
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001257static void bdrv_backing_detach(BdrvChild *c)
1258{
1259 BlockDriverState *parent = c->opaque;
1260
1261 assert(parent->backing_blocker);
1262 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1263 error_free(parent->backing_blocker);
1264 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001265}
Kevin Wolfd736f112017-12-18 16:05:48 +01001266
Kevin Wolf6858eba2017-06-29 19:32:21 +02001267static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1268 const char *filename, Error **errp)
1269{
1270 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001271 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001272 int ret;
1273
Alberto Garciae94d3db2018-11-12 16:00:34 +02001274 if (read_only) {
1275 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001276 if (ret < 0) {
1277 return ret;
1278 }
1279 }
1280
Kevin Wolf6858eba2017-06-29 19:32:21 +02001281 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001282 base->drv ? base->drv->format_name : "",
1283 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001284 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001285 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001286 }
1287
Alberto Garciae94d3db2018-11-12 16:00:34 +02001288 if (read_only) {
1289 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001290 }
1291
Kevin Wolf6858eba2017-06-29 19:32:21 +02001292 return ret;
1293}
1294
Max Reitzfae8bd32020-05-13 13:05:20 +02001295/*
1296 * Returns the options and flags that a generic child of a BDS should
1297 * get, based on the given options and flags for the parent BDS.
1298 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001299static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1300 int *child_flags, QDict *child_options,
1301 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001302{
1303 int flags = parent_flags;
1304
1305 /*
1306 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1307 * Generally, the question to answer is: Should this child be
1308 * format-probed by default?
1309 */
1310
1311 /*
1312 * Pure and non-filtered data children of non-format nodes should
1313 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1314 * set). This only affects a very limited set of drivers (namely
1315 * quorum and blkverify when this comment was written).
1316 * Force-clear BDRV_O_PROTOCOL then.
1317 */
1318 if (!parent_is_format &&
1319 (role & BDRV_CHILD_DATA) &&
1320 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1321 {
1322 flags &= ~BDRV_O_PROTOCOL;
1323 }
1324
1325 /*
1326 * All children of format nodes (except for COW children) and all
1327 * metadata children in general should never be format-probed.
1328 * Force-set BDRV_O_PROTOCOL then.
1329 */
1330 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1331 (role & BDRV_CHILD_METADATA))
1332 {
1333 flags |= BDRV_O_PROTOCOL;
1334 }
1335
1336 /*
1337 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1338 * the parent.
1339 */
1340 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1341 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1342 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1343
1344 if (role & BDRV_CHILD_COW) {
1345 /* backing files are opened read-only by default */
1346 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1347 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1348 } else {
1349 /* Inherit the read-only option from the parent if it's not set */
1350 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1351 qdict_copy_default(child_options, parent_options,
1352 BDRV_OPT_AUTO_READ_ONLY);
1353 }
1354
1355 /*
1356 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1357 * can default to enable it on lower layers regardless of the
1358 * parent option.
1359 */
1360 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1361
1362 /* Clear flags that only apply to the top layer */
1363 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1364
1365 if (role & BDRV_CHILD_METADATA) {
1366 flags &= ~BDRV_O_NO_IO;
1367 }
1368 if (role & BDRV_CHILD_COW) {
1369 flags &= ~BDRV_O_TEMPORARY;
1370 }
1371
1372 *child_flags = flags;
1373}
1374
Max Reitzca2f1232020-05-13 13:05:22 +02001375static void bdrv_child_cb_attach(BdrvChild *child)
1376{
1377 BlockDriverState *bs = child->opaque;
1378
1379 if (child->role & BDRV_CHILD_COW) {
1380 bdrv_backing_attach(child);
1381 }
1382
1383 bdrv_apply_subtree_drain(child, bs);
1384}
1385
Max Reitz48e08282020-05-13 13:05:23 +02001386static void bdrv_child_cb_detach(BdrvChild *child)
1387{
1388 BlockDriverState *bs = child->opaque;
1389
1390 if (child->role & BDRV_CHILD_COW) {
1391 bdrv_backing_detach(child);
1392 }
1393
1394 bdrv_unapply_subtree_drain(child, bs);
1395}
1396
Max Reitz43483552020-05-13 13:05:24 +02001397static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1398 const char *filename, Error **errp)
1399{
1400 if (c->role & BDRV_CHILD_COW) {
1401 return bdrv_backing_update_filename(c, base, filename, errp);
1402 }
1403 return 0;
1404}
1405
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001406static AioContext *bdrv_child_cb_get_parent_aio_context(BdrvChild *c)
1407{
1408 BlockDriverState *bs = c->opaque;
1409
1410 return bdrv_get_aio_context(bs);
1411}
1412
Max Reitz43483552020-05-13 13:05:24 +02001413const BdrvChildClass child_of_bds = {
1414 .parent_is_bds = true,
1415 .get_parent_desc = bdrv_child_get_parent_desc,
1416 .inherit_options = bdrv_inherited_options,
1417 .drained_begin = bdrv_child_cb_drained_begin,
1418 .drained_poll = bdrv_child_cb_drained_poll,
1419 .drained_end = bdrv_child_cb_drained_end,
1420 .attach = bdrv_child_cb_attach,
1421 .detach = bdrv_child_cb_detach,
1422 .inactivate = bdrv_child_cb_inactivate,
1423 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1424 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1425 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001426 .get_parent_aio_context = bdrv_child_cb_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001427};
1428
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001429AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1430{
1431 return c->klass->get_parent_aio_context(c);
1432}
1433
Kevin Wolf7b272452012-11-12 17:05:39 +01001434static int bdrv_open_flags(BlockDriverState *bs, int flags)
1435{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001436 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001437
1438 /*
1439 * Clear flags that are internal to the block layer before opening the
1440 * image.
1441 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001442 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001443
Kevin Wolf7b272452012-11-12 17:05:39 +01001444 return open_flags;
1445}
1446
Kevin Wolf91a097e2015-05-08 17:49:53 +02001447static void update_flags_from_options(int *flags, QemuOpts *opts)
1448{
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001449 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001450
Alberto Garcia57f9db92018-09-06 12:37:06 +03001451 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001452 *flags |= BDRV_O_NO_FLUSH;
1453 }
1454
Alberto Garcia57f9db92018-09-06 12:37:06 +03001455 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001456 *flags |= BDRV_O_NOCACHE;
1457 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001458
Alberto Garcia57f9db92018-09-06 12:37:06 +03001459 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001460 *flags |= BDRV_O_RDWR;
1461 }
1462
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001463 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1464 *flags |= BDRV_O_AUTO_RDONLY;
1465 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001466}
1467
1468static void update_options_from_flags(QDict *options, int flags)
1469{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001470 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001471 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001472 }
1473 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001474 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1475 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001476 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001477 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001478 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001479 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001480 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1481 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1482 flags & BDRV_O_AUTO_RDONLY);
1483 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001484}
1485
Kevin Wolf636ea372014-01-24 14:11:52 +01001486static void bdrv_assign_node_name(BlockDriverState *bs,
1487 const char *node_name,
1488 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001489{
Jeff Cody15489c72015-10-12 19:36:50 -04001490 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001491
Jeff Cody15489c72015-10-12 19:36:50 -04001492 if (!node_name) {
1493 node_name = gen_node_name = id_generate(ID_BLOCK);
1494 } else if (!id_wellformed(node_name)) {
1495 /*
1496 * Check for empty string or invalid characters, but not if it is
1497 * generated (generated names use characters not available to the user)
1498 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001499 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001500 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001501 }
1502
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001503 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001504 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001505 error_setg(errp, "node-name=%s is conflicting with a device id",
1506 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001507 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001508 }
1509
Benoît Canet6913c0c2014-01-23 21:31:33 +01001510 /* takes care of avoiding duplicates node names */
1511 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001512 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001513 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001514 }
1515
Kevin Wolf824808d2018-07-04 13:28:29 +02001516 /* Make sure that the node name isn't truncated */
1517 if (strlen(node_name) >= sizeof(bs->node_name)) {
1518 error_setg(errp, "Node name too long");
1519 goto out;
1520 }
1521
Benoît Canet6913c0c2014-01-23 21:31:33 +01001522 /* copy node name into the bs and insert it into the graph list */
1523 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1524 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001525out:
1526 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001527}
1528
Kevin Wolf01a56502017-01-18 15:51:56 +01001529static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1530 const char *node_name, QDict *options,
1531 int open_flags, Error **errp)
1532{
1533 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001534 int i, ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001535
1536 bdrv_assign_node_name(bs, node_name, &local_err);
1537 if (local_err) {
1538 error_propagate(errp, local_err);
1539 return -EINVAL;
1540 }
1541
1542 bs->drv = drv;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001543 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Kevin Wolf01a56502017-01-18 15:51:56 +01001544 bs->opaque = g_malloc0(drv->instance_size);
1545
1546 if (drv->bdrv_file_open) {
1547 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1548 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001549 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001550 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001551 } else {
1552 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001553 }
1554
1555 if (ret < 0) {
1556 if (local_err) {
1557 error_propagate(errp, local_err);
1558 } else if (bs->filename[0]) {
1559 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1560 } else {
1561 error_setg_errno(errp, -ret, "Could not open image");
1562 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001563 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001564 }
1565
1566 ret = refresh_total_sectors(bs, bs->total_sectors);
1567 if (ret < 0) {
1568 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001569 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001570 }
1571
1572 bdrv_refresh_limits(bs, &local_err);
1573 if (local_err) {
1574 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001575 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001576 }
1577
1578 assert(bdrv_opt_mem_align(bs) != 0);
1579 assert(bdrv_min_mem_align(bs) != 0);
1580 assert(is_power_of_2(bs->bl.request_alignment));
1581
Kevin Wolf0f122642018-03-28 18:29:18 +02001582 for (i = 0; i < bs->quiesce_counter; i++) {
1583 if (drv->bdrv_co_drain_begin) {
1584 drv->bdrv_co_drain_begin(bs);
1585 }
1586 }
1587
Kevin Wolf01a56502017-01-18 15:51:56 +01001588 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001589open_failed:
1590 bs->drv = NULL;
1591 if (bs->file != NULL) {
1592 bdrv_unref_child(bs, bs->file);
1593 bs->file = NULL;
1594 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001595 g_free(bs->opaque);
1596 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001597 return ret;
1598}
1599
Kevin Wolf680c7f92017-01-18 17:16:41 +01001600BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1601 int flags, Error **errp)
1602{
1603 BlockDriverState *bs;
1604 int ret;
1605
1606 bs = bdrv_new();
1607 bs->open_flags = flags;
1608 bs->explicit_options = qdict_new();
1609 bs->options = qdict_new();
1610 bs->opaque = NULL;
1611
1612 update_options_from_flags(bs->options, flags);
1613
1614 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1615 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001616 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001617 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001618 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001619 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001620 bdrv_unref(bs);
1621 return NULL;
1622 }
1623
1624 return bs;
1625}
1626
Kevin Wolfc5f30142016-10-06 11:33:17 +02001627QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001628 .name = "bdrv_common",
1629 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1630 .desc = {
1631 {
1632 .name = "node-name",
1633 .type = QEMU_OPT_STRING,
1634 .help = "Node name of the block device node",
1635 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001636 {
1637 .name = "driver",
1638 .type = QEMU_OPT_STRING,
1639 .help = "Block driver to use for the node",
1640 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001641 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001642 .name = BDRV_OPT_CACHE_DIRECT,
1643 .type = QEMU_OPT_BOOL,
1644 .help = "Bypass software writeback cache on the host",
1645 },
1646 {
1647 .name = BDRV_OPT_CACHE_NO_FLUSH,
1648 .type = QEMU_OPT_BOOL,
1649 .help = "Ignore flush requests",
1650 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001651 {
1652 .name = BDRV_OPT_READ_ONLY,
1653 .type = QEMU_OPT_BOOL,
1654 .help = "Node is opened in read-only mode",
1655 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001656 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001657 .name = BDRV_OPT_AUTO_READ_ONLY,
1658 .type = QEMU_OPT_BOOL,
1659 .help = "Node can become read-only if opening read-write fails",
1660 },
1661 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001662 .name = "detect-zeroes",
1663 .type = QEMU_OPT_STRING,
1664 .help = "try to optimize zero writes (off, on, unmap)",
1665 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001666 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001667 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001668 .type = QEMU_OPT_STRING,
1669 .help = "discard operation (ignore/off, unmap/on)",
1670 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001671 {
1672 .name = BDRV_OPT_FORCE_SHARE,
1673 .type = QEMU_OPT_BOOL,
1674 .help = "always accept other writers (default: off)",
1675 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001676 { /* end of list */ }
1677 },
1678};
1679
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001680QemuOptsList bdrv_create_opts_simple = {
1681 .name = "simple-create-opts",
1682 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001683 .desc = {
1684 {
1685 .name = BLOCK_OPT_SIZE,
1686 .type = QEMU_OPT_SIZE,
1687 .help = "Virtual disk size"
1688 },
1689 {
1690 .name = BLOCK_OPT_PREALLOC,
1691 .type = QEMU_OPT_STRING,
1692 .help = "Preallocation mode (allowed values: off)"
1693 },
1694 { /* end of list */ }
1695 }
1696};
1697
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001698/*
Kevin Wolf57915332010-04-14 15:24:50 +02001699 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001700 *
1701 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001702 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001703static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001704 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001705{
1706 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001707 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001708 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001709 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001710 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001711 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001712 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001713 Error *local_err = NULL;
Kevin Wolf57915332010-04-14 15:24:50 +02001714
Paolo Bonzini64058752012-05-08 16:51:49 +02001715 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001716 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001717
Kevin Wolf62392eb2015-04-24 16:38:02 +02001718 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001719 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001720 ret = -EINVAL;
1721 goto fail_opts;
1722 }
1723
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001724 update_flags_from_options(&bs->open_flags, opts);
1725
Kevin Wolf62392eb2015-04-24 16:38:02 +02001726 driver_name = qemu_opt_get(opts, "driver");
1727 drv = bdrv_find_format(driver_name);
1728 assert(drv != NULL);
1729
Fam Zheng5a9347c2017-05-03 00:35:37 +08001730 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1731
1732 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1733 error_setg(errp,
1734 BDRV_OPT_FORCE_SHARE
1735 "=on can only be used with read-only images");
1736 ret = -EINVAL;
1737 goto fail_opts;
1738 }
1739
Kevin Wolf45673672013-04-22 17:48:40 +02001740 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001741 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001742 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001743 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001744 /*
1745 * Caution: while qdict_get_try_str() is fine, getting
1746 * non-string types would require more care. When @options
1747 * come from -blockdev or blockdev_add, its members are typed
1748 * according to the QAPI schema, but when they come from
1749 * -drive, they're all QString.
1750 */
Kevin Wolf45673672013-04-22 17:48:40 +02001751 filename = qdict_get_try_str(options, "filename");
1752 }
1753
Max Reitz4a008242017-04-13 18:06:24 +02001754 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001755 error_setg(errp, "The '%s' block driver requires a file name",
1756 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001757 ret = -EINVAL;
1758 goto fail_opts;
1759 }
1760
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001761 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1762 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001763
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001764 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001765
1766 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001767 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1768 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1769 } else {
1770 ret = -ENOTSUP;
1771 }
1772 if (ret < 0) {
1773 error_setg(errp,
1774 !bs->read_only && bdrv_is_whitelisted(drv, true)
1775 ? "Driver '%s' can only be used for read-only devices"
1776 : "Driver '%s' is not whitelisted",
1777 drv->format_name);
1778 goto fail_opts;
1779 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001780 }
Kevin Wolf57915332010-04-14 15:24:50 +02001781
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001782 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001783 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001784
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001785 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001786 if (!bs->read_only) {
1787 bdrv_enable_copy_on_read(bs);
1788 } else {
1789 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001790 ret = -EINVAL;
1791 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001792 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001793 }
1794
Alberto Garcia415bbca2018-10-03 13:23:13 +03001795 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001796 if (discard != NULL) {
1797 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1798 error_setg(errp, "Invalid discard option");
1799 ret = -EINVAL;
1800 goto fail_opts;
1801 }
1802 }
1803
Alberto Garcia543770b2018-09-06 12:37:09 +03001804 bs->detect_zeroes =
1805 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1806 if (local_err) {
1807 error_propagate(errp, local_err);
1808 ret = -EINVAL;
1809 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001810 }
1811
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001812 if (filename != NULL) {
1813 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1814 } else {
1815 bs->filename[0] = '\0';
1816 }
Max Reitz91af7012014-07-18 20:24:56 +02001817 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001818
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001819 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001820 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001821 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001822
Kevin Wolf01a56502017-01-18 15:51:56 +01001823 assert(!drv->bdrv_file_open || file == NULL);
1824 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001825 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001826 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001827 }
1828
Kevin Wolf18edf282015-04-07 17:12:56 +02001829 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001830 return 0;
1831
Kevin Wolf18edf282015-04-07 17:12:56 +02001832fail_opts:
1833 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001834 return ret;
1835}
1836
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001837static QDict *parse_json_filename(const char *filename, Error **errp)
1838{
1839 QObject *options_obj;
1840 QDict *options;
1841 int ret;
1842
1843 ret = strstart(filename, "json:", &filename);
1844 assert(ret);
1845
Markus Armbruster5577fff2017-02-28 22:26:59 +01001846 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001847 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001848 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001849 return NULL;
1850 }
1851
Max Reitz7dc847e2018-02-24 16:40:29 +01001852 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001853 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001854 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001855 error_setg(errp, "Invalid JSON object given");
1856 return NULL;
1857 }
1858
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001859 qdict_flatten(options);
1860
1861 return options;
1862}
1863
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001864static void parse_json_protocol(QDict *options, const char **pfilename,
1865 Error **errp)
1866{
1867 QDict *json_options;
1868 Error *local_err = NULL;
1869
1870 /* Parse json: pseudo-protocol */
1871 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1872 return;
1873 }
1874
1875 json_options = parse_json_filename(*pfilename, &local_err);
1876 if (local_err) {
1877 error_propagate(errp, local_err);
1878 return;
1879 }
1880
1881 /* Options given in the filename have lower priority than options
1882 * specified directly */
1883 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001884 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001885 *pfilename = NULL;
1886}
1887
Kevin Wolf57915332010-04-14 15:24:50 +02001888/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001889 * Fills in default options for opening images and converts the legacy
1890 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001891 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1892 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001893 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001894static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001895 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001896{
1897 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001898 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001899 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001900 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001901 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001902
Markus Armbruster129c7d12017-03-30 19:43:12 +02001903 /*
1904 * Caution: while qdict_get_try_str() is fine, getting non-string
1905 * types would require more care. When @options come from
1906 * -blockdev or blockdev_add, its members are typed according to
1907 * the QAPI schema, but when they come from -drive, they're all
1908 * QString.
1909 */
Max Reitz53a29512015-03-19 14:53:16 -04001910 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001911 if (drvname) {
1912 drv = bdrv_find_format(drvname);
1913 if (!drv) {
1914 error_setg(errp, "Unknown driver '%s'", drvname);
1915 return -ENOENT;
1916 }
1917 /* If the user has explicitly specified the driver, this choice should
1918 * override the BDRV_O_PROTOCOL flag */
1919 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001920 }
1921
1922 if (protocol) {
1923 *flags |= BDRV_O_PROTOCOL;
1924 } else {
1925 *flags &= ~BDRV_O_PROTOCOL;
1926 }
1927
Kevin Wolf91a097e2015-05-08 17:49:53 +02001928 /* Translate cache options from flags into options */
1929 update_options_from_flags(*options, *flags);
1930
Kevin Wolff54120f2014-05-26 11:09:59 +02001931 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001932 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001933 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001934 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001935 parse_filename = true;
1936 } else {
1937 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1938 "the same time");
1939 return -EINVAL;
1940 }
1941 }
1942
1943 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001944 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001945 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001946
Max Reitz053e1572015-08-26 19:47:51 +02001947 if (!drvname && protocol) {
1948 if (filename) {
1949 drv = bdrv_find_protocol(filename, parse_filename, errp);
1950 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001951 return -EINVAL;
1952 }
Max Reitz053e1572015-08-26 19:47:51 +02001953
1954 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05001955 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02001956 } else {
1957 error_setg(errp, "Must specify either driver or file");
1958 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001959 }
1960 }
1961
Kevin Wolf17b005f2014-05-27 10:50:29 +02001962 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001963
1964 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001965 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001966 drv->bdrv_parse_filename(filename, *options, &local_err);
1967 if (local_err) {
1968 error_propagate(errp, local_err);
1969 return -EINVAL;
1970 }
1971
1972 if (!drv->bdrv_needs_filename) {
1973 qdict_del(*options, "filename");
1974 }
1975 }
1976
1977 return 0;
1978}
1979
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03001980static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
1981 uint64_t new_used_perm,
1982 uint64_t new_shared_perm,
1983 GSList *ignore_children,
1984 Error **errp);
Fam Zhengc1cef672017-03-14 10:30:50 +08001985
Kevin Wolf148eb132017-09-14 14:32:04 +02001986typedef struct BlockReopenQueueEntry {
1987 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01001988 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02001989 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03001990 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02001991} BlockReopenQueueEntry;
1992
1993/*
1994 * Return the flags that @bs will have after the reopens in @q have
1995 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1996 * return the current flags.
1997 */
1998static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1999{
2000 BlockReopenQueueEntry *entry;
2001
2002 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002003 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002004 if (entry->state.bs == bs) {
2005 return entry->state.flags;
2006 }
2007 }
2008 }
2009
2010 return bs->open_flags;
2011}
2012
2013/* Returns whether the image file can be written to after the reopen queue @q
2014 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002015static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2016 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002017{
2018 int flags = bdrv_reopen_get_flags(q, bs);
2019
2020 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2021}
2022
Max Reitzcc022142018-06-06 21:37:00 +02002023/*
2024 * Return whether the BDS can be written to. This is not necessarily
2025 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2026 * be written to but do not count as read-only images.
2027 */
2028bool bdrv_is_writable(BlockDriverState *bs)
2029{
2030 return bdrv_is_writable_after_reopen(bs, NULL);
2031}
2032
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002033static char *bdrv_child_user_desc(BdrvChild *c)
2034{
2035 if (c->klass->get_parent_desc) {
2036 return c->klass->get_parent_desc(c);
2037 }
2038
2039 return g_strdup("another user");
2040}
2041
2042static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2043{
2044 g_autofree char *user = NULL;
2045 g_autofree char *perm_names = NULL;
2046
2047 if ((b->perm & a->shared_perm) == b->perm) {
2048 return true;
2049 }
2050
2051 perm_names = bdrv_perm_names(b->perm & ~a->shared_perm);
2052 user = bdrv_child_user_desc(a);
2053 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2054 "allow '%s' on %s",
2055 user, a->name, perm_names, bdrv_get_node_name(b->bs));
2056
2057 return false;
2058}
2059
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002060static bool bdrv_parent_perms_conflict(BlockDriverState *bs,
2061 GSList *ignore_children,
2062 Error **errp)
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002063{
2064 BdrvChild *a, *b;
2065
2066 /*
2067 * During the loop we'll look at each pair twice. That's correct because
2068 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2069 * directions.
2070 */
2071 QLIST_FOREACH(a, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002072 if (g_slist_find(ignore_children, a)) {
2073 continue;
2074 }
2075
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002076 QLIST_FOREACH(b, &bs->parents, next_parent) {
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002077 if (a == b || g_slist_find(ignore_children, b)) {
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002078 continue;
2079 }
2080
2081 if (!bdrv_a_allow_b(a, b, errp)) {
2082 return true;
2083 }
2084 }
2085 }
2086
2087 return false;
2088}
2089
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002090static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002091 BdrvChild *c, BdrvChildRole role,
2092 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002093 uint64_t parent_perm, uint64_t parent_shared,
2094 uint64_t *nperm, uint64_t *nshared)
2095{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002096 assert(bs->drv && bs->drv->bdrv_child_perm);
Max Reitze5d8a402020-05-13 13:05:44 +02002097 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002098 parent_perm, parent_shared,
2099 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002100 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002101 if (child_bs && child_bs->force_share) {
2102 *nshared = BLK_PERM_ALL;
2103 }
2104}
2105
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002106/*
2107 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2108 * nodes that are already in the @list, of course) so that final list is
2109 * topologically sorted. Return the result (GSList @list object is updated, so
2110 * don't use old reference after function call).
2111 *
2112 * On function start @list must be already topologically sorted and for any node
2113 * in the @list the whole subtree of the node must be in the @list as well. The
2114 * simplest way to satisfy this criteria: use only result of
2115 * bdrv_topological_dfs() or NULL as @list parameter.
2116 */
2117static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2118 BlockDriverState *bs)
2119{
2120 BdrvChild *child;
2121 g_autoptr(GHashTable) local_found = NULL;
2122
2123 if (!found) {
2124 assert(!list);
2125 found = local_found = g_hash_table_new(NULL, NULL);
2126 }
2127
2128 if (g_hash_table_contains(found, bs)) {
2129 return list;
2130 }
2131 g_hash_table_add(found, bs);
2132
2133 QLIST_FOREACH(child, &bs->children, next) {
2134 list = bdrv_topological_dfs(list, found, child->bs);
2135 }
2136
2137 return g_slist_prepend(list, bs);
2138}
2139
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002140static void bdrv_child_set_perm_commit(void *opaque)
2141{
2142 BdrvChild *c = opaque;
2143
2144 c->has_backup_perm = false;
2145}
2146
2147static void bdrv_child_set_perm_abort(void *opaque)
2148{
2149 BdrvChild *c = opaque;
2150 /*
2151 * We may have child->has_backup_perm unset at this point, as in case of
2152 * _check_ stage of permission update failure we may _check_ not the whole
2153 * subtree. Still, _abort_ is called on the whole subtree anyway.
2154 */
2155 if (c->has_backup_perm) {
2156 c->perm = c->backup_perm;
2157 c->shared_perm = c->backup_shared_perm;
2158 c->has_backup_perm = false;
2159 }
2160}
2161
2162static TransactionActionDrv bdrv_child_set_pem_drv = {
2163 .abort = bdrv_child_set_perm_abort,
2164 .commit = bdrv_child_set_perm_commit,
2165};
2166
2167/*
2168 * With tran=NULL needs to be followed by direct call to either
2169 * bdrv_child_set_perm_commit() or bdrv_child_set_perm_abort().
2170 *
2171 * With non-NULL tran needs to be followed by tran_abort() or tran_commit()
2172 * instead.
2173 */
2174static void bdrv_child_set_perm_safe(BdrvChild *c, uint64_t perm,
2175 uint64_t shared, Transaction *tran)
2176{
2177 if (!c->has_backup_perm) {
2178 c->has_backup_perm = true;
2179 c->backup_perm = c->perm;
2180 c->backup_shared_perm = c->shared_perm;
2181 }
2182 /*
2183 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2184 * same c twice during check_perm procedure
2185 */
2186
2187 c->perm = perm;
2188 c->shared_perm = shared;
2189
2190 if (tran) {
2191 tran_add(tran, &bdrv_child_set_pem_drv, c);
2192 }
2193}
2194
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002195static void bdrv_drv_set_perm_commit(void *opaque)
2196{
2197 BlockDriverState *bs = opaque;
2198 uint64_t cumulative_perms, cumulative_shared_perms;
2199
2200 if (bs->drv->bdrv_set_perm) {
2201 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2202 &cumulative_shared_perms);
2203 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2204 }
2205}
2206
2207static void bdrv_drv_set_perm_abort(void *opaque)
2208{
2209 BlockDriverState *bs = opaque;
2210
2211 if (bs->drv->bdrv_abort_perm_update) {
2212 bs->drv->bdrv_abort_perm_update(bs);
2213 }
2214}
2215
2216TransactionActionDrv bdrv_drv_set_perm_drv = {
2217 .abort = bdrv_drv_set_perm_abort,
2218 .commit = bdrv_drv_set_perm_commit,
2219};
2220
2221static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2222 uint64_t shared_perm, Transaction *tran,
2223 Error **errp)
2224{
2225 if (!bs->drv) {
2226 return 0;
2227 }
2228
2229 if (bs->drv->bdrv_check_perm) {
2230 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2231 if (ret < 0) {
2232 return ret;
2233 }
2234 }
2235
2236 if (tran) {
2237 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2238 }
2239
2240 return 0;
2241}
2242
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002243typedef struct BdrvReplaceChildState {
2244 BdrvChild *child;
2245 BlockDriverState *old_bs;
2246} BdrvReplaceChildState;
2247
2248static void bdrv_replace_child_commit(void *opaque)
2249{
2250 BdrvReplaceChildState *s = opaque;
2251
2252 bdrv_unref(s->old_bs);
2253}
2254
2255static void bdrv_replace_child_abort(void *opaque)
2256{
2257 BdrvReplaceChildState *s = opaque;
2258 BlockDriverState *new_bs = s->child->bs;
2259
2260 /* old_bs reference is transparently moved from @s to @s->child */
2261 bdrv_replace_child_noperm(s->child, s->old_bs);
2262 bdrv_unref(new_bs);
2263}
2264
2265static TransactionActionDrv bdrv_replace_child_drv = {
2266 .commit = bdrv_replace_child_commit,
2267 .abort = bdrv_replace_child_abort,
2268 .clean = g_free,
2269};
2270
2271/*
2272 * bdrv_replace_child_safe
2273 *
2274 * Note: real unref of old_bs is done only on commit.
2275 */
Vladimir Sementsov-Ogievskiy09786232021-04-28 18:17:44 +03002276static void bdrv_replace_child_safe(BdrvChild *child, BlockDriverState *new_bs,
2277 Transaction *tran)
2278{
2279 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2280 *s = (BdrvReplaceChildState) {
2281 .child = child,
2282 .old_bs = child->bs,
2283 };
2284 tran_add(tran, &bdrv_replace_child_drv, s);
2285
2286 if (new_bs) {
2287 bdrv_ref(new_bs);
2288 }
2289 bdrv_replace_child_noperm(child, new_bs);
2290 /* old_bs reference is transparently moved from @child to @s */
2291}
2292
Kevin Wolf33a610c2016-12-15 13:04:20 +01002293/*
2294 * Check whether permissions on this node can be changed in a way that
2295 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
2296 * permissions of all its parents. This involves checking whether all necessary
2297 * permission changes to child nodes can be performed.
2298 *
2299 * A call to this function must always be followed by a call to bdrv_set_perm()
2300 * or bdrv_abort_perm_update().
2301 */
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002302static int bdrv_node_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
2303 uint64_t cumulative_perms,
2304 uint64_t cumulative_shared_perms,
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002305 GSList *ignore_children,
2306 Transaction *tran, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002307{
2308 BlockDriver *drv = bs->drv;
2309 BdrvChild *c;
2310 int ret;
2311
2312 /* Write permissions never work with read-only images */
2313 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002314 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002315 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002316 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2317 error_setg(errp, "Block node is read-only");
2318 } else {
2319 uint64_t current_perms, current_shared;
2320 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2321 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2322 error_setg(errp, "Cannot make block node read-only, there is "
2323 "a writer on it");
2324 } else {
2325 error_setg(errp, "Cannot make block node read-only and create "
2326 "a writer on it");
2327 }
2328 }
2329
Kevin Wolf33a610c2016-12-15 13:04:20 +01002330 return -EPERM;
2331 }
2332
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002333 /*
2334 * Unaligned requests will automatically be aligned to bl.request_alignment
2335 * and without RESIZE we can't extend requests to write to space beyond the
2336 * end of the image, so it's required that the image size is aligned.
2337 */
2338 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2339 !(cumulative_perms & BLK_PERM_RESIZE))
2340 {
2341 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2342 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2343 "Image size is not a multiple of request "
2344 "alignment");
2345 return -EPERM;
2346 }
2347 }
2348
Kevin Wolf33a610c2016-12-15 13:04:20 +01002349 /* Check this node */
2350 if (!drv) {
2351 return 0;
2352 }
2353
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002354 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002355 errp);
2356 if (ret < 0) {
2357 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002358 }
2359
Kevin Wolf78e421c2016-12-20 23:25:12 +01002360 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002361 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002362 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002363 return 0;
2364 }
2365
2366 /* Check all children */
2367 QLIST_FOREACH(c, &bs->children, next) {
2368 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002369
Max Reitze5d8a402020-05-13 13:05:44 +02002370 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002371 cumulative_perms, cumulative_shared_perms,
2372 &cur_perm, &cur_shared);
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002373 bdrv_child_set_perm_safe(c, cur_perm, cur_shared, tran);
2374 }
2375
2376 return 0;
2377}
2378
2379/*
2380 * If use_cumulative_perms is true, use cumulative_perms and
2381 * cumulative_shared_perms for first element of the list. Otherwise just refresh
2382 * all permissions.
2383 */
2384static int bdrv_check_perm_common(GSList *list, BlockReopenQueue *q,
2385 bool use_cumulative_perms,
2386 uint64_t cumulative_perms,
2387 uint64_t cumulative_shared_perms,
2388 GSList *ignore_children,
2389 Transaction *tran, Error **errp)
2390{
2391 int ret;
2392 BlockDriverState *bs;
2393
2394 if (use_cumulative_perms) {
2395 bs = list->data;
2396
2397 ret = bdrv_node_check_perm(bs, q, cumulative_perms,
2398 cumulative_shared_perms,
2399 ignore_children, tran, errp);
2400 if (ret < 0) {
2401 return ret;
2402 }
2403
2404 list = list->next;
2405 }
2406
2407 for ( ; list; list = list->next) {
2408 bs = list->data;
2409
2410 if (bdrv_parent_perms_conflict(bs, ignore_children, errp)) {
2411 return -EINVAL;
2412 }
2413
2414 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2415 &cumulative_shared_perms);
2416
2417 ret = bdrv_node_check_perm(bs, q, cumulative_perms,
2418 cumulative_shared_perms,
2419 ignore_children, tran, errp);
2420 if (ret < 0) {
2421 return ret;
2422 }
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002423 }
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002424
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002425 return 0;
2426}
2427
2428static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
2429 uint64_t cumulative_perms,
2430 uint64_t cumulative_shared_perms,
2431 GSList *ignore_children, Error **errp)
2432{
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002433 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2434 return bdrv_check_perm_common(list, q, true, cumulative_perms,
2435 cumulative_shared_perms, ignore_children,
2436 NULL, errp);
2437}
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002438
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002439static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2440 Transaction *tran, Error **errp)
2441{
2442 return bdrv_check_perm_common(list, q, false, 0, 0, NULL, tran, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002443}
2444
2445/*
2446 * Notifies drivers that after a previous bdrv_check_perm() call, the
2447 * permission update is not performed and any preparations made for it (e.g.
2448 * taken file locks) need to be undone.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002449 */
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002450static void bdrv_node_abort_perm_update(BlockDriverState *bs)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002451{
2452 BlockDriver *drv = bs->drv;
2453 BdrvChild *c;
2454
2455 if (!drv) {
2456 return;
2457 }
2458
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002459 bdrv_drv_set_perm_abort(bs);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002460
2461 QLIST_FOREACH(c, &bs->children, next) {
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002462 bdrv_child_set_perm_abort(c);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002463 }
2464}
2465
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002466static void bdrv_list_abort_perm_update(GSList *list)
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002467{
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002468 for ( ; list; list = list->next) {
2469 bdrv_node_abort_perm_update((BlockDriverState *)list->data);
2470 }
2471}
2472
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002473static void bdrv_abort_perm_update(BlockDriverState *bs)
2474{
2475 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2476 return bdrv_list_abort_perm_update(list);
2477}
2478
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002479static void bdrv_node_set_perm(BlockDriverState *bs)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002480{
2481 BlockDriver *drv = bs->drv;
2482 BdrvChild *c;
2483
2484 if (!drv) {
2485 return;
2486 }
2487
Vladimir Sementsov-Ogievskiy2513ef52021-04-28 18:17:42 +03002488 bdrv_drv_set_perm_commit(bs);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002489
Kevin Wolf78e421c2016-12-20 23:25:12 +01002490 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002491 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002492 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002493 return;
2494 }
2495
2496 /* Update all children */
2497 QLIST_FOREACH(c, &bs->children, next) {
Vladimir Sementsov-Ogievskiy3ef45e02021-04-28 18:17:40 +03002498 bdrv_child_set_perm_commit(c);
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002499 }
2500}
2501
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002502static void bdrv_list_set_perm(GSList *list)
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002503{
Vladimir Sementsov-Ogievskiybd57f8f2021-04-28 18:17:41 +03002504 for ( ; list; list = list->next) {
2505 bdrv_node_set_perm((BlockDriverState *)list->data);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002506 }
2507}
2508
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002509static void bdrv_set_perm(BlockDriverState *bs)
2510{
2511 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2512 return bdrv_list_set_perm(list);
2513}
2514
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002515void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2516 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002517{
2518 BdrvChild *c;
2519 uint64_t cumulative_perms = 0;
2520 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2521
2522 QLIST_FOREACH(c, &bs->parents, next_parent) {
2523 cumulative_perms |= c->perm;
2524 cumulative_shared_perms &= c->shared_perm;
2525 }
2526
2527 *perm = cumulative_perms;
2528 *shared_perm = cumulative_shared_perms;
2529}
2530
Fam Zheng51761962017-05-03 00:35:36 +08002531char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002532{
2533 struct perm_name {
2534 uint64_t perm;
2535 const char *name;
2536 } permissions[] = {
2537 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2538 { BLK_PERM_WRITE, "write" },
2539 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2540 { BLK_PERM_RESIZE, "resize" },
2541 { BLK_PERM_GRAPH_MOD, "change children" },
2542 { 0, NULL }
2543 };
2544
Alberto Garciae2a74232020-01-10 18:15:18 +01002545 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002546 struct perm_name *p;
2547
2548 for (p = permissions; p->name; p++) {
2549 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002550 if (result->len > 0) {
2551 g_string_append(result, ", ");
2552 }
2553 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002554 }
2555 }
2556
Alberto Garciae2a74232020-01-10 18:15:18 +01002557 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002558}
2559
Kevin Wolf33a610c2016-12-15 13:04:20 +01002560/*
2561 * Checks whether a new reference to @bs can be added if the new user requires
Kevin Wolf46181122017-03-06 15:00:13 +01002562 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2563 * set, the BdrvChild objects in this list are ignored in the calculations;
2564 * this allows checking permission updates for an existing reference.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002565 *
2566 * Needs to be followed by a call to either bdrv_set_perm() or
2567 * bdrv_abort_perm_update(). */
Kevin Wolf3121fb42017-09-14 14:42:12 +02002568static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2569 uint64_t new_used_perm,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002570 uint64_t new_shared_perm,
Max Reitz9eab1542019-05-22 19:03:50 +02002571 GSList *ignore_children,
Max Reitz9eab1542019-05-22 19:03:50 +02002572 Error **errp)
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002573{
2574 BdrvChild *c;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002575 uint64_t cumulative_perms = new_used_perm;
2576 uint64_t cumulative_shared_perms = new_shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002577
Max Reitz9eab1542019-05-22 19:03:50 +02002578
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002579 /* There is no reason why anyone couldn't tolerate write_unchanged */
2580 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2581
2582 QLIST_FOREACH(c, &bs->parents, next_parent) {
Kevin Wolf46181122017-03-06 15:00:13 +01002583 if (g_slist_find(ignore_children, c)) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002584 continue;
2585 }
2586
Kevin Wolfd0833192017-01-16 18:26:20 +01002587 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2588 char *user = bdrv_child_user_desc(c);
2589 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
Max Reitz9eab1542019-05-22 19:03:50 +02002590
Kevin Wolfd0833192017-01-16 18:26:20 +01002591 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2592 "allow '%s' on %s",
2593 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2594 g_free(user);
2595 g_free(perm_names);
2596 return -EPERM;
2597 }
2598
2599 if ((c->perm & new_shared_perm) != c->perm) {
2600 char *user = bdrv_child_user_desc(c);
2601 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
Max Reitz9eab1542019-05-22 19:03:50 +02002602
Kevin Wolfd0833192017-01-16 18:26:20 +01002603 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2604 "'%s' on %s",
2605 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2606 g_free(user);
2607 g_free(perm_names);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002608 return -EPERM;
2609 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002610
2611 cumulative_perms |= c->perm;
2612 cumulative_shared_perms &= c->shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002613 }
2614
Kevin Wolf3121fb42017-09-14 14:42:12 +02002615 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002616 ignore_children, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002617}
2618
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002619static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002620{
2621 int ret;
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002622 Transaction *tran = tran_new();
2623 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002624
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002625 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2626 tran_finalize(tran, ret);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002627
Vladimir Sementsov-Ogievskiyb1d2bbe2021-04-28 18:17:43 +03002628 return ret;
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002629}
2630
Kevin Wolf33a610c2016-12-15 13:04:20 +01002631int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2632 Error **errp)
2633{
Max Reitz10467792019-05-22 19:03:51 +02002634 Error *local_err = NULL;
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002635 Transaction *tran = tran_new();
Kevin Wolf33a610c2016-12-15 13:04:20 +01002636 int ret;
2637
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002638 bdrv_child_set_perm_safe(c, perm, shared, tran);
2639
2640 ret = bdrv_refresh_perms(c->bs, &local_err);
2641
2642 tran_finalize(tran, ret);
2643
Kevin Wolf33a610c2016-12-15 13:04:20 +01002644 if (ret < 0) {
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002645 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2646 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002647 error_propagate(errp, local_err);
2648 } else {
2649 /*
2650 * Our caller may intend to only loosen restrictions and
2651 * does not expect this function to fail. Errors are not
2652 * fatal in such a case, so we can just hide them from our
2653 * caller.
2654 */
2655 error_free(local_err);
2656 ret = 0;
2657 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002658 }
2659
Vladimir Sementsov-Ogievskiy83928dc2021-04-28 18:17:39 +03002660 return ret;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002661}
2662
Max Reitzc1087f12019-05-22 19:03:46 +02002663int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2664{
2665 uint64_t parent_perms, parent_shared;
2666 uint64_t perms, shared;
2667
2668 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002669 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002670 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002671
2672 return bdrv_child_try_set_perm(c, perms, shared, errp);
2673}
2674
Max Reitz87278af2020-05-13 13:05:40 +02002675/*
2676 * Default implementation for .bdrv_child_perm() for block filters:
2677 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2678 * filtered child.
2679 */
2680static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002681 BdrvChildRole role,
2682 BlockReopenQueue *reopen_queue,
2683 uint64_t perm, uint64_t shared,
2684 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002685{
Kevin Wolfe444fa82019-08-02 15:59:41 +02002686 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2687 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002688}
2689
Max Reitz70082db2020-05-13 13:05:26 +02002690static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002691 BdrvChildRole role,
2692 BlockReopenQueue *reopen_queue,
2693 uint64_t perm, uint64_t shared,
2694 uint64_t *nperm, uint64_t *nshared)
2695{
Max Reitze5d8a402020-05-13 13:05:44 +02002696 assert(role & BDRV_CHILD_COW);
Max Reitz70082db2020-05-13 13:05:26 +02002697
2698 /*
2699 * We want consistent read from backing files if the parent needs it.
2700 * No other operations are performed on backing files.
2701 */
2702 perm &= BLK_PERM_CONSISTENT_READ;
2703
2704 /*
2705 * If the parent can deal with changing data, we're okay with a
2706 * writable and resizable backing file.
2707 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2708 */
2709 if (shared & BLK_PERM_WRITE) {
2710 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2711 } else {
2712 shared = 0;
2713 }
2714
2715 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2716 BLK_PERM_WRITE_UNCHANGED;
2717
2718 if (bs->open_flags & BDRV_O_INACTIVE) {
2719 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2720 }
2721
2722 *nperm = perm;
2723 *nshared = shared;
2724}
2725
Max Reitz6f838a42020-05-13 13:05:27 +02002726static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002727 BdrvChildRole role,
2728 BlockReopenQueue *reopen_queue,
2729 uint64_t perm, uint64_t shared,
2730 uint64_t *nperm, uint64_t *nshared)
2731{
2732 int flags;
2733
Max Reitze5d8a402020-05-13 13:05:44 +02002734 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002735
2736 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2737
2738 /*
2739 * Apart from the modifications below, the same permissions are
2740 * forwarded and left alone as for filters
2741 */
Max Reitze5d8a402020-05-13 13:05:44 +02002742 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002743 perm, shared, &perm, &shared);
2744
Max Reitzf8890542020-05-13 13:05:28 +02002745 if (role & BDRV_CHILD_METADATA) {
2746 /* Format drivers may touch metadata even if the guest doesn't write */
2747 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2748 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2749 }
2750
2751 /*
2752 * bs->file always needs to be consistent because of the
2753 * metadata. We can never allow other users to resize or write
2754 * to it.
2755 */
2756 if (!(flags & BDRV_O_NO_IO)) {
2757 perm |= BLK_PERM_CONSISTENT_READ;
2758 }
2759 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002760 }
2761
Max Reitzf8890542020-05-13 13:05:28 +02002762 if (role & BDRV_CHILD_DATA) {
2763 /*
2764 * Technically, everything in this block is a subset of the
2765 * BDRV_CHILD_METADATA path taken above, and so this could
2766 * be an "else if" branch. However, that is not obvious, and
2767 * this function is not performance critical, therefore we let
2768 * this be an independent "if".
2769 */
2770
2771 /*
2772 * We cannot allow other users to resize the file because the
2773 * format driver might have some assumptions about the size
2774 * (e.g. because it is stored in metadata, or because the file
2775 * is split into fixed-size data files).
2776 */
2777 shared &= ~BLK_PERM_RESIZE;
2778
2779 /*
2780 * WRITE_UNCHANGED often cannot be performed as such on the
2781 * data file. For example, the qcow2 driver may still need to
2782 * write copied clusters on copy-on-read.
2783 */
2784 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2785 perm |= BLK_PERM_WRITE;
2786 }
2787
2788 /*
2789 * If the data file is written to, the format driver may
2790 * expect to be able to resize it by writing beyond the EOF.
2791 */
2792 if (perm & BLK_PERM_WRITE) {
2793 perm |= BLK_PERM_RESIZE;
2794 }
Max Reitz6f838a42020-05-13 13:05:27 +02002795 }
Max Reitz6f838a42020-05-13 13:05:27 +02002796
2797 if (bs->open_flags & BDRV_O_INACTIVE) {
2798 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2799 }
2800
2801 *nperm = perm;
2802 *nshared = shared;
2803}
2804
Max Reitz2519f542020-05-13 13:05:29 +02002805void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002806 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002807 uint64_t perm, uint64_t shared,
2808 uint64_t *nperm, uint64_t *nshared)
2809{
Max Reitz2519f542020-05-13 13:05:29 +02002810 if (role & BDRV_CHILD_FILTERED) {
2811 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2812 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002813 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002814 perm, shared, nperm, nshared);
2815 } else if (role & BDRV_CHILD_COW) {
2816 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002817 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002818 perm, shared, nperm, nshared);
2819 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002820 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002821 perm, shared, nperm, nshared);
2822 } else {
2823 g_assert_not_reached();
2824 }
2825}
2826
Max Reitz7b1d9c42019-11-08 13:34:51 +01002827uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2828{
2829 static const uint64_t permissions[] = {
2830 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2831 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2832 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2833 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2834 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2835 };
2836
2837 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2838 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2839
2840 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2841
2842 return permissions[qapi_perm];
2843}
2844
Kevin Wolf8ee03992017-03-06 13:45:28 +01002845static void bdrv_replace_child_noperm(BdrvChild *child,
2846 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002847{
2848 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002849 int new_bs_quiesce_counter;
2850 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002851
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002852 assert(!child->frozen);
2853
Fam Zhengbb2614e2017-04-07 14:54:10 +08002854 if (old_bs && new_bs) {
2855 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2856 }
Max Reitzdebc2922019-07-22 15:33:44 +02002857
2858 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2859 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2860
2861 /*
2862 * If the new child node is drained but the old one was not, flush
2863 * all outstanding requests to the old child node.
2864 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002865 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002866 bdrv_parent_drained_begin_single(child, true);
2867 drain_saldo--;
2868 }
2869
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002870 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002871 /* Detach first so that the recursive drain sections coming from @child
2872 * are already gone and we only end the drain sections that came from
2873 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002874 if (child->klass->detach) {
2875 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002876 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002877 QLIST_REMOVE(child, next_parent);
2878 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002879
2880 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002881
2882 if (new_bs) {
2883 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002884
2885 /*
2886 * Detaching the old node may have led to the new node's
2887 * quiesce_counter having been decreased. Not a problem, we
2888 * just need to recognize this here and then invoke
2889 * drained_end appropriately more often.
2890 */
2891 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2892 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002893
Kevin Wolfd736f112017-12-18 16:05:48 +01002894 /* Attach only after starting new drained sections, so that recursive
2895 * drain sections coming from @child don't get an extra .drained_begin
2896 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002897 if (child->klass->attach) {
2898 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002899 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002900 }
Max Reitzdebc2922019-07-22 15:33:44 +02002901
2902 /*
2903 * If the old child node was drained but the new one is not, allow
2904 * requests to come in only after the new node has been attached.
2905 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002906 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002907 bdrv_parent_drained_end_single(child);
2908 drain_saldo++;
2909 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002910}
2911
Kevin Wolf466787f2017-03-08 14:44:07 +01002912/*
2913 * Updates @child to change its reference to point to @new_bs, including
zhaolichange3a6e0d2020-09-17 15:50:20 +08002914 * checking and applying the necessary permission updates both to the old node
Kevin Wolf466787f2017-03-08 14:44:07 +01002915 * and to @new_bs.
2916 *
2917 * NULL is passed as @new_bs for removing the reference before freeing @child.
2918 *
2919 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2920 * function uses bdrv_set_perm() to update the permissions according to the new
2921 * reference that @new_bs gets.
Max Reitz7b99a262019-06-12 16:07:11 +02002922 *
2923 * Callers must ensure that child->frozen is false.
Kevin Wolf466787f2017-03-08 14:44:07 +01002924 */
2925static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
Kevin Wolf8ee03992017-03-06 13:45:28 +01002926{
2927 BlockDriverState *old_bs = child->bs;
Kevin Wolf8ee03992017-03-06 13:45:28 +01002928
Max Reitz7b99a262019-06-12 16:07:11 +02002929 /* Asserts that child->frozen == false */
Kevin Wolf8aecf1d2017-08-03 17:02:57 +02002930 bdrv_replace_child_noperm(child, new_bs);
2931
Max Reitz87ace5f2019-05-22 19:03:49 +02002932 /*
2933 * Start with the new node's permissions. If @new_bs is a (direct
2934 * or indirect) child of @old_bs, we must complete the permission
2935 * update on @new_bs before we loosen the restrictions on @old_bs.
2936 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2937 * updating the permissions of @new_bs, and thus not purely loosen
2938 * restrictions.
2939 */
2940 if (new_bs) {
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002941 bdrv_set_perm(new_bs);
Max Reitz87ace5f2019-05-22 19:03:49 +02002942 }
2943
Kevin Wolf8ee03992017-03-06 13:45:28 +01002944 if (old_bs) {
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002945 /*
2946 * Update permissions for old node. We're just taking a parent away, so
2947 * we're loosening restrictions. Errors of permission update are not
2948 * fatal in this case, ignore them.
2949 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002950 bdrv_refresh_perms(old_bs, NULL);
Kevin Wolfad943dc2019-04-24 18:04:42 +02002951
2952 /* When the parent requiring a non-default AioContext is removed, the
2953 * node moves back to the main AioContext */
2954 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
Kevin Wolf8ee03992017-03-06 13:45:28 +01002955 }
Kevin Wolff54120f2014-05-26 11:09:59 +02002956}
2957
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03002958static void bdrv_remove_empty_child(BdrvChild *child)
2959{
2960 assert(!child->bs);
2961 QLIST_SAFE_REMOVE(child, next);
2962 g_free(child->name);
2963 g_free(child);
2964}
2965
2966typedef struct BdrvAttachChildCommonState {
2967 BdrvChild **child;
2968 AioContext *old_parent_ctx;
2969 AioContext *old_child_ctx;
2970} BdrvAttachChildCommonState;
2971
2972static void bdrv_attach_child_common_abort(void *opaque)
2973{
2974 BdrvAttachChildCommonState *s = opaque;
2975 BdrvChild *child = *s->child;
2976 BlockDriverState *bs = child->bs;
2977
2978 bdrv_replace_child_noperm(child, NULL);
2979
2980 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2981 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2982 }
2983
2984 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
2985 GSList *ignore = g_slist_prepend(NULL, child);
2986
2987 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2988 &error_abort);
2989 g_slist_free(ignore);
2990 ignore = g_slist_prepend(NULL, child);
2991 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
2992
2993 g_slist_free(ignore);
2994 }
2995
2996 bdrv_unref(bs);
2997 bdrv_remove_empty_child(child);
2998 *s->child = NULL;
2999}
3000
3001static TransactionActionDrv bdrv_attach_child_common_drv = {
3002 .abort = bdrv_attach_child_common_abort,
3003 .clean = g_free,
3004};
3005
3006/*
3007 * Common part of attaching bdrv child to bs or to blk or to job
3008 */
3009static int bdrv_attach_child_common(BlockDriverState *child_bs,
3010 const char *child_name,
3011 const BdrvChildClass *child_class,
3012 BdrvChildRole child_role,
3013 uint64_t perm, uint64_t shared_perm,
3014 void *opaque, BdrvChild **child,
3015 Transaction *tran, Error **errp)
3016{
3017 BdrvChild *new_child;
3018 AioContext *parent_ctx;
3019 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3020
3021 assert(child);
3022 assert(*child == NULL);
3023
3024 new_child = g_new(BdrvChild, 1);
3025 *new_child = (BdrvChild) {
3026 .bs = NULL,
3027 .name = g_strdup(child_name),
3028 .klass = child_class,
3029 .role = child_role,
3030 .perm = perm,
3031 .shared_perm = shared_perm,
3032 .opaque = opaque,
3033 };
3034
3035 /*
3036 * If the AioContexts don't match, first try to move the subtree of
3037 * child_bs into the AioContext of the new parent. If this doesn't work,
3038 * try moving the parent into the AioContext of child_bs instead.
3039 */
3040 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3041 if (child_ctx != parent_ctx) {
3042 Error *local_err = NULL;
3043 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
3044
3045 if (ret < 0 && child_class->can_set_aio_ctx) {
3046 GSList *ignore = g_slist_prepend(NULL, new_child);
3047 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
3048 NULL))
3049 {
3050 error_free(local_err);
3051 ret = 0;
3052 g_slist_free(ignore);
3053 ignore = g_slist_prepend(NULL, new_child);
3054 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
3055 }
3056 g_slist_free(ignore);
3057 }
3058
3059 if (ret < 0) {
3060 error_propagate(errp, local_err);
3061 bdrv_remove_empty_child(new_child);
3062 return ret;
3063 }
3064 }
3065
3066 bdrv_ref(child_bs);
3067 bdrv_replace_child_noperm(new_child, child_bs);
3068
3069 *child = new_child;
3070
3071 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3072 *s = (BdrvAttachChildCommonState) {
3073 .child = child,
3074 .old_parent_ctx = parent_ctx,
3075 .old_child_ctx = child_ctx,
3076 };
3077 tran_add(tran, &bdrv_attach_child_common_drv, s);
3078
3079 return 0;
3080}
3081
3082static void bdrv_detach_child(BdrvChild *child)
3083{
3084 bdrv_replace_child(child, NULL);
3085 bdrv_remove_empty_child(child);
3086}
3087
Alberto Garciab441dc72019-05-13 16:46:18 +03003088/*
3089 * This function steals the reference to child_bs from the caller.
3090 * That reference is later dropped by bdrv_root_unref_child().
3091 *
3092 * On failure NULL is returned, errp is set and the reference to
3093 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003094 *
3095 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3096 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03003097 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003098BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3099 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003100 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003101 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003102 uint64_t perm, uint64_t shared_perm,
3103 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02003104{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003105 int ret;
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003106 BdrvChild *child = NULL;
3107 Transaction *tran = tran_new();
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003108
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003109 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3110 child_role, perm, shared_perm, opaque,
3111 &child, tran, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003112 if (ret < 0) {
Alberto Garciab441dc72019-05-13 16:46:18 +03003113 bdrv_unref(child_bs);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003114 return NULL;
3115 }
3116
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003117 ret = bdrv_refresh_perms(child_bs, errp);
3118 tran_finalize(tran, ret);
Kevin Wolfdf581792015-06-15 11:53:47 +02003119
Vladimir Sementsov-Ogievskiy548a74c2021-04-28 18:17:46 +03003120 bdrv_unref(child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003121 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02003122}
3123
Alberto Garciab441dc72019-05-13 16:46:18 +03003124/*
3125 * This function transfers the reference to child_bs from the caller
3126 * to parent_bs. That reference is later dropped by parent_bs on
3127 * bdrv_close() or if someone calls bdrv_unref_child().
3128 *
3129 * On failure NULL is returned, errp is set and the reference to
3130 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02003131 *
3132 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3133 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03003134 */
Wen Congyang98292c62016-05-10 15:36:38 +08003135BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3136 BlockDriverState *child_bs,
3137 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02003138 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003139 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01003140 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003141{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003142 BdrvChild *child;
Kevin Wolff68c5982016-12-20 15:51:12 +01003143 uint64_t perm, shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003144
Kevin Wolff68c5982016-12-20 15:51:12 +01003145 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3146
3147 assert(parent_bs->drv);
Max Reitze5d8a402020-05-13 13:05:44 +02003148 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08003149 perm, shared_perm, &perm, &shared_perm);
Kevin Wolff68c5982016-12-20 15:51:12 +01003150
Max Reitzbd86fb92020-05-13 13:05:13 +02003151 child = bdrv_root_attach_child(child_bs, child_name, child_class,
Vladimir Sementsov-Ogievskiy228ca372021-04-28 18:17:34 +03003152 child_role, perm, shared_perm, parent_bs,
3153 errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01003154 if (child == NULL) {
3155 return NULL;
3156 }
3157
Kevin Wolff21d96d2016-03-08 13:47:46 +01003158 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
3159 return child;
3160}
3161
Max Reitz7b99a262019-06-12 16:07:11 +02003162/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01003163void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02003164{
Kevin Wolf779020c2015-10-13 14:09:44 +02003165 BlockDriverState *child_bs;
3166
Kevin Wolff21d96d2016-03-08 13:47:46 +01003167 child_bs = child->bs;
3168 bdrv_detach_child(child);
3169 bdrv_unref(child_bs);
3170}
3171
Max Reitz3cf746b2019-07-03 19:28:07 +02003172/**
3173 * Clear all inherits_from pointers from children and grandchildren of
3174 * @root that point to @root, where necessary.
3175 */
3176static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
Kevin Wolff21d96d2016-03-08 13:47:46 +01003177{
Max Reitz3cf746b2019-07-03 19:28:07 +02003178 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02003179
Max Reitz3cf746b2019-07-03 19:28:07 +02003180 if (child->bs->inherits_from == root) {
3181 /*
3182 * Remove inherits_from only when the last reference between root and
3183 * child->bs goes away.
3184 */
3185 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003186 if (c != child && c->bs == child->bs) {
3187 break;
3188 }
3189 }
3190 if (c == NULL) {
3191 child->bs->inherits_from = NULL;
3192 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003193 }
3194
Max Reitz3cf746b2019-07-03 19:28:07 +02003195 QLIST_FOREACH(c, &child->bs->children, next) {
3196 bdrv_unset_inherits_from(root, c);
3197 }
3198}
3199
Max Reitz7b99a262019-06-12 16:07:11 +02003200/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02003201void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3202{
3203 if (child == NULL) {
3204 return;
3205 }
3206
3207 bdrv_unset_inherits_from(parent, child);
Kevin Wolff21d96d2016-03-08 13:47:46 +01003208 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02003209}
3210
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003211
3212static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3213{
3214 BdrvChild *c;
3215 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02003216 if (c->klass->change_media) {
3217 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003218 }
3219 }
3220}
3221
Alberto Garcia0065c452018-10-31 18:16:37 +02003222/* Return true if you can reach parent going through child->inherits_from
3223 * recursively. If parent or child are NULL, return false */
3224static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3225 BlockDriverState *parent)
3226{
3227 while (child && child != parent) {
3228 child = child->inherits_from;
3229 }
3230
3231 return child != NULL;
3232}
3233
Kevin Wolf5db15a52015-09-14 15:33:33 +02003234/*
Max Reitz25191e52020-05-13 13:05:33 +02003235 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3236 * mostly used for COW backing children (role = COW), but also for
3237 * filtered children (role = FILTERED | PRIMARY).
3238 */
3239static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3240{
3241 if (bs->drv && bs->drv->is_filter) {
3242 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3243 } else {
3244 return BDRV_CHILD_COW;
3245 }
3246}
3247
3248/*
Max Reitz9ee413c2019-06-12 18:42:34 +02003249 * Sets the bs->backing link of a BDS. A new reference is created; callers
Kevin Wolf5db15a52015-09-14 15:33:33 +02003250 * which don't need their own reference any more must call bdrv_unref().
3251 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003252int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3253 Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08003254{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003255 int ret = 0;
Alberto Garcia0065c452018-10-31 18:16:37 +02003256 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
3257 bdrv_inherits_from_recursive(backing_hd, bs);
3258
Max Reitz9ee413c2019-06-12 18:42:34 +02003259 if (bdrv_is_backing_chain_frozen(bs, child_bs(bs->backing), errp)) {
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003260 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02003261 }
3262
Kevin Wolf5db15a52015-09-14 15:33:33 +02003263 if (backing_hd) {
3264 bdrv_ref(backing_hd);
3265 }
Fam Zheng8d24cce2014-05-23 21:29:45 +08003266
Kevin Wolf760e0062015-06-17 14:55:21 +02003267 if (bs->backing) {
Max Reitz7b99a262019-06-12 16:07:11 +02003268 /* Cannot be frozen, we checked that above */
Kevin Wolf5db15a52015-09-14 15:33:33 +02003269 bdrv_unref_child(bs, bs->backing);
Vladimir Sementsov-Ogievskiy6e579632020-03-16 09:06:30 +03003270 bs->backing = NULL;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003271 }
3272
Fam Zheng8d24cce2014-05-23 21:29:45 +08003273 if (!backing_hd) {
3274 goto out;
3275 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003276
Max Reitz25191e52020-05-13 13:05:33 +02003277 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_of_bds,
3278 bdrv_backing_role(bs), errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003279 if (!bs->backing) {
3280 ret = -EPERM;
3281 goto out;
3282 }
3283
Alberto Garcia0065c452018-10-31 18:16:37 +02003284 /* If backing_hd was already part of bs's backing chain, and
3285 * inherits_from pointed recursively to bs then let's update it to
3286 * point directly to bs (else it will become NULL). */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003287 if (update_inherits_from) {
Alberto Garcia0065c452018-10-31 18:16:37 +02003288 backing_hd->inherits_from = bs;
3289 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003290
Fam Zheng8d24cce2014-05-23 21:29:45 +08003291out:
Kevin Wolf3baca892014-07-16 17:48:16 +02003292 bdrv_refresh_limits(bs, NULL);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003293
3294 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003295}
3296
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003297/*
3298 * Opens the backing file for a BlockDriverState if not yet open
3299 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003300 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3301 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3302 * itself, all options starting with "${bdref_key}." are considered part of the
3303 * BlockdevRef.
3304 *
3305 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003306 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003307int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3308 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003309{
Max Reitz6b6833c2019-02-01 20:29:15 +01003310 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003311 char *bdref_key_dot;
3312 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003313 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003314 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003315 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003316 QDict *options;
3317 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003318 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003319
Kevin Wolf760e0062015-06-17 14:55:21 +02003320 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003321 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003322 }
3323
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003324 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003325 if (parent_options == NULL) {
3326 tmp_parent_options = qdict_new();
3327 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003328 }
3329
Paolo Bonzini9156df12012-10-18 16:49:17 +02003330 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003331
3332 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3333 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3334 g_free(bdref_key_dot);
3335
Markus Armbruster129c7d12017-03-30 19:43:12 +02003336 /*
3337 * Caution: while qdict_get_try_str() is fine, getting non-string
3338 * types would require more care. When @parent_options come from
3339 * -blockdev or blockdev_add, its members are typed according to
3340 * the QAPI schema, but when they come from -drive, they're all
3341 * QString.
3342 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003343 reference = qdict_get_try_str(parent_options, bdref_key);
3344 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003345 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003346 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003347 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003348 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003349 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003350 if (qdict_size(options) == 0) {
3351 /* If the user specifies options that do not modify the
3352 * backing file's behavior, we might still consider it the
3353 * implicit backing file. But it's easier this way, and
3354 * just specifying some of the backing BDS's options is
3355 * only possible with -drive anyway (otherwise the QAPI
3356 * schema forces the user to specify everything). */
3357 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3358 }
3359
Max Reitz6b6833c2019-02-01 20:29:15 +01003360 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003361 if (local_err) {
3362 ret = -EINVAL;
3363 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003364 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003365 goto free_exit;
3366 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003367 }
3368
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003369 if (!bs->drv || !bs->drv->supports_backing) {
3370 ret = -EINVAL;
3371 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003372 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003373 goto free_exit;
3374 }
3375
Peter Krempa6bff5972017-10-12 16:14:10 +02003376 if (!reference &&
3377 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003378 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003379 }
3380
Max Reitz6b6833c2019-02-01 20:29:15 +01003381 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003382 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003383 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003384 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003385 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003386 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003387 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003388 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003389
Max Reitz998c2012019-02-01 20:29:08 +01003390 if (implicit_backing) {
3391 bdrv_refresh_filename(backing_hd);
3392 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3393 backing_hd->filename);
3394 }
3395
Kevin Wolf5db15a52015-09-14 15:33:33 +02003396 /* Hook up the backing file link; drop our reference, bs owns the
3397 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003398 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003399 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003400 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003401 goto free_exit;
3402 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003403
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003404 qdict_del(parent_options, bdref_key);
3405
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003406free_exit:
3407 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003408 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003409 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003410}
3411
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003412static BlockDriverState *
3413bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003414 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003415 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003416{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003417 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003418 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003419 char *bdref_key_dot;
3420 const char *reference;
3421
Max Reitzbd86fb92020-05-13 13:05:13 +02003422 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003423
Max Reitzda557aa2013-12-20 19:28:11 +01003424 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3425 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3426 g_free(bdref_key_dot);
3427
Markus Armbruster129c7d12017-03-30 19:43:12 +02003428 /*
3429 * Caution: while qdict_get_try_str() is fine, getting non-string
3430 * types would require more care. When @options come from
3431 * -blockdev or blockdev_add, its members are typed according to
3432 * the QAPI schema, but when they come from -drive, they're all
3433 * QString.
3434 */
Max Reitzda557aa2013-12-20 19:28:11 +01003435 reference = qdict_get_try_str(options, bdref_key);
3436 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003437 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003438 error_setg(errp, "A block device must be specified for \"%s\"",
3439 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003440 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003441 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003442 goto done;
3443 }
3444
Max Reitz5b363932016-05-17 16:41:31 +02003445 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003446 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003447 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003448 goto done;
3449 }
3450
Max Reitzda557aa2013-12-20 19:28:11 +01003451done:
3452 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003453 return bs;
3454}
3455
3456/*
3457 * Opens a disk image whose options are given as BlockdevRef in another block
3458 * device's options.
3459 *
3460 * If allow_none is true, no image will be opened if filename is false and no
3461 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3462 *
3463 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3464 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3465 * itself, all options starting with "${bdref_key}." are considered part of the
3466 * BlockdevRef.
3467 *
3468 * The BlockdevRef will be removed from the options QDict.
3469 */
3470BdrvChild *bdrv_open_child(const char *filename,
3471 QDict *options, const char *bdref_key,
3472 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003473 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003474 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003475 bool allow_none, Error **errp)
3476{
3477 BlockDriverState *bs;
3478
Max Reitzbd86fb92020-05-13 13:05:13 +02003479 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003480 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003481 if (bs == NULL) {
3482 return NULL;
3483 }
3484
Max Reitz258b7762020-05-13 13:05:15 +02003485 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3486 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003487}
3488
Max Reitzbd86fb92020-05-13 13:05:13 +02003489/*
3490 * TODO Future callers may need to specify parent/child_class in order for
3491 * option inheritance to work. Existing callers use it for the root node.
3492 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003493BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3494{
3495 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003496 QObject *obj = NULL;
3497 QDict *qdict = NULL;
3498 const char *reference = NULL;
3499 Visitor *v = NULL;
3500
3501 if (ref->type == QTYPE_QSTRING) {
3502 reference = ref->u.reference;
3503 } else {
3504 BlockdevOptions *options = &ref->u.definition;
3505 assert(ref->type == QTYPE_QDICT);
3506
3507 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003508 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003509 visit_complete(v, &obj);
3510
Max Reitz7dc847e2018-02-24 16:40:29 +01003511 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003512 qdict_flatten(qdict);
3513
3514 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3515 * compatibility with other callers) rather than what we want as the
3516 * real defaults. Apply the defaults here instead. */
3517 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3518 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3519 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003520 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3521
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003522 }
3523
Max Reitz272c02e2020-05-13 13:05:17 +02003524 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003525 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003526 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003527 visit_free(v);
3528 return bs;
3529}
3530
Max Reitz66836182016-05-17 16:41:27 +02003531static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3532 int flags,
3533 QDict *snapshot_options,
3534 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003535{
3536 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003537 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003538 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003539 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003540 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003541 int ret;
3542
3543 /* if snapshot, we create a temporary backing file and open it
3544 instead of opening 'filename' directly */
3545
3546 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003547 total_size = bdrv_getlength(bs);
3548 if (total_size < 0) {
3549 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003550 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003551 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003552
3553 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003554 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003555 if (ret < 0) {
3556 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003557 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003558 }
3559
Max Reitzef810432014-12-02 18:32:42 +01003560 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003561 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003562 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003563 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003564 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003565 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003566 error_prepend(errp, "Could not create temporary overlay '%s': ",
3567 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003568 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003569 }
3570
Kevin Wolf73176be2016-03-07 13:02:15 +01003571 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003572 qdict_put_str(snapshot_options, "file.driver", "file");
3573 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3574 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003575
Max Reitz5b363932016-05-17 16:41:31 +02003576 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003577 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003578 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003579 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003580 }
3581
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003582 ret = bdrv_append(bs_snapshot, bs, errp);
3583 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003584 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003585 goto out;
3586 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003587
3588out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003589 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003590 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003591 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003592}
3593
Max Reitzda557aa2013-12-20 19:28:11 +01003594/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003595 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003596 *
3597 * options is a QDict of options to pass to the block drivers, or NULL for an
3598 * empty set of options. The reference to the QDict belongs to the block layer
3599 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003600 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003601 *
3602 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3603 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003604 *
3605 * The reference parameter may be used to specify an existing block device which
3606 * should be opened. If specified, neither options nor a filename may be given,
3607 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003608 */
Max Reitz5b363932016-05-17 16:41:31 +02003609static BlockDriverState *bdrv_open_inherit(const char *filename,
3610 const char *reference,
3611 QDict *options, int flags,
3612 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003613 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003614 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003615 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003616{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003617 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003618 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003619 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003620 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003621 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003622 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003623 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003624 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003625 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003626 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003627
Max Reitzbd86fb92020-05-13 13:05:13 +02003628 assert(!child_class || !flags);
3629 assert(!child_class == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01003630
Max Reitzddf56362014-02-18 18:33:06 +01003631 if (reference) {
3632 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003633 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003634
Max Reitzddf56362014-02-18 18:33:06 +01003635 if (filename || options_non_empty) {
3636 error_setg(errp, "Cannot reference an existing block device with "
3637 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003638 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003639 }
3640
3641 bs = bdrv_lookup_bs(reference, reference, errp);
3642 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003643 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003644 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003645
Max Reitzddf56362014-02-18 18:33:06 +01003646 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003647 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003648 }
3649
Max Reitz5b363932016-05-17 16:41:31 +02003650 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003651
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003652 /* NULL means an empty set of options */
3653 if (options == NULL) {
3654 options = qdict_new();
3655 }
3656
Kevin Wolf145f5982015-05-08 16:15:03 +02003657 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003658 parse_json_protocol(options, &filename, &local_err);
3659 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003660 goto fail;
3661 }
3662
Kevin Wolf145f5982015-05-08 16:15:03 +02003663 bs->explicit_options = qdict_clone_shallow(options);
3664
Max Reitzbd86fb92020-05-13 13:05:13 +02003665 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003666 bool parent_is_format;
3667
3668 if (parent->drv) {
3669 parent_is_format = parent->drv->is_format;
3670 } else {
3671 /*
3672 * parent->drv is not set yet because this node is opened for
3673 * (potential) format probing. That means that @parent is going
3674 * to be a format node.
3675 */
3676 parent_is_format = true;
3677 }
3678
Kevin Wolfbddcec32015-04-09 18:47:50 +02003679 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003680 child_class->inherit_options(child_role, parent_is_format,
3681 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003682 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003683 }
3684
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003685 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003686 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003687 goto fail;
3688 }
3689
Markus Armbruster129c7d12017-03-30 19:43:12 +02003690 /*
3691 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3692 * Caution: getting a boolean member of @options requires care.
3693 * When @options come from -blockdev or blockdev_add, members are
3694 * typed according to the QAPI schema, but when they come from
3695 * -drive, they're all QString.
3696 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003697 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3698 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3699 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3700 } else {
3701 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003702 }
3703
3704 if (flags & BDRV_O_SNAPSHOT) {
3705 snapshot_options = qdict_new();
3706 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3707 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003708 /* Let bdrv_backing_options() override "read-only" */
3709 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003710 bdrv_inherited_options(BDRV_CHILD_COW, true,
3711 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003712 }
3713
Kevin Wolf62392eb2015-04-24 16:38:02 +02003714 bs->open_flags = flags;
3715 bs->options = options;
3716 options = qdict_clone_shallow(options);
3717
Kevin Wolf76c591b2014-06-04 14:19:44 +02003718 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003719 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003720 drvname = qdict_get_try_str(options, "driver");
3721 if (drvname) {
3722 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003723 if (!drv) {
3724 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003725 goto fail;
3726 }
3727 }
3728
3729 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003730
Markus Armbruster129c7d12017-03-30 19:43:12 +02003731 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003732 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003733 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3734 (backing && *backing == '\0'))
3735 {
Max Reitz4f7be282018-02-24 16:40:33 +01003736 if (backing) {
3737 warn_report("Use of \"backing\": \"\" is deprecated; "
3738 "use \"backing\": null instead");
3739 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003740 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003741 qdict_del(bs->explicit_options, "backing");
3742 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003743 qdict_del(options, "backing");
3744 }
3745
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003746 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003747 * probing, the block drivers will do their own bdrv_open_child() for the
3748 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003749 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003750 BlockDriverState *file_bs;
3751
3752 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003753 &child_of_bds, BDRV_CHILD_IMAGE,
3754 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003755 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003756 goto fail;
3757 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003758 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003759 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3760 * looking at the header to guess the image format. This works even
3761 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003762 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003763 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003764 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003765 if (local_err) {
3766 goto fail;
3767 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003768
Eric Blake46f5ac22017-04-27 16:58:17 -05003769 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003770 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003771 }
3772
Kevin Wolf76c591b2014-06-04 14:19:44 +02003773 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003774 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003775 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003776 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003777 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003778 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003779 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003780 /*
3781 * This option update would logically belong in bdrv_fill_options(),
3782 * but we first need to open bs->file for the probing to work, while
3783 * opening bs->file already requires the (mostly) final set of options
3784 * so that cache mode etc. can be inherited.
3785 *
3786 * Adding the driver later is somewhat ugly, but it's not an option
3787 * that would ever be inherited, so it's correct. We just need to make
3788 * sure to update both bs->options (which has the full effective
3789 * options for bs) and options (which has file.* already removed).
3790 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003791 qdict_put_str(bs->options, "driver", drv->format_name);
3792 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003793 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003794 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003795 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003796 }
3797
Max Reitz53a29512015-03-19 14:53:16 -04003798 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3799 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3800 /* file must be NULL if a protocol BDS is about to be created
3801 * (the inverse results in an error message from bdrv_open_common()) */
3802 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3803
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003804 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003805 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003806 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003807 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003808 }
3809
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003810 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003811 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003812 file = NULL;
3813 }
3814
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003815 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003816 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003817 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003818 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003819 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003820 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003821 }
3822
Alberto Garcia50196d72018-09-06 12:37:03 +03003823 /* Remove all children options and references
3824 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003825 QLIST_FOREACH(child, &bs->children, next) {
3826 char *child_key_dot;
3827 child_key_dot = g_strdup_printf("%s.", child->name);
3828 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3829 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003830 qdict_del(bs->explicit_options, child->name);
3831 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003832 g_free(child_key_dot);
3833 }
3834
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003835 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003836 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003837 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003838 if (flags & BDRV_O_PROTOCOL) {
3839 error_setg(errp, "Block protocol '%s' doesn't support the option "
3840 "'%s'", drv->format_name, entry->key);
3841 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003842 error_setg(errp,
3843 "Block format '%s' does not support the option '%s'",
3844 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003845 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003846
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003847 goto close_and_fail;
3848 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003849
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003850 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003851
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003852 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003853 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003854
3855 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3856 * temporary snapshot afterwards. */
3857 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003858 BlockDriverState *snapshot_bs;
3859 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3860 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003861 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003862 if (local_err) {
3863 goto close_and_fail;
3864 }
Max Reitz5b363932016-05-17 16:41:31 +02003865 /* We are not going to return bs but the overlay on top of it
3866 * (snapshot_bs); thus, we have to drop the strong reference to bs
3867 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3868 * though, because the overlay still has a reference to it. */
3869 bdrv_unref(bs);
3870 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003871 }
3872
Max Reitz5b363932016-05-17 16:41:31 +02003873 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003874
Kevin Wolf8bfea152014-04-11 19:16:36 +02003875fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003876 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003877 qobject_unref(snapshot_options);
3878 qobject_unref(bs->explicit_options);
3879 qobject_unref(bs->options);
3880 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003881 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003882 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003883 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003884 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003885 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003886
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003887close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02003888 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003889 qobject_unref(snapshot_options);
3890 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003891 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003892 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003893}
3894
Max Reitz5b363932016-05-17 16:41:31 +02003895BlockDriverState *bdrv_open(const char *filename, const char *reference,
3896 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02003897{
Max Reitz5b363932016-05-17 16:41:31 +02003898 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02003899 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003900}
3901
Alberto Garciafaf116b2019-03-12 18:48:49 +02003902/* Return true if the NULL-terminated @list contains @str */
3903static bool is_str_in_list(const char *str, const char *const *list)
3904{
3905 if (str && list) {
3906 int i;
3907 for (i = 0; list[i] != NULL; i++) {
3908 if (!strcmp(str, list[i])) {
3909 return true;
3910 }
3911 }
3912 }
3913 return false;
3914}
3915
3916/*
3917 * Check that every option set in @bs->options is also set in
3918 * @new_opts.
3919 *
3920 * Options listed in the common_options list and in
3921 * @bs->drv->mutable_opts are skipped.
3922 *
3923 * Return 0 on success, otherwise return -EINVAL and set @errp.
3924 */
3925static int bdrv_reset_options_allowed(BlockDriverState *bs,
3926 const QDict *new_opts, Error **errp)
3927{
3928 const QDictEntry *e;
3929 /* These options are common to all block drivers and are handled
3930 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3931 const char *const common_options[] = {
3932 "node-name", "discard", "cache.direct", "cache.no-flush",
3933 "read-only", "auto-read-only", "detect-zeroes", NULL
3934 };
3935
3936 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3937 if (!qdict_haskey(new_opts, e->key) &&
3938 !is_str_in_list(e->key, common_options) &&
3939 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3940 error_setg(errp, "Option '%s' cannot be reset "
3941 "to its default value", e->key);
3942 return -EINVAL;
3943 }
3944 }
3945
3946 return 0;
3947}
3948
Jeff Codye971aa12012-09-20 15:13:19 -04003949/*
Alberto Garciacb828c32019-03-12 18:48:47 +02003950 * Returns true if @child can be reached recursively from @bs
3951 */
3952static bool bdrv_recurse_has_child(BlockDriverState *bs,
3953 BlockDriverState *child)
3954{
3955 BdrvChild *c;
3956
3957 if (bs == child) {
3958 return true;
3959 }
3960
3961 QLIST_FOREACH(c, &bs->children, next) {
3962 if (bdrv_recurse_has_child(c->bs, child)) {
3963 return true;
3964 }
3965 }
3966
3967 return false;
3968}
3969
3970/*
Jeff Codye971aa12012-09-20 15:13:19 -04003971 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3972 * reopen of multiple devices.
3973 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003974 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04003975 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3976 * be created and initialized. This newly created BlockReopenQueue should be
3977 * passed back in for subsequent calls that are intended to be of the same
3978 * atomic 'set'.
3979 *
3980 * bs is the BlockDriverState to add to the reopen queue.
3981 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003982 * options contains the changed options for the associated bs
3983 * (the BlockReopenQueue takes ownership)
3984 *
Jeff Codye971aa12012-09-20 15:13:19 -04003985 * flags contains the open flags for the associated bs
3986 *
3987 * returns a pointer to bs_queue, which is either the newly allocated
3988 * bs_queue, or the existing bs_queue being used.
3989 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01003990 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04003991 */
Kevin Wolf28518102015-05-08 17:07:31 +02003992static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3993 BlockDriverState *bs,
3994 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003995 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02003996 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02003997 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02003998 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02003999 int parent_flags,
4000 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04004001{
4002 assert(bs != NULL);
4003
4004 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02004005 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004006 QDict *old_options, *explicit_options, *options_copy;
4007 int flags;
4008 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004009
Kevin Wolf1a63a902017-12-06 20:24:44 +01004010 /* Make sure that the caller remembered to use a drained section. This is
4011 * important to avoid graph changes between the recursive queuing here and
4012 * bdrv_reopen_multiple(). */
4013 assert(bs->quiesce_counter > 0);
4014
Jeff Codye971aa12012-09-20 15:13:19 -04004015 if (bs_queue == NULL) {
4016 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004017 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04004018 }
4019
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004020 if (!options) {
4021 options = qdict_new();
4022 }
4023
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004024 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004025 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004026 if (bs == bs_entry->state.bs) {
4027 break;
4028 }
4029 }
4030
Kevin Wolf28518102015-05-08 17:07:31 +02004031 /*
4032 * Precedence of options:
4033 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004034 * 2. Retained from explicitly set options of bs
4035 * 3. Inherited from parent node
4036 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02004037 */
4038
Kevin Wolf145f5982015-05-08 16:15:03 +02004039 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02004040 if (bs_entry || keep_old_opts) {
4041 old_options = qdict_clone_shallow(bs_entry ?
4042 bs_entry->state.explicit_options :
4043 bs->explicit_options);
4044 bdrv_join_options(bs, options, old_options);
4045 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03004046 }
Kevin Wolf145f5982015-05-08 16:15:03 +02004047
4048 explicit_options = qdict_clone_shallow(options);
4049
Kevin Wolf28518102015-05-08 17:07:31 +02004050 /* Inherit from parent node */
4051 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004052 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02004053 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02004054 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004055 } else {
4056 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02004057 }
4058
Alberto Garcia077e8e22019-03-12 18:48:44 +02004059 if (keep_old_opts) {
4060 /* Old values are used for options that aren't set yet */
4061 old_options = qdict_clone_shallow(bs->options);
4062 bdrv_join_options(bs, options, old_options);
4063 qobject_unref(old_options);
4064 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004065
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004066 /* We have the final set of options so let's update the flags */
4067 options_copy = qdict_clone_shallow(options);
4068 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4069 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4070 update_flags_from_options(&flags, opts);
4071 qemu_opts_del(opts);
4072 qobject_unref(options_copy);
4073
Kevin Wolffd452022017-08-03 17:02:59 +02004074 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02004075 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02004076 if (flags & BDRV_O_RDWR) {
4077 flags |= BDRV_O_ALLOW_RDWR;
4078 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02004079
Kevin Wolf1857c972017-09-14 14:53:46 +02004080 if (!bs_entry) {
4081 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004082 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02004083 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004084 qobject_unref(bs_entry->state.options);
4085 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02004086 }
4087
4088 bs_entry->state.bs = bs;
4089 bs_entry->state.options = options;
4090 bs_entry->state.explicit_options = explicit_options;
4091 bs_entry->state.flags = flags;
4092
Kevin Wolf30450252017-07-03 17:07:35 +02004093 /* This needs to be overwritten in bdrv_reopen_prepare() */
4094 bs_entry->state.perm = UINT64_MAX;
4095 bs_entry->state.shared_perm = 0;
4096
Alberto Garcia85466322019-03-12 18:48:45 +02004097 /*
4098 * If keep_old_opts is false then it means that unspecified
4099 * options must be reset to their original value. We don't allow
4100 * resetting 'backing' but we need to know if the option is
4101 * missing in order to decide if we have to return an error.
4102 */
4103 if (!keep_old_opts) {
4104 bs_entry->state.backing_missing =
4105 !qdict_haskey(options, "backing") &&
4106 !qdict_haskey(options, "backing.driver");
4107 }
4108
Kevin Wolf67251a32015-04-09 18:54:04 +02004109 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02004110 QDict *new_child_options = NULL;
4111 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02004112
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004113 /* reopen can only change the options of block devices that were
4114 * implicitly created and inherited options. For other (referenced)
4115 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02004116 if (child->bs->inherits_from != bs) {
4117 continue;
4118 }
4119
Alberto Garcia85466322019-03-12 18:48:45 +02004120 /* Check if the options contain a child reference */
4121 if (qdict_haskey(options, child->name)) {
4122 const char *childref = qdict_get_try_str(options, child->name);
4123 /*
4124 * The current child must not be reopened if the child
4125 * reference is null or points to a different node.
4126 */
4127 if (g_strcmp0(childref, child->bs->node_name)) {
4128 continue;
4129 }
4130 /*
4131 * If the child reference points to the current child then
4132 * reopen it with its existing set of options (note that
4133 * it can still inherit new options from the parent).
4134 */
4135 child_keep_old = true;
4136 } else {
4137 /* Extract child options ("child-name.*") */
4138 char *child_key_dot = g_strdup_printf("%s.", child->name);
4139 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4140 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4141 g_free(child_key_dot);
4142 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02004143
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02004144 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02004145 child->klass, child->role, bs->drv->is_format,
4146 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04004147 }
4148
Jeff Codye971aa12012-09-20 15:13:19 -04004149 return bs_queue;
4150}
4151
Kevin Wolf28518102015-05-08 17:07:31 +02004152BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4153 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02004154 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02004155{
Max Reitz3cdc69d2020-05-13 13:05:18 +02004156 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4157 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02004158}
4159
Jeff Codye971aa12012-09-20 15:13:19 -04004160/*
4161 * Reopen multiple BlockDriverStates atomically & transactionally.
4162 *
4163 * The queue passed in (bs_queue) must have been built up previous
4164 * via bdrv_reopen_queue().
4165 *
4166 * Reopens all BDS specified in the queue, with the appropriate
4167 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02004168 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04004169 * data cleaned up.
4170 *
4171 * If all devices prepare successfully, then the changes are committed
4172 * to all devices.
4173 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01004174 * All affected nodes must be drained between bdrv_reopen_queue() and
4175 * bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04004176 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02004177int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004178{
4179 int ret = -1;
4180 BlockReopenQueueEntry *bs_entry, *next;
Jeff Codye971aa12012-09-20 15:13:19 -04004181
4182 assert(bs_queue != NULL);
4183
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004184 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01004185 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolfa4615ab2019-03-05 16:51:13 +01004186 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
Jeff Codye971aa12012-09-20 15:13:19 -04004187 goto cleanup;
4188 }
4189 bs_entry->prepared = true;
4190 }
4191
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004192 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004193 BDRVReopenState *state = &bs_entry->state;
4194 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03004195 state->shared_perm, NULL, errp);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004196 if (ret < 0) {
4197 goto cleanup_perm;
4198 }
Alberto Garciacb828c32019-03-12 18:48:47 +02004199 /* Check if new_backing_bs would accept the new permissions */
4200 if (state->replace_backing_bs && state->new_backing_bs) {
4201 uint64_t nperm, nshared;
4202 bdrv_child_perm(state->bs, state->new_backing_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02004203 NULL, bdrv_backing_role(state->bs),
Max Reitz25191e52020-05-13 13:05:33 +02004204 bs_queue, state->perm, state->shared_perm,
Alberto Garciacb828c32019-03-12 18:48:47 +02004205 &nperm, &nshared);
4206 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03004207 nperm, nshared, NULL, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02004208 if (ret < 0) {
4209 goto cleanup_perm;
4210 }
4211 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004212 bs_entry->perms_checked = true;
4213 }
4214
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004215 /*
4216 * If we reach this point, we have success and just need to apply the
4217 * changes.
4218 *
4219 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4220 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4221 * children are usually goes after parents in reopen-queue, so go from last
4222 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04004223 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03004224 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Jeff Codye971aa12012-09-20 15:13:19 -04004225 bdrv_reopen_commit(&bs_entry->state);
4226 }
4227
4228 ret = 0;
Kevin Wolf69b736e2019-03-05 17:18:22 +01004229cleanup_perm:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004230 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01004231 BDRVReopenState *state = &bs_entry->state;
Jeff Codye971aa12012-09-20 15:13:19 -04004232
Kevin Wolf69b736e2019-03-05 17:18:22 +01004233 if (!bs_entry->perms_checked) {
4234 continue;
4235 }
4236
4237 if (ret == 0) {
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03004238 uint64_t perm, shared;
4239
4240 bdrv_get_cumulative_perm(state->bs, &perm, &shared);
4241 assert(perm == state->perm);
4242 assert(shared == state->shared_perm);
4243
4244 bdrv_set_perm(state->bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01004245 } else {
4246 bdrv_abort_perm_update(state->bs);
Alberto Garciacb828c32019-03-12 18:48:47 +02004247 if (state->replace_backing_bs && state->new_backing_bs) {
4248 bdrv_abort_perm_update(state->new_backing_bs);
4249 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01004250 }
4251 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01004252
4253 if (ret == 0) {
4254 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4255 BlockDriverState *bs = bs_entry->state.bs;
4256
4257 if (bs->drv->bdrv_reopen_commit_post)
4258 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4259 }
4260 }
Jeff Codye971aa12012-09-20 15:13:19 -04004261cleanup:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004262 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Alberto Garcia1bab38e2018-06-29 14:37:01 +03004263 if (ret) {
4264 if (bs_entry->prepared) {
4265 bdrv_reopen_abort(&bs_entry->state);
4266 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004267 qobject_unref(bs_entry->state.explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004268 qobject_unref(bs_entry->state.options);
Jeff Codye971aa12012-09-20 15:13:19 -04004269 }
Alberto Garciacb828c32019-03-12 18:48:47 +02004270 if (bs_entry->state.new_backing_bs) {
4271 bdrv_unref(bs_entry->state.new_backing_bs);
4272 }
Jeff Codye971aa12012-09-20 15:13:19 -04004273 g_free(bs_entry);
4274 }
4275 g_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004276
Jeff Codye971aa12012-09-20 15:13:19 -04004277 return ret;
4278}
4279
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004280int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4281 Error **errp)
4282{
4283 int ret;
4284 BlockReopenQueue *queue;
4285 QDict *opts = qdict_new();
4286
4287 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4288
4289 bdrv_subtree_drained_begin(bs);
Alberto Garcia077e8e22019-03-12 18:48:44 +02004290 queue = bdrv_reopen_queue(NULL, bs, opts, true);
Alberto Garcia5019aec2019-03-12 18:48:50 +02004291 ret = bdrv_reopen_multiple(queue, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004292 bdrv_subtree_drained_end(bs);
4293
4294 return ret;
4295}
4296
Kevin Wolf30450252017-07-03 17:07:35 +02004297static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
4298 BdrvChild *c)
4299{
4300 BlockReopenQueueEntry *entry;
4301
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004302 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf30450252017-07-03 17:07:35 +02004303 BlockDriverState *bs = entry->state.bs;
4304 BdrvChild *child;
4305
4306 QLIST_FOREACH(child, &bs->children, next) {
4307 if (child == c) {
4308 return entry;
4309 }
4310 }
4311 }
4312
4313 return NULL;
4314}
4315
4316static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
4317 uint64_t *perm, uint64_t *shared)
4318{
4319 BdrvChild *c;
4320 BlockReopenQueueEntry *parent;
4321 uint64_t cumulative_perms = 0;
4322 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
4323
4324 QLIST_FOREACH(c, &bs->parents, next_parent) {
4325 parent = find_parent_in_reopen_queue(q, c);
4326 if (!parent) {
4327 cumulative_perms |= c->perm;
4328 cumulative_shared_perms &= c->shared_perm;
4329 } else {
4330 uint64_t nperm, nshared;
4331
Max Reitze5d8a402020-05-13 13:05:44 +02004332 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
Kevin Wolf30450252017-07-03 17:07:35 +02004333 parent->state.perm, parent->state.shared_perm,
4334 &nperm, &nshared);
4335
4336 cumulative_perms |= nperm;
4337 cumulative_shared_perms &= nshared;
4338 }
4339 }
4340 *perm = cumulative_perms;
4341 *shared = cumulative_shared_perms;
4342}
Jeff Codye971aa12012-09-20 15:13:19 -04004343
Kevin Wolf1de6b452020-03-06 15:14:13 +01004344static bool bdrv_reopen_can_attach(BlockDriverState *parent,
4345 BdrvChild *child,
4346 BlockDriverState *new_child,
4347 Error **errp)
4348{
4349 AioContext *parent_ctx = bdrv_get_aio_context(parent);
4350 AioContext *child_ctx = bdrv_get_aio_context(new_child);
4351 GSList *ignore;
4352 bool ret;
4353
4354 ignore = g_slist_prepend(NULL, child);
4355 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
4356 g_slist_free(ignore);
4357 if (ret) {
4358 return ret;
4359 }
4360
4361 ignore = g_slist_prepend(NULL, child);
4362 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
4363 g_slist_free(ignore);
4364 return ret;
4365}
4366
Jeff Codye971aa12012-09-20 15:13:19 -04004367/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004368 * Take a BDRVReopenState and check if the value of 'backing' in the
4369 * reopen_state->options QDict is valid or not.
4370 *
4371 * If 'backing' is missing from the QDict then return 0.
4372 *
4373 * If 'backing' contains the node name of the backing file of
4374 * reopen_state->bs then return 0.
4375 *
4376 * If 'backing' contains a different node name (or is null) then check
4377 * whether the current backing file can be replaced with the new one.
4378 * If that's the case then reopen_state->replace_backing_bs is set to
4379 * true and reopen_state->new_backing_bs contains a pointer to the new
4380 * backing BlockDriverState (or NULL).
4381 *
4382 * Return 0 on success, otherwise return < 0 and set @errp.
4383 */
4384static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
4385 Error **errp)
4386{
4387 BlockDriverState *bs = reopen_state->bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004388 BlockDriverState *overlay_bs, *below_bs, *new_backing_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004389 QObject *value;
4390 const char *str;
4391
4392 value = qdict_get(reopen_state->options, "backing");
4393 if (value == NULL) {
4394 return 0;
4395 }
4396
4397 switch (qobject_type(value)) {
4398 case QTYPE_QNULL:
4399 new_backing_bs = NULL;
4400 break;
4401 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004402 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciacb828c32019-03-12 18:48:47 +02004403 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4404 if (new_backing_bs == NULL) {
4405 return -EINVAL;
4406 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4407 error_setg(errp, "Making '%s' a backing file of '%s' "
4408 "would create a cycle", str, bs->node_name);
4409 return -EINVAL;
4410 }
4411 break;
4412 default:
4413 /* 'backing' does not allow any other data type */
4414 g_assert_not_reached();
4415 }
4416
4417 /*
Kevin Wolf1de6b452020-03-06 15:14:13 +01004418 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4419 * bdrv_reopen_commit() won't fail.
Alberto Garciacb828c32019-03-12 18:48:47 +02004420 */
4421 if (new_backing_bs) {
Kevin Wolf1de6b452020-03-06 15:14:13 +01004422 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004423 return -EINVAL;
4424 }
4425 }
4426
4427 /*
Max Reitz1d42f482019-06-12 17:24:39 +02004428 * Ensure that @bs can really handle backing files, because we are
4429 * about to give it one (or swap the existing one)
4430 */
4431 if (bs->drv->is_filter) {
4432 /* Filters always have a file or a backing child */
4433 if (!bs->backing) {
4434 error_setg(errp, "'%s' is a %s filter node that does not support a "
4435 "backing child", bs->node_name, bs->drv->format_name);
4436 return -EINVAL;
4437 }
4438 } else if (!bs->drv->supports_backing) {
4439 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
4440 "files", bs->drv->format_name, bs->node_name);
4441 return -EINVAL;
4442 }
4443
4444 /*
Alberto Garciacb828c32019-03-12 18:48:47 +02004445 * Find the "actual" backing file by skipping all links that point
4446 * to an implicit node, if any (e.g. a commit filter node).
Max Reitz1d42f482019-06-12 17:24:39 +02004447 * We cannot use any of the bdrv_skip_*() functions here because
4448 * those return the first explicit node, while we are looking for
4449 * its overlay here.
Alberto Garciacb828c32019-03-12 18:48:47 +02004450 */
4451 overlay_bs = bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004452 for (below_bs = bdrv_filter_or_cow_bs(overlay_bs);
4453 below_bs && below_bs->implicit;
4454 below_bs = bdrv_filter_or_cow_bs(overlay_bs))
4455 {
4456 overlay_bs = below_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004457 }
4458
4459 /* If we want to replace the backing file we need some extra checks */
Max Reitz1d42f482019-06-12 17:24:39 +02004460 if (new_backing_bs != bdrv_filter_or_cow_bs(overlay_bs)) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004461 /* Check for implicit nodes between bs and its backing file */
4462 if (bs != overlay_bs) {
4463 error_setg(errp, "Cannot change backing link if '%s' has "
4464 "an implicit backing file", bs->node_name);
4465 return -EPERM;
4466 }
Max Reitz1d42f482019-06-12 17:24:39 +02004467 /*
4468 * Check if the backing link that we want to replace is frozen.
4469 * Note that
4470 * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4471 * because we know that overlay_bs == bs, and that @bs
4472 * either is a filter that uses ->backing or a COW format BDS
4473 * with bs->drv->supports_backing == true.
4474 */
4475 if (bdrv_is_backing_chain_frozen(overlay_bs,
4476 child_bs(overlay_bs->backing), errp))
4477 {
Alberto Garciacb828c32019-03-12 18:48:47 +02004478 return -EPERM;
4479 }
4480 reopen_state->replace_backing_bs = true;
4481 if (new_backing_bs) {
4482 bdrv_ref(new_backing_bs);
4483 reopen_state->new_backing_bs = new_backing_bs;
4484 }
4485 }
4486
4487 return 0;
4488}
4489
4490/*
Jeff Codye971aa12012-09-20 15:13:19 -04004491 * Prepares a BlockDriverState for reopen. All changes are staged in the
4492 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4493 * the block driver layer .bdrv_reopen_prepare()
4494 *
4495 * bs is the BlockDriverState to reopen
4496 * flags are the new open flags
4497 * queue is the reopen queue
4498 *
4499 * Returns 0 on success, non-zero on error. On error errp will be set
4500 * as well.
4501 *
4502 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4503 * It is the responsibility of the caller to then call the abort() or
4504 * commit() for any other BDS that have been left in a prepare() state
4505 *
4506 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004507static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4508 BlockReopenQueue *queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004509{
4510 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004511 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004512 Error *local_err = NULL;
4513 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004514 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004515 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004516 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004517 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004518 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004519
4520 assert(reopen_state != NULL);
4521 assert(reopen_state->bs->drv != NULL);
4522 drv = reopen_state->bs->drv;
4523
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004524 /* This function and each driver's bdrv_reopen_prepare() remove
4525 * entries from reopen_state->options as they are processed, so
4526 * we need to make a copy of the original QDict. */
4527 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4528
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004529 /* Process generic block layer options */
4530 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004531 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004532 ret = -EINVAL;
4533 goto error;
4534 }
4535
Alberto Garciae6d79c42018-11-12 16:00:47 +02004536 /* This was already called in bdrv_reopen_queue_child() so the flags
4537 * are up-to-date. This time we simply want to remove the options from
4538 * QemuOpts in order to indicate that they have been processed. */
4539 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004540 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004541 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004542
Alberto Garcia415bbca2018-10-03 13:23:13 +03004543 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004544 if (discard != NULL) {
4545 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4546 error_setg(errp, "Invalid discard option");
4547 ret = -EINVAL;
4548 goto error;
4549 }
4550 }
4551
Alberto Garcia543770b2018-09-06 12:37:09 +03004552 reopen_state->detect_zeroes =
4553 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4554 if (local_err) {
4555 error_propagate(errp, local_err);
4556 ret = -EINVAL;
4557 goto error;
4558 }
4559
Alberto Garcia57f9db92018-09-06 12:37:06 +03004560 /* All other options (including node-name and driver) must be unchanged.
4561 * Put them back into the QDict, so that they are checked at the end
4562 * of this function. */
4563 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004564
Jeff Cody3d8ce172017-04-07 16:55:30 -04004565 /* If we are to stay read-only, do not allow permission change
4566 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4567 * not set, or if the BDS still has copy_on_read enabled */
4568 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004569 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004570 if (local_err) {
4571 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004572 goto error;
4573 }
4574
Kevin Wolf30450252017-07-03 17:07:35 +02004575 /* Calculate required permissions after reopening */
4576 bdrv_reopen_perm(queue, reopen_state->bs,
4577 &reopen_state->perm, &reopen_state->shared_perm);
Jeff Codye971aa12012-09-20 15:13:19 -04004578
4579 ret = bdrv_flush(reopen_state->bs);
4580 if (ret) {
Eric Blake455b0fd2015-11-10 23:51:20 -07004581 error_setg_errno(errp, -ret, "Error flushing drive");
Jeff Codye971aa12012-09-20 15:13:19 -04004582 goto error;
4583 }
4584
4585 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004586 /*
4587 * If a driver-specific option is missing, it means that we
4588 * should reset it to its default value.
4589 * But not all options allow that, so we need to check it first.
4590 */
4591 ret = bdrv_reset_options_allowed(reopen_state->bs,
4592 reopen_state->options, errp);
4593 if (ret) {
4594 goto error;
4595 }
4596
Jeff Codye971aa12012-09-20 15:13:19 -04004597 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4598 if (ret) {
4599 if (local_err != NULL) {
4600 error_propagate(errp, local_err);
4601 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004602 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004603 error_setg(errp, "failed while preparing to reopen image '%s'",
4604 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004605 }
4606 goto error;
4607 }
4608 } else {
4609 /* It is currently mandatory to have a bdrv_reopen_prepare()
4610 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004611 error_setg(errp, "Block format '%s' used by node '%s' "
4612 "does not support reopening files", drv->format_name,
4613 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004614 ret = -1;
4615 goto error;
4616 }
4617
Max Reitz9ad08c42018-11-16 17:45:24 +01004618 drv_prepared = true;
4619
Alberto Garciabacd9b82019-03-12 18:48:46 +02004620 /*
4621 * We must provide the 'backing' option if the BDS has a backing
4622 * file or if the image file has a backing file name as part of
4623 * its metadata. Otherwise the 'backing' option can be omitted.
4624 */
4625 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004626 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004627 error_setg(errp, "backing is missing for '%s'",
4628 reopen_state->bs->node_name);
4629 ret = -EINVAL;
4630 goto error;
4631 }
4632
Alberto Garciacb828c32019-03-12 18:48:47 +02004633 /*
4634 * Allow changing the 'backing' option. The new value can be
4635 * either a reference to an existing node (using its node name)
4636 * or NULL to simply detach the current backing file.
4637 */
4638 ret = bdrv_reopen_parse_backing(reopen_state, errp);
4639 if (ret < 0) {
4640 goto error;
4641 }
4642 qdict_del(reopen_state->options, "backing");
4643
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004644 /* Options that are not handled are only okay if they are unchanged
4645 * compared to the old state. It is expected that some options are only
4646 * used for the initial open, but not reopen (e.g. filename) */
4647 if (qdict_size(reopen_state->options)) {
4648 const QDictEntry *entry = qdict_first(reopen_state->options);
4649
4650 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004651 QObject *new = entry->value;
4652 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004653
Alberto Garciadb905282018-09-06 12:37:05 +03004654 /* Allow child references (child_name=node_name) as long as they
4655 * point to the current child (i.e. everything stays the same). */
4656 if (qobject_type(new) == QTYPE_QSTRING) {
4657 BdrvChild *child;
4658 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4659 if (!strcmp(child->name, entry->key)) {
4660 break;
4661 }
4662 }
4663
4664 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004665 if (!strcmp(child->bs->node_name,
4666 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004667 continue; /* Found child with this name, skip option */
4668 }
4669 }
4670 }
4671
Max Reitz54fd1b02017-11-14 19:01:26 +01004672 /*
4673 * TODO: When using -drive to specify blockdev options, all values
4674 * will be strings; however, when using -blockdev, blockdev-add or
4675 * filenames using the json:{} pseudo-protocol, they will be
4676 * correctly typed.
4677 * In contrast, reopening options are (currently) always strings
4678 * (because you can only specify them through qemu-io; all other
4679 * callers do not specify any options).
4680 * Therefore, when using anything other than -drive to create a BDS,
4681 * this cannot detect non-string options as unchanged, because
4682 * qobject_is_equal() always returns false for objects of different
4683 * type. In the future, this should be remedied by correctly typing
4684 * all options. For now, this is not too big of an issue because
4685 * the user can simply omit options which cannot be changed anyway,
4686 * so they will stay unchanged.
4687 */
4688 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004689 error_setg(errp, "Cannot change the option '%s'", entry->key);
4690 ret = -EINVAL;
4691 goto error;
4692 }
4693 } while ((entry = qdict_next(reopen_state->options, entry)));
4694 }
4695
Jeff Codye971aa12012-09-20 15:13:19 -04004696 ret = 0;
4697
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004698 /* Restore the original reopen_state->options QDict */
4699 qobject_unref(reopen_state->options);
4700 reopen_state->options = qobject_ref(orig_reopen_opts);
4701
Jeff Codye971aa12012-09-20 15:13:19 -04004702error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004703 if (ret < 0 && drv_prepared) {
4704 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4705 * call drv->bdrv_reopen_abort() before signaling an error
4706 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4707 * when the respective bdrv_reopen_prepare() has failed) */
4708 if (drv->bdrv_reopen_abort) {
4709 drv->bdrv_reopen_abort(reopen_state);
4710 }
4711 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004712 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004713 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004714 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004715 return ret;
4716}
4717
4718/*
4719 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4720 * makes them final by swapping the staging BlockDriverState contents into
4721 * the active BlockDriverState contents.
4722 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004723static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004724{
4725 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004726 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004727 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004728
4729 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004730 bs = reopen_state->bs;
4731 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004732 assert(drv != NULL);
4733
4734 /* If there are any driver level actions to take */
4735 if (drv->bdrv_reopen_commit) {
4736 drv->bdrv_reopen_commit(reopen_state);
4737 }
4738
4739 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004740 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004741 qobject_unref(bs->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004742
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004743 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004744 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004745 bs->open_flags = reopen_state->flags;
4746 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
Alberto Garcia543770b2018-09-06 12:37:09 +03004747 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004748
Alberto Garciacb828c32019-03-12 18:48:47 +02004749 if (reopen_state->replace_backing_bs) {
4750 qdict_del(bs->explicit_options, "backing");
4751 qdict_del(bs->options, "backing");
4752 }
4753
Alberto Garcia50196d72018-09-06 12:37:03 +03004754 /* Remove child references from bs->options and bs->explicit_options.
4755 * Child options were already removed in bdrv_reopen_queue_child() */
4756 QLIST_FOREACH(child, &bs->children, next) {
4757 qdict_del(bs->explicit_options, child->name);
4758 qdict_del(bs->options, child->name);
4759 }
4760
Alberto Garciacb828c32019-03-12 18:48:47 +02004761 /*
4762 * Change the backing file if a new one was specified. We do this
4763 * after updating bs->options, so bdrv_refresh_filename() (called
4764 * from bdrv_set_backing_hd()) has the new values.
4765 */
4766 if (reopen_state->replace_backing_bs) {
Max Reitz1d42f482019-06-12 17:24:39 +02004767 BlockDriverState *old_backing_bs = child_bs(bs->backing);
Alberto Garciacb828c32019-03-12 18:48:47 +02004768 assert(!old_backing_bs || !old_backing_bs->implicit);
4769 /* Abort the permission update on the backing bs we're detaching */
4770 if (old_backing_bs) {
4771 bdrv_abort_perm_update(old_backing_bs);
4772 }
4773 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4774 }
4775
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004776 bdrv_refresh_limits(bs, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004777}
4778
4779/*
4780 * Abort the reopen, and delete and free the staged changes in
4781 * reopen_state
4782 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004783static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004784{
4785 BlockDriver *drv;
4786
4787 assert(reopen_state != NULL);
4788 drv = reopen_state->bs->drv;
4789 assert(drv != NULL);
4790
4791 if (drv->bdrv_reopen_abort) {
4792 drv->bdrv_reopen_abort(reopen_state);
4793 }
4794}
4795
4796
Max Reitz64dff522016-01-29 16:36:10 +01004797static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004798{
Max Reitz33384422014-06-20 21:57:33 +02004799 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004800 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004801
Max Reitz30f55fb2016-05-17 16:41:32 +02004802 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004803
Paolo Bonzinifc272912015-12-23 11:48:24 +01004804 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004805 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004806 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004807
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004808 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004809 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004810 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004811 bs->drv->bdrv_close(bs);
4812 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004813 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004814 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004815
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004816 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004817 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004818 }
4819
Alberto Garciadd4118c2019-05-13 16:46:17 +03004820 bs->backing = NULL;
4821 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004822 g_free(bs->opaque);
4823 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004824 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004825 bs->backing_file[0] = '\0';
4826 bs->backing_format[0] = '\0';
4827 bs->total_sectors = 0;
4828 bs->encrypted = false;
4829 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004830 qobject_unref(bs->options);
4831 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004832 bs->options = NULL;
4833 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004834 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004835 bs->full_open_options = NULL;
4836
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004837 bdrv_release_named_dirty_bitmaps(bs);
4838 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4839
Max Reitz33384422014-06-20 21:57:33 +02004840 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4841 g_free(ban);
4842 }
4843 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004844 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004845
4846 /*
4847 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4848 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4849 * gets called.
4850 */
4851 if (bs->quiesce_counter) {
4852 bdrv_drain_all_end_quiesce(bs);
4853 }
bellardb3380822004-03-14 21:38:54 +00004854}
4855
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004856void bdrv_close_all(void)
4857{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004858 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004859
Max Reitzca9bd242016-01-29 16:36:14 +01004860 /* Drop references from requests still in flight, such as canceled block
4861 * jobs whose AIO context has not been polled yet */
4862 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004863
Max Reitzca9bd242016-01-29 16:36:14 +01004864 blk_remove_all_bs();
4865 blockdev_close_all_bdrv_states();
4866
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004867 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004868}
4869
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004870static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004871{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004872 GQueue *queue;
4873 GHashTable *found;
4874 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004875
Max Reitzbd86fb92020-05-13 13:05:13 +02004876 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004877 return false;
4878 }
4879
Max Reitzec9f10f2018-06-13 20:18:15 +02004880 /* If the child @c belongs to the BDS @to, replacing the current
4881 * c->bs by @to would mean to create a loop.
4882 *
4883 * Such a case occurs when appending a BDS to a backing chain.
4884 * For instance, imagine the following chain:
4885 *
4886 * guest device -> node A -> further backing chain...
4887 *
4888 * Now we create a new BDS B which we want to put on top of this
4889 * chain, so we first attach A as its backing node:
4890 *
4891 * node B
4892 * |
4893 * v
4894 * guest device -> node A -> further backing chain...
4895 *
4896 * Finally we want to replace A by B. When doing that, we want to
4897 * replace all pointers to A by pointers to B -- except for the
4898 * pointer from B because (1) that would create a loop, and (2)
4899 * that pointer should simply stay intact:
4900 *
4901 * guest device -> node B
4902 * |
4903 * v
4904 * node A -> further backing chain...
4905 *
4906 * In general, when replacing a node A (c->bs) by a node B (@to),
4907 * if A is a child of B, that means we cannot replace A by B there
4908 * because that would create a loop. Silently detaching A from B
4909 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004910 * place there is the most sensible choice.
4911 *
4912 * We would also create a loop in any cases where @c is only
4913 * indirectly referenced by @to. Prevent this by returning false
4914 * if @c is found (by breadth-first search) anywhere in the whole
4915 * subtree of @to.
4916 */
4917
4918 ret = true;
4919 found = g_hash_table_new(NULL, NULL);
4920 g_hash_table_add(found, to);
4921 queue = g_queue_new();
4922 g_queue_push_tail(queue, to);
4923
4924 while (!g_queue_is_empty(queue)) {
4925 BlockDriverState *v = g_queue_pop_head(queue);
4926 BdrvChild *c2;
4927
4928 QLIST_FOREACH(c2, &v->children, next) {
4929 if (c2 == c) {
4930 ret = false;
4931 break;
4932 }
4933
4934 if (g_hash_table_contains(found, c2->bs)) {
4935 continue;
4936 }
4937
4938 g_queue_push_tail(queue, c2->bs);
4939 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004940 }
4941 }
4942
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004943 g_queue_free(queue);
4944 g_hash_table_destroy(found);
4945
4946 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004947}
4948
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004949/*
4950 * With auto_skip=true bdrv_replace_node_common skips updating from parents
4951 * if it creates a parent-child relation loop or if parent is block-job.
4952 *
4953 * With auto_skip=false the error is returned if from has a parent which should
4954 * not be updated.
4955 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004956static int bdrv_replace_node_common(BlockDriverState *from,
4957 BlockDriverState *to,
4958 bool auto_skip, Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004959{
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004960 BdrvChild *c, *next;
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004961 Transaction *tran = tran_new();
4962 g_autoptr(GHashTable) found = NULL;
4963 g_autoptr(GSList) refresh_list = NULL;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004964 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004965
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004966 /* Make sure that @from doesn't go away until we have successfully attached
4967 * all of its parents to @to. */
4968 bdrv_ref(from);
4969
Kevin Wolff871abd2019-05-21 19:00:25 +02004970 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01004971 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02004972 bdrv_drained_begin(from);
4973
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004974 /*
4975 * Do the replacement without permission update.
4976 * Replacement may influence the permissions, we should calculate new
4977 * permissions based on new graph. If we fail, we'll roll-back the
4978 * replacement.
4979 */
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004980 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
Max Reitzec9f10f2018-06-13 20:18:15 +02004981 assert(c->bs == from);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004982 if (!should_update_child(c, to)) {
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004983 if (auto_skip) {
4984 continue;
4985 }
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004986 ret = -EINVAL;
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004987 error_setg(errp, "Should not change '%s' link to '%s'",
4988 c->name, from->node_name);
4989 goto out;
Kevin Wolf26de9432017-01-17 13:39:34 +01004990 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004991 if (c->frozen) {
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004992 ret = -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004993 error_setg(errp, "Cannot change '%s' link to '%s'",
4994 c->name, from->node_name);
4995 goto out;
4996 }
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03004997 bdrv_replace_child_safe(c, to, tran);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004998 }
4999
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005000 found = g_hash_table_new(NULL, NULL);
5001
5002 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5003 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5004
5005 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005006 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005007 goto out;
5008 }
5009
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005010 ret = 0;
5011
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005012out:
Vladimir Sementsov-Ogievskiy3bb0e292021-04-28 18:17:45 +03005013 tran_finalize(tran, ret);
5014
Kevin Wolff871abd2019-05-21 19:00:25 +02005015 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005016 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005017
5018 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005019}
5020
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005021int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5022 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03005023{
5024 return bdrv_replace_node_common(from, to, true, errp);
5025}
5026
Jeff Cody8802d1f2012-02-28 15:54:06 -05005027/*
5028 * Add new bs contents at the top of an image chain while the chain is
5029 * live, while keeping required fields on the top layer.
5030 *
5031 * This will modify the BlockDriverState fields, and swap contents
5032 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5033 *
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02005034 * bs_new must not be attached to a BlockBackend.
Jeff Codyf6801b82012-03-27 16:30:19 -04005035 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05005036 * This function does not create any image files.
5037 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005038int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5039 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05005040{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005041 int ret = bdrv_set_backing_hd(bs_new, bs_top, errp);
5042 if (ret < 0) {
Vladimir Sementsov-Ogievskiyae9d4412021-04-28 18:17:32 +03005043 return ret;
Kevin Wolfb2c28322017-02-20 12:46:42 +01005044 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005045
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03005046 ret = bdrv_replace_node(bs_top, bs_new, errp);
5047 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005048 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
Vladimir Sementsov-Ogievskiyae9d4412021-04-28 18:17:32 +03005049 return ret;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01005050 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02005051
Vladimir Sementsov-Ogievskiyae9d4412021-04-28 18:17:32 +03005052 return 0;
Jeff Cody8802d1f2012-02-28 15:54:06 -05005053}
5054
Fam Zheng4f6fd342013-08-23 09:14:47 +08005055static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00005056{
Fam Zheng3718d8a2014-05-23 21:29:43 +08005057 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08005058 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02005059
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01005060 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01005061 if (bs->node_name[0] != '\0') {
5062 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5063 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01005064 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5065
Anton Kuchin30c321f2019-05-07 11:12:56 +03005066 bdrv_close(bs);
5067
Anthony Liguori7267c092011-08-20 22:09:37 -05005068 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00005069}
5070
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03005071BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *node_options,
5072 int flags, Error **errp)
5073{
5074 BlockDriverState *new_node_bs;
5075 Error *local_err = NULL;
5076
5077 new_node_bs = bdrv_open(NULL, NULL, node_options, flags, errp);
5078 if (new_node_bs == NULL) {
5079 error_prepend(errp, "Could not create node: ");
5080 return NULL;
5081 }
5082
5083 bdrv_drained_begin(bs);
5084 bdrv_replace_node(bs, new_node_bs, &local_err);
5085 bdrv_drained_end(bs);
5086
5087 if (local_err) {
5088 bdrv_unref(new_node_bs);
5089 error_propagate(errp, local_err);
5090 return NULL;
5091 }
5092
5093 return new_node_bs;
5094}
5095
aliguorie97fc192009-04-21 23:11:50 +00005096/*
5097 * Run consistency checks on an image
5098 *
Kevin Wolfe076f332010-06-29 11:43:13 +02005099 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02005100 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02005101 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00005102 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005103int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5104 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00005105{
Max Reitz908bcd52014-08-07 22:47:55 +02005106 if (bs->drv == NULL) {
5107 return -ENOMEDIUM;
5108 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005109 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00005110 return -ENOTSUP;
5111 }
5112
Kevin Wolfe076f332010-06-29 11:43:13 +02005113 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01005114 return bs->drv->bdrv_co_check(bs, res, fix);
5115}
5116
Kevin Wolf756e6732010-01-12 12:55:17 +01005117/*
5118 * Return values:
5119 * 0 - success
5120 * -EINVAL - backing format specified, but no file
5121 * -ENOSPC - can't update the backing file because no space is left in the
5122 * image file header
5123 * -ENOTSUP - format driver doesn't support changing the backing file
5124 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05005125int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5126 const char *backing_fmt, bool warn)
Kevin Wolf756e6732010-01-12 12:55:17 +01005127{
5128 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02005129 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005130
Max Reitzd470ad42017-11-10 21:31:09 +01005131 if (!drv) {
5132 return -ENOMEDIUM;
5133 }
5134
Paolo Bonzini5f377792012-04-12 14:01:01 +02005135 /* Backing file format doesn't make sense without a backing file */
5136 if (backing_fmt && !backing_file) {
5137 return -EINVAL;
5138 }
5139
Eric Blakee54ee1b2020-07-06 15:39:53 -05005140 if (warn && backing_file && !backing_fmt) {
5141 warn_report("Deprecated use of backing file without explicit "
5142 "backing format, use of this image requires "
5143 "potentially unsafe format probing");
5144 }
5145
Kevin Wolf756e6732010-01-12 12:55:17 +01005146 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005147 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01005148 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02005149 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01005150 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02005151
5152 if (ret == 0) {
5153 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5154 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01005155 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5156 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02005157 }
5158 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01005159}
5160
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005161/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005162 * Finds the first non-filter node above bs in the chain between
5163 * active and bs. The returned node is either an immediate parent of
5164 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005165 *
5166 * Returns NULL if bs is not found in active's image chain,
5167 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005168 *
5169 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005170 */
5171BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5172 BlockDriverState *bs)
5173{
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005174 bs = bdrv_skip_filters(bs);
5175 active = bdrv_skip_filters(active);
5176
5177 while (active) {
5178 BlockDriverState *next = bdrv_backing_chain_next(active);
5179 if (bs == next) {
5180 return active;
5181 }
5182 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005183 }
5184
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005185 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005186}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005187
Jeff Cody4caf0fc2014-06-25 15:35:26 -04005188/* Given a BDS, searches for the base layer. */
5189BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5190{
5191 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005192}
5193
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005194/*
Max Reitz7b99a262019-06-12 16:07:11 +02005195 * Return true if at least one of the COW (backing) and filter links
5196 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005197 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005198 */
5199bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5200 Error **errp)
5201{
5202 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005203 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005204
Max Reitz7b99a262019-06-12 16:07:11 +02005205 for (i = bs; i != base; i = child_bs(child)) {
5206 child = bdrv_filter_or_cow_child(i);
5207
5208 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005209 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005210 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005211 return true;
5212 }
5213 }
5214
5215 return false;
5216}
5217
5218/*
Max Reitz7b99a262019-06-12 16:07:11 +02005219 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005220 * If any of the links is already frozen the operation is aborted and
5221 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005222 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005223 * Returns 0 on success. On failure returns < 0 and sets @errp.
5224 */
5225int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5226 Error **errp)
5227{
5228 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005229 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005230
5231 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5232 return -EPERM;
5233 }
5234
Max Reitz7b99a262019-06-12 16:07:11 +02005235 for (i = bs; i != base; i = child_bs(child)) {
5236 child = bdrv_filter_or_cow_child(i);
5237 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02005238 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02005239 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02005240 return -EPERM;
5241 }
5242 }
5243
Max Reitz7b99a262019-06-12 16:07:11 +02005244 for (i = bs; i != base; i = child_bs(child)) {
5245 child = bdrv_filter_or_cow_child(i);
5246 if (child) {
5247 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005248 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005249 }
5250
5251 return 0;
5252}
5253
5254/*
Max Reitz7b99a262019-06-12 16:07:11 +02005255 * Unfreeze all COW (backing) and filter links between @bs and @base.
5256 * The caller must ensure that all links are frozen before using this
5257 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005258 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005259 */
5260void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5261{
5262 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005263 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005264
Max Reitz7b99a262019-06-12 16:07:11 +02005265 for (i = bs; i != base; i = child_bs(child)) {
5266 child = bdrv_filter_or_cow_child(i);
5267 if (child) {
5268 assert(child->frozen);
5269 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005270 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005271 }
5272}
5273
5274/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005275 * Drops images above 'base' up to and including 'top', and sets the image
5276 * above 'top' to have base as its backing file.
5277 *
5278 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5279 * information in 'bs' can be properly updated.
5280 *
5281 * E.g., this will convert the following chain:
5282 * bottom <- base <- intermediate <- top <- active
5283 *
5284 * to
5285 *
5286 * bottom <- base <- active
5287 *
5288 * It is allowed for bottom==base, in which case it converts:
5289 *
5290 * base <- intermediate <- top <- active
5291 *
5292 * to
5293 *
5294 * base <- active
5295 *
Jeff Cody54e26902014-06-25 15:40:10 -04005296 * If backing_file_str is non-NULL, it will be used when modifying top's
5297 * overlay image metadata.
5298 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005299 * Error conditions:
5300 * if active == top, that is considered an error
5301 *
5302 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005303int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5304 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005305{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005306 BlockDriverState *explicit_top = top;
5307 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005308 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005309 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005310 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005311 g_autoptr(GSList) updated_children = NULL;
5312 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005313
Kevin Wolf6858eba2017-06-29 19:32:21 +02005314 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005315 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005316
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005317 if (!top->drv || !base->drv) {
5318 goto exit;
5319 }
5320
Kevin Wolf5db15a52015-09-14 15:33:33 +02005321 /* Make sure that base is in the backing chain of top */
5322 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005323 goto exit;
5324 }
5325
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005326 /* If 'base' recursively inherits from 'top' then we should set
5327 * base->inherits_from to top->inherits_from after 'top' and all
5328 * other intermediate nodes have been dropped.
5329 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5330 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005331 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005332 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5333
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005334 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolfbde70712017-06-27 20:36:18 +02005335 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
5336 * we've figured out how they should work. */
Max Reitzf30c66b2019-02-01 20:29:05 +01005337 if (!backing_file_str) {
5338 bdrv_refresh_filename(base);
5339 backing_file_str = base->filename;
5340 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005341
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005342 QLIST_FOREACH(c, &top->parents, next_parent) {
5343 updated_children = g_slist_prepend(updated_children, c);
5344 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005345
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005346 bdrv_replace_node_common(top, base, false, &local_err);
5347 if (local_err) {
5348 error_report_err(local_err);
5349 goto exit;
5350 }
5351
5352 for (p = updated_children; p; p = p->next) {
5353 c = p->data;
5354
Max Reitzbd86fb92020-05-13 13:05:13 +02005355 if (c->klass->update_filename) {
5356 ret = c->klass->update_filename(c, base, backing_file_str,
5357 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005358 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005359 /*
5360 * TODO: Actually, we want to rollback all previous iterations
5361 * of this loop, and (which is almost impossible) previous
5362 * bdrv_replace_node()...
5363 *
5364 * Note, that c->klass->update_filename may lead to permission
5365 * update, so it's a bad idea to call it inside permission
5366 * update transaction of bdrv_replace_node.
5367 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005368 error_report_err(local_err);
5369 goto exit;
5370 }
5371 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005372 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005373
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005374 if (update_inherits_from) {
5375 base->inherits_from = explicit_top->inherits_from;
5376 }
5377
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005378 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005379exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005380 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005381 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005382 return ret;
5383}
5384
bellard83f64092006-08-01 16:21:11 +00005385/**
Max Reitz081e4652019-06-12 18:14:13 +02005386 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5387 * sums the size of all data-bearing children. (This excludes backing
5388 * children.)
5389 */
5390static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5391{
5392 BdrvChild *child;
5393 int64_t child_size, sum = 0;
5394
5395 QLIST_FOREACH(child, &bs->children, next) {
5396 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5397 BDRV_CHILD_FILTERED))
5398 {
5399 child_size = bdrv_get_allocated_file_size(child->bs);
5400 if (child_size < 0) {
5401 return child_size;
5402 }
5403 sum += child_size;
5404 }
5405 }
5406
5407 return sum;
5408}
5409
5410/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005411 * Length of a allocated file in bytes. Sparse files are counted by actual
5412 * allocated space. Return < 0 if error or unknown.
5413 */
5414int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5415{
5416 BlockDriver *drv = bs->drv;
5417 if (!drv) {
5418 return -ENOMEDIUM;
5419 }
5420 if (drv->bdrv_get_allocated_file_size) {
5421 return drv->bdrv_get_allocated_file_size(bs);
5422 }
Max Reitz081e4652019-06-12 18:14:13 +02005423
5424 if (drv->bdrv_file_open) {
5425 /*
5426 * Protocol drivers default to -ENOTSUP (most of their data is
5427 * not stored in any of their children (if they even have any),
5428 * so there is no generic way to figure it out).
5429 */
5430 return -ENOTSUP;
5431 } else if (drv->is_filter) {
5432 /* Filter drivers default to the size of their filtered child */
5433 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5434 } else {
5435 /* Other drivers default to summing their children's sizes */
5436 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005437 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005438}
5439
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005440/*
5441 * bdrv_measure:
5442 * @drv: Format driver
5443 * @opts: Creation options for new image
5444 * @in_bs: Existing image containing data for new image (may be NULL)
5445 * @errp: Error object
5446 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5447 * or NULL on error
5448 *
5449 * Calculate file size required to create a new image.
5450 *
5451 * If @in_bs is given then space for allocated clusters and zero clusters
5452 * from that image are included in the calculation. If @opts contains a
5453 * backing file that is shared by @in_bs then backing clusters may be omitted
5454 * from the calculation.
5455 *
5456 * If @in_bs is NULL then the calculation includes no allocated clusters
5457 * unless a preallocation option is given in @opts.
5458 *
5459 * Note that @in_bs may use a different BlockDriver from @drv.
5460 *
5461 * If an error occurs the @errp pointer is set.
5462 */
5463BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5464 BlockDriverState *in_bs, Error **errp)
5465{
5466 if (!drv->bdrv_measure) {
5467 error_setg(errp, "Block driver '%s' does not support size measurement",
5468 drv->format_name);
5469 return NULL;
5470 }
5471
5472 return drv->bdrv_measure(opts, in_bs, errp);
5473}
5474
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005475/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005476 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005477 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005478int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005479{
5480 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005481
bellard83f64092006-08-01 16:21:11 +00005482 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005483 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005484
Kevin Wolfb94a2612013-10-29 12:18:58 +01005485 if (drv->has_variable_length) {
5486 int ret = refresh_total_sectors(bs, bs->total_sectors);
5487 if (ret < 0) {
5488 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005489 }
bellard83f64092006-08-01 16:21:11 +00005490 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005491 return bs->total_sectors;
5492}
5493
5494/**
5495 * Return length in bytes on success, -errno on error.
5496 * The length is always a multiple of BDRV_SECTOR_SIZE.
5497 */
5498int64_t bdrv_getlength(BlockDriverState *bs)
5499{
5500 int64_t ret = bdrv_nb_sectors(bs);
5501
Eric Blake122860b2020-11-05 09:51:22 -06005502 if (ret < 0) {
5503 return ret;
5504 }
5505 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5506 return -EFBIG;
5507 }
5508 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005509}
5510
bellard19cb3732006-08-19 11:45:59 +00005511/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005512void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005513{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005514 int64_t nb_sectors = bdrv_nb_sectors(bs);
5515
5516 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005517}
bellardcf989512004-02-16 21:56:36 +00005518
Eric Blake54115412016-06-23 16:37:26 -06005519bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005520{
5521 return bs->sg;
5522}
5523
Max Reitzae23f782019-06-12 22:57:15 +02005524/**
5525 * Return whether the given node supports compressed writes.
5526 */
5527bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5528{
5529 BlockDriverState *filtered;
5530
5531 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5532 return false;
5533 }
5534
5535 filtered = bdrv_filter_bs(bs);
5536 if (filtered) {
5537 /*
5538 * Filters can only forward compressed writes, so we have to
5539 * check the child.
5540 */
5541 return bdrv_supports_compressed_writes(filtered);
5542 }
5543
5544 return true;
5545}
5546
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005547const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005548{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005549 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005550}
5551
Stefan Hajnocziada42402014-08-27 12:08:55 +01005552static int qsort_strcmp(const void *a, const void *b)
5553{
Max Reitzceff5bd2016-10-12 22:49:05 +02005554 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005555}
5556
ths5fafdf22007-09-16 21:08:06 +00005557void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005558 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005559{
5560 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005561 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005562 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005563 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005564
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005565 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005566 if (drv->format_name) {
5567 bool found = false;
5568 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005569
5570 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5571 continue;
5572 }
5573
Jeff Codye855e4f2014-04-28 18:29:54 -04005574 while (formats && i && !found) {
5575 found = !strcmp(formats[--i], drv->format_name);
5576 }
5577
5578 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005579 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005580 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005581 }
5582 }
bellardea2384d2004-08-01 21:59:26 +00005583 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005584
Max Reitzeb0df692016-10-12 22:49:06 +02005585 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5586 const char *format_name = block_driver_modules[i].format_name;
5587
5588 if (format_name) {
5589 bool found = false;
5590 int j = count;
5591
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005592 if (use_bdrv_whitelist &&
5593 !bdrv_format_is_whitelisted(format_name, read_only)) {
5594 continue;
5595 }
5596
Max Reitzeb0df692016-10-12 22:49:06 +02005597 while (formats && j && !found) {
5598 found = !strcmp(formats[--j], format_name);
5599 }
5600
5601 if (!found) {
5602 formats = g_renew(const char *, formats, count + 1);
5603 formats[count++] = format_name;
5604 }
5605 }
5606 }
5607
Stefan Hajnocziada42402014-08-27 12:08:55 +01005608 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5609
5610 for (i = 0; i < count; i++) {
5611 it(opaque, formats[i]);
5612 }
5613
Jeff Codye855e4f2014-04-28 18:29:54 -04005614 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005615}
5616
Benoît Canetdc364f42014-01-23 21:31:32 +01005617/* This function is to find a node in the bs graph */
5618BlockDriverState *bdrv_find_node(const char *node_name)
5619{
5620 BlockDriverState *bs;
5621
5622 assert(node_name);
5623
5624 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5625 if (!strcmp(node_name, bs->node_name)) {
5626 return bs;
5627 }
5628 }
5629 return NULL;
5630}
5631
Benoît Canetc13163f2014-01-23 21:31:34 +01005632/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005633BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5634 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005635{
Eric Blake9812e712020-10-27 00:05:47 -05005636 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005637 BlockDriverState *bs;
5638
5639 list = NULL;
5640 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005641 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005642 if (!info) {
5643 qapi_free_BlockDeviceInfoList(list);
5644 return NULL;
5645 }
Eric Blake9812e712020-10-27 00:05:47 -05005646 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005647 }
5648
5649 return list;
5650}
5651
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005652typedef struct XDbgBlockGraphConstructor {
5653 XDbgBlockGraph *graph;
5654 GHashTable *graph_nodes;
5655} XDbgBlockGraphConstructor;
5656
5657static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5658{
5659 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5660
5661 gr->graph = g_new0(XDbgBlockGraph, 1);
5662 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5663
5664 return gr;
5665}
5666
5667static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5668{
5669 XDbgBlockGraph *graph = gr->graph;
5670
5671 g_hash_table_destroy(gr->graph_nodes);
5672 g_free(gr);
5673
5674 return graph;
5675}
5676
5677static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5678{
5679 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5680
5681 if (ret != 0) {
5682 return ret;
5683 }
5684
5685 /*
5686 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5687 * answer of g_hash_table_lookup.
5688 */
5689 ret = g_hash_table_size(gr->graph_nodes) + 1;
5690 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5691
5692 return ret;
5693}
5694
5695static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5696 XDbgBlockGraphNodeType type, const char *name)
5697{
5698 XDbgBlockGraphNode *n;
5699
5700 n = g_new0(XDbgBlockGraphNode, 1);
5701
5702 n->id = xdbg_graph_node_num(gr, node);
5703 n->type = type;
5704 n->name = g_strdup(name);
5705
Eric Blake9812e712020-10-27 00:05:47 -05005706 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005707}
5708
5709static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5710 const BdrvChild *child)
5711{
Max Reitzcdb1cec2019-11-08 13:34:52 +01005712 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005713 XDbgBlockGraphEdge *edge;
5714
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005715 edge = g_new0(XDbgBlockGraphEdge, 1);
5716
5717 edge->parent = xdbg_graph_node_num(gr, parent);
5718 edge->child = xdbg_graph_node_num(gr, child->bs);
5719 edge->name = g_strdup(child->name);
5720
Max Reitzcdb1cec2019-11-08 13:34:52 +01005721 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5722 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5723
5724 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005725 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005726 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01005727 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005728 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005729 }
5730 }
5731
Eric Blake9812e712020-10-27 00:05:47 -05005732 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005733}
5734
5735
5736XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5737{
5738 BlockBackend *blk;
5739 BlockJob *job;
5740 BlockDriverState *bs;
5741 BdrvChild *child;
5742 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5743
5744 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5745 char *allocated_name = NULL;
5746 const char *name = blk_name(blk);
5747
5748 if (!*name) {
5749 name = allocated_name = blk_get_attached_dev_id(blk);
5750 }
5751 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5752 name);
5753 g_free(allocated_name);
5754 if (blk_root(blk)) {
5755 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5756 }
5757 }
5758
5759 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5760 GSList *el;
5761
5762 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5763 job->job.id);
5764 for (el = job->nodes; el; el = el->next) {
5765 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5766 }
5767 }
5768
5769 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5770 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5771 bs->node_name);
5772 QLIST_FOREACH(child, &bs->children, next) {
5773 xdbg_graph_add_edge(gr, bs, child);
5774 }
5775 }
5776
5777 return xdbg_graph_finalize(gr);
5778}
5779
Benoît Canet12d3ba82014-01-23 21:31:35 +01005780BlockDriverState *bdrv_lookup_bs(const char *device,
5781 const char *node_name,
5782 Error **errp)
5783{
Markus Armbruster7f06d472014-10-07 13:59:12 +02005784 BlockBackend *blk;
5785 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005786
Benoît Canet12d3ba82014-01-23 21:31:35 +01005787 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02005788 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005789
Markus Armbruster7f06d472014-10-07 13:59:12 +02005790 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005791 bs = blk_bs(blk);
5792 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02005793 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02005794 }
5795
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005796 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005797 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005798 }
5799
Benoît Canetdd67fa52014-02-12 17:15:06 +01005800 if (node_name) {
5801 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005802
Benoît Canetdd67fa52014-02-12 17:15:06 +01005803 if (bs) {
5804 return bs;
5805 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005806 }
5807
Connor Kuehl785ec4b2021-03-05 09:19:28 -06005808 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01005809 device ? device : "",
5810 node_name ? node_name : "");
5811 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005812}
5813
Jeff Cody5a6684d2014-06-25 15:40:09 -04005814/* If 'base' is in the same chain as 'top', return true. Otherwise,
5815 * return false. If either argument is NULL, return false. */
5816bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5817{
5818 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005819 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04005820 }
5821
5822 return top != NULL;
5823}
5824
Fam Zheng04df7652014-10-31 11:32:54 +08005825BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5826{
5827 if (!bs) {
5828 return QTAILQ_FIRST(&graph_bdrv_states);
5829 }
5830 return QTAILQ_NEXT(bs, node_list);
5831}
5832
Kevin Wolf0f122642018-03-28 18:29:18 +02005833BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5834{
5835 if (!bs) {
5836 return QTAILQ_FIRST(&all_bdrv_states);
5837 }
5838 return QTAILQ_NEXT(bs, bs_list);
5839}
5840
Fam Zheng20a9e772014-10-31 11:32:55 +08005841const char *bdrv_get_node_name(const BlockDriverState *bs)
5842{
5843 return bs->node_name;
5844}
5845
Kevin Wolf1f0c4612016-03-22 18:38:44 +01005846const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005847{
5848 BdrvChild *c;
5849 const char *name;
5850
5851 /* If multiple parents have a name, just pick the first one. */
5852 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005853 if (c->klass->get_name) {
5854 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005855 if (name && *name) {
5856 return name;
5857 }
5858 }
5859 }
5860
5861 return NULL;
5862}
5863
Markus Armbruster7f06d472014-10-07 13:59:12 +02005864/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02005865const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005866{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005867 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00005868}
5869
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005870/* This can be used to identify nodes that might not have a device
5871 * name associated. Since node and device names live in the same
5872 * namespace, the result is unambiguous. The exception is if both are
5873 * absent, then this returns an empty (non-null) string. */
5874const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5875{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005876 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005877}
5878
Markus Armbrusterc8433282012-06-05 16:49:24 +02005879int bdrv_get_flags(BlockDriverState *bs)
5880{
5881 return bs->open_flags;
5882}
5883
Peter Lieven3ac21622013-06-28 12:47:42 +02005884int bdrv_has_zero_init_1(BlockDriverState *bs)
5885{
5886 return 1;
5887}
5888
Kevin Wolff2feebb2010-04-14 17:30:35 +02005889int bdrv_has_zero_init(BlockDriverState *bs)
5890{
Max Reitz93393e62019-06-12 17:03:38 +02005891 BlockDriverState *filtered;
5892
Max Reitzd470ad42017-11-10 21:31:09 +01005893 if (!bs->drv) {
5894 return 0;
5895 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005896
Paolo Bonzini11212d82013-09-04 19:00:27 +02005897 /* If BS is a copy on write image, it is initialized to
5898 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02005899 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02005900 return 0;
5901 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02005902 if (bs->drv->bdrv_has_zero_init) {
5903 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02005904 }
Max Reitz93393e62019-06-12 17:03:38 +02005905
5906 filtered = bdrv_filter_bs(bs);
5907 if (filtered) {
5908 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005909 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005910
Peter Lieven3ac21622013-06-28 12:47:42 +02005911 /* safe default */
5912 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02005913}
5914
Peter Lieven4ce78692013-10-24 12:06:54 +02005915bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5916{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03005917 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02005918 return false;
5919 }
5920
Eric Blakee24d8132018-01-26 13:34:39 -06005921 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02005922}
5923
ths5fafdf22007-09-16 21:08:06 +00005924void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00005925 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00005926{
Kevin Wolf3574c602011-10-26 11:02:11 +02005927 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00005928}
5929
bellardfaea38e2006-08-05 21:31:00 +00005930int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5931{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005932 int ret;
bellardfaea38e2006-08-05 21:31:00 +00005933 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005934 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5935 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00005936 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005937 }
5938 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02005939 BlockDriverState *filtered = bdrv_filter_bs(bs);
5940 if (filtered) {
5941 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005942 }
bellardfaea38e2006-08-05 21:31:00 +00005943 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005944 }
bellardfaea38e2006-08-05 21:31:00 +00005945 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005946 ret = drv->bdrv_get_info(bs, bdi);
5947 if (ret < 0) {
5948 return ret;
5949 }
5950
5951 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
5952 return -EINVAL;
5953 }
5954
5955 return 0;
bellardfaea38e2006-08-05 21:31:00 +00005956}
5957
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005958ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5959 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02005960{
5961 BlockDriver *drv = bs->drv;
5962 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005963 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02005964 }
5965 return NULL;
5966}
5967
Anton Nefedovd9245592019-09-23 15:17:37 +03005968BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5969{
5970 BlockDriver *drv = bs->drv;
5971 if (!drv || !drv->bdrv_get_specific_stats) {
5972 return NULL;
5973 }
5974 return drv->bdrv_get_specific_stats(bs);
5975}
5976
Eric Blakea31939e2015-11-18 01:52:54 -07005977void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005978{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005979 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005980 return;
5981 }
5982
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005983 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005984}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005985
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005986static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01005987{
5988 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02005989 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005990 }
5991
5992 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005993 assert(bs->drv->bdrv_debug_remove_breakpoint);
5994 return bs;
5995 }
5996
5997 return NULL;
5998}
5999
6000int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6001 const char *tag)
6002{
6003 bs = bdrv_find_debug_node(bs);
6004 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01006005 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6006 }
6007
6008 return -ENOTSUP;
6009}
6010
Fam Zheng4cc70e92013-11-20 10:01:54 +08006011int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6012{
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03006013 bs = bdrv_find_debug_node(bs);
6014 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08006015 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6016 }
6017
6018 return -ENOTSUP;
6019}
6020
Kevin Wolf41c695c2012-12-06 14:32:58 +01006021int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6022{
Max Reitz938789e2014-03-10 23:44:08 +01006023 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02006024 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006025 }
6026
6027 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6028 return bs->drv->bdrv_debug_resume(bs, tag);
6029 }
6030
6031 return -ENOTSUP;
6032}
6033
6034bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6035{
6036 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02006037 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01006038 }
6039
6040 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6041 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6042 }
6043
6044 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01006045}
6046
Jeff Codyb1b1d782012-10-16 15:49:09 -04006047/* backing_file can either be relative, or absolute, or a protocol. If it is
6048 * relative, it must be relative to the chain. So, passing in bs->filename
6049 * from a BDS as backing_file should not be done, as that may be relative to
6050 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006051BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6052 const char *backing_file)
6053{
Jeff Codyb1b1d782012-10-16 15:49:09 -04006054 char *filename_full = NULL;
6055 char *backing_file_full = NULL;
6056 char *filename_tmp = NULL;
6057 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02006058 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006059 BlockDriverState *curr_bs = NULL;
6060 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006061 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006062
6063 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006064 return NULL;
6065 }
6066
Jeff Codyb1b1d782012-10-16 15:49:09 -04006067 filename_full = g_malloc(PATH_MAX);
6068 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006069
6070 is_protocol = path_has_protocol(backing_file);
6071
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006072 /*
6073 * Being largely a legacy function, skip any filters here
6074 * (because filters do not have normal filenames, so they cannot
6075 * match anyway; and allowing json:{} filenames is a bit out of
6076 * scope).
6077 */
6078 for (curr_bs = bdrv_skip_filters(bs);
6079 bdrv_cow_child(curr_bs) != NULL;
6080 curr_bs = bs_below)
6081 {
6082 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006083
Max Reitz0b877d02018-08-01 20:34:11 +02006084 if (bdrv_backing_overridden(curr_bs)) {
6085 /*
6086 * If the backing file was overridden, we can only compare
6087 * directly against the backing node's filename.
6088 */
6089
6090 if (!filenames_refreshed) {
6091 /*
6092 * This will automatically refresh all of the
6093 * filenames in the rest of the backing chain, so we
6094 * only need to do this once.
6095 */
6096 bdrv_refresh_filename(bs_below);
6097 filenames_refreshed = true;
6098 }
6099
6100 if (strcmp(backing_file, bs_below->filename) == 0) {
6101 retval = bs_below;
6102 break;
6103 }
6104 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6105 /*
6106 * If either of the filename paths is actually a protocol, then
6107 * compare unmodified paths; otherwise make paths relative.
6108 */
Max Reitz6b6833c2019-02-01 20:29:15 +01006109 char *backing_file_full_ret;
6110
Jeff Codyb1b1d782012-10-16 15:49:09 -04006111 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006112 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006113 break;
6114 }
Jeff Cody418661e2017-01-25 20:08:20 -05006115 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01006116 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6117 NULL);
6118 if (backing_file_full_ret) {
6119 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6120 g_free(backing_file_full_ret);
6121 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006122 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05006123 break;
6124 }
Jeff Cody418661e2017-01-25 20:08:20 -05006125 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006126 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04006127 /* If not an absolute filename path, make it relative to the current
6128 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01006129 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6130 NULL);
6131 /* We are going to compare canonicalized absolute pathnames */
6132 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6133 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006134 continue;
6135 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006136 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006137
6138 /* We need to make sure the backing filename we are comparing against
6139 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01006140 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6141 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6142 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006143 continue;
6144 }
Max Reitz2d9158c2019-02-01 20:29:17 +01006145 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006146
6147 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02006148 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04006149 break;
6150 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006151 }
6152 }
6153
Jeff Codyb1b1d782012-10-16 15:49:09 -04006154 g_free(filename_full);
6155 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04006156 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00006157}
6158
bellardea2384d2004-08-01 21:59:26 +00006159void bdrv_init(void)
6160{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05006161 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00006162}
pbrookce1a14d2006-08-07 02:38:06 +00006163
Markus Armbrustereb852012009-10-27 18:41:44 +01006164void bdrv_init_with_whitelist(void)
6165{
6166 use_bdrv_whitelist = 1;
6167 bdrv_init();
6168}
6169
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03006170int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006171{
Kevin Wolf4417ab72017-05-04 18:52:37 +02006172 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006173 Error *local_err = NULL;
6174 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006175 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006176
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006177 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006178 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06006179 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006180
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03006181 QLIST_FOREACH(child, &bs->children, next) {
Paolo Bonzini2b148f32018-03-01 17:36:18 +01006182 bdrv_co_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006183 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006184 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006185 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006186 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006187 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006188
Kevin Wolfdafe0962017-11-16 13:00:01 +01006189 /*
6190 * Update permissions, they may differ for inactive nodes.
6191 *
6192 * Note that the required permissions of inactive images are always a
6193 * subset of the permissions required after activating the image. This
6194 * allows us to just get the permissions upfront without restricting
6195 * drv->bdrv_invalidate_cache().
6196 *
6197 * It also means that in error cases, we don't have to try and revert to
6198 * the old permissions (which is an operation that could fail, too). We can
6199 * just keep the extended permissions for the next time that an activation
6200 * of the image is tried.
6201 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01006202 if (bs->open_flags & BDRV_O_INACTIVE) {
6203 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006204 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01006205 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006206 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006207 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08006208 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01006209
Kevin Wolf7bb49412019-12-17 15:06:38 +01006210 if (bs->drv->bdrv_co_invalidate_cache) {
6211 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6212 if (local_err) {
6213 bs->open_flags |= BDRV_O_INACTIVE;
6214 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006215 return -EINVAL;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006216 }
6217 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04006218
Kevin Wolf7bb49412019-12-17 15:06:38 +01006219 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6220 bdrv_dirty_bitmap_skip_store(bm, false);
6221 }
6222
6223 ret = refresh_total_sectors(bs, bs->total_sectors);
6224 if (ret < 0) {
6225 bs->open_flags |= BDRV_O_INACTIVE;
6226 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006227 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01006228 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006229 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02006230
6231 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006232 if (parent->klass->activate) {
6233 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02006234 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01006235 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006236 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006237 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02006238 }
6239 }
6240 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006241
6242 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06006243}
6244
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006245void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06006246{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01006247 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006248 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06006249
Kevin Wolf88be7b42016-05-20 18:49:07 +02006250 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006251 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006252 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006253
6254 aio_context_acquire(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006255 ret = bdrv_invalidate_cache(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006256 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006257 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006258 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006259 return;
6260 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006261 }
6262}
6263
Kevin Wolf9e372712018-11-23 15:11:14 +01006264static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6265{
6266 BdrvChild *parent;
6267
6268 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006269 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006270 BlockDriverState *parent_bs = parent->opaque;
6271 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6272 return true;
6273 }
6274 }
6275 }
6276
6277 return false;
6278}
6279
6280static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006281{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006282 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006283 int ret;
6284
Max Reitzd470ad42017-11-10 21:31:09 +01006285 if (!bs->drv) {
6286 return -ENOMEDIUM;
6287 }
6288
Kevin Wolf9e372712018-11-23 15:11:14 +01006289 /* Make sure that we don't inactivate a child before its parent.
6290 * It will be covered by recursion from the yet active parent. */
6291 if (bdrv_has_bds_parent(bs, true)) {
6292 return 0;
6293 }
6294
6295 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6296
6297 /* Inactivate this node */
6298 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006299 ret = bs->drv->bdrv_inactivate(bs);
6300 if (ret < 0) {
6301 return ret;
6302 }
6303 }
6304
Kevin Wolf9e372712018-11-23 15:11:14 +01006305 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006306 if (parent->klass->inactivate) {
6307 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006308 if (ret < 0) {
6309 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006310 }
6311 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006312 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006313
Kevin Wolf9e372712018-11-23 15:11:14 +01006314 bs->open_flags |= BDRV_O_INACTIVE;
6315
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006316 /*
6317 * Update permissions, they may differ for inactive nodes.
6318 * We only tried to loosen restrictions, so errors are not fatal, ignore
6319 * them.
6320 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006321 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006322
6323 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006324 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006325 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006326 if (ret < 0) {
6327 return ret;
6328 }
6329 }
6330
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006331 return 0;
6332}
6333
6334int bdrv_inactivate_all(void)
6335{
Max Reitz79720af2016-03-16 19:54:44 +01006336 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006337 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006338 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006339 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006340
Kevin Wolf88be7b42016-05-20 18:49:07 +02006341 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006342 AioContext *aio_context = bdrv_get_aio_context(bs);
6343
6344 if (!g_slist_find(aio_ctxs, aio_context)) {
6345 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6346 aio_context_acquire(aio_context);
6347 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006348 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006349
Kevin Wolf9e372712018-11-23 15:11:14 +01006350 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6351 /* Nodes with BDS parents are covered by recursion from the last
6352 * parent that gets inactivated. Don't inactivate them a second
6353 * time if that has already happened. */
6354 if (bdrv_has_bds_parent(bs, false)) {
6355 continue;
6356 }
6357 ret = bdrv_inactivate_recurse(bs);
6358 if (ret < 0) {
6359 bdrv_next_cleanup(&it);
6360 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006361 }
6362 }
6363
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006364out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006365 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6366 AioContext *aio_context = ctx->data;
6367 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006368 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006369 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006370
6371 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006372}
6373
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006374/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006375/* removable device support */
6376
6377/**
6378 * Return TRUE if the media is present
6379 */
Max Reitze031f752015-10-19 17:53:11 +02006380bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006381{
6382 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006383 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006384
Max Reitze031f752015-10-19 17:53:11 +02006385 if (!drv) {
6386 return false;
6387 }
Max Reitz28d7a782015-10-19 17:53:13 +02006388 if (drv->bdrv_is_inserted) {
6389 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006390 }
Max Reitz28d7a782015-10-19 17:53:13 +02006391 QLIST_FOREACH(child, &bs->children, next) {
6392 if (!bdrv_is_inserted(child->bs)) {
6393 return false;
6394 }
6395 }
6396 return true;
bellard19cb3732006-08-19 11:45:59 +00006397}
6398
6399/**
bellard19cb3732006-08-19 11:45:59 +00006400 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6401 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006402void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006403{
6404 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006405
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006406 if (drv && drv->bdrv_eject) {
6407 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006408 }
bellard19cb3732006-08-19 11:45:59 +00006409}
6410
bellard19cb3732006-08-19 11:45:59 +00006411/**
6412 * Lock or unlock the media (if it is locked, the user won't be able
6413 * to eject it manually).
6414 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006415void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006416{
6417 BlockDriver *drv = bs->drv;
6418
Markus Armbruster025e8492011-09-06 18:58:47 +02006419 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006420
Markus Armbruster025e8492011-09-06 18:58:47 +02006421 if (drv && drv->bdrv_lock_medium) {
6422 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006423 }
6424}
ths985a03b2007-12-24 16:10:43 +00006425
Fam Zheng9fcb0252013-08-23 09:14:46 +08006426/* Get a reference to bs */
6427void bdrv_ref(BlockDriverState *bs)
6428{
6429 bs->refcnt++;
6430}
6431
6432/* Release a previously grabbed reference to bs.
6433 * If after releasing, reference count is zero, the BlockDriverState is
6434 * deleted. */
6435void bdrv_unref(BlockDriverState *bs)
6436{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006437 if (!bs) {
6438 return;
6439 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006440 assert(bs->refcnt > 0);
6441 if (--bs->refcnt == 0) {
6442 bdrv_delete(bs);
6443 }
6444}
6445
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006446struct BdrvOpBlocker {
6447 Error *reason;
6448 QLIST_ENTRY(BdrvOpBlocker) list;
6449};
6450
6451bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6452{
6453 BdrvOpBlocker *blocker;
6454 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6455 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6456 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006457 error_propagate_prepend(errp, error_copy(blocker->reason),
6458 "Node '%s' is busy: ",
6459 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006460 return true;
6461 }
6462 return false;
6463}
6464
6465void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6466{
6467 BdrvOpBlocker *blocker;
6468 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6469
Markus Armbruster5839e532014-08-19 10:31:08 +02006470 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006471 blocker->reason = reason;
6472 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6473}
6474
6475void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6476{
6477 BdrvOpBlocker *blocker, *next;
6478 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6479 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6480 if (blocker->reason == reason) {
6481 QLIST_REMOVE(blocker, list);
6482 g_free(blocker);
6483 }
6484 }
6485}
6486
6487void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6488{
6489 int i;
6490 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6491 bdrv_op_block(bs, i, reason);
6492 }
6493}
6494
6495void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6496{
6497 int i;
6498 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6499 bdrv_op_unblock(bs, i, reason);
6500 }
6501}
6502
6503bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6504{
6505 int i;
6506
6507 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6508 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6509 return false;
6510 }
6511 }
6512 return true;
6513}
6514
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006515void bdrv_img_create(const char *filename, const char *fmt,
6516 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006517 char *options, uint64_t img_size, int flags, bool quiet,
6518 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006519{
Chunyan Liu83d05212014-06-05 17:20:51 +08006520 QemuOptsList *create_opts = NULL;
6521 QemuOpts *opts = NULL;
6522 const char *backing_fmt, *backing_file;
6523 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006524 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006525 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006526 int ret = 0;
6527
6528 /* Find driver and parse its options */
6529 drv = bdrv_find_format(fmt);
6530 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006531 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006532 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006533 }
6534
Max Reitzb65a5e12015-02-05 13:58:12 -05006535 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006536 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006537 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006538 }
6539
Max Reitzc6149722014-12-02 18:32:45 +01006540 if (!drv->create_opts) {
6541 error_setg(errp, "Format driver '%s' does not support image creation",
6542 drv->format_name);
6543 return;
6544 }
6545
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006546 if (!proto_drv->create_opts) {
6547 error_setg(errp, "Protocol driver '%s' does not support image creation",
6548 proto_drv->format_name);
6549 return;
6550 }
6551
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006552 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006553 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006554 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006555
Chunyan Liu83d05212014-06-05 17:20:51 +08006556 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006557
6558 /* Parse -o options */
6559 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006560 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006561 goto out;
6562 }
6563 }
6564
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006565 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6566 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6567 } else if (img_size != UINT64_C(-1)) {
6568 error_setg(errp, "The image size must be specified only once");
6569 goto out;
6570 }
6571
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006572 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006573 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006574 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006575 error_setg(errp, "Backing file not supported for file format '%s'",
6576 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006577 goto out;
6578 }
6579 }
6580
6581 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006582 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006583 error_setg(errp, "Backing file format not supported for file "
6584 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006585 goto out;
6586 }
6587 }
6588
Chunyan Liu83d05212014-06-05 17:20:51 +08006589 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6590 if (backing_file) {
6591 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006592 error_setg(errp, "Error: Trying to create an image with the "
6593 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006594 goto out;
6595 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006596 if (backing_file[0] == '\0') {
6597 error_setg(errp, "Expected backing file name, got empty string");
6598 goto out;
6599 }
Jes Sorensen792da932010-12-16 13:52:17 +01006600 }
6601
Chunyan Liu83d05212014-06-05 17:20:51 +08006602 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006603
John Snow6e6e55f2017-07-17 20:34:22 -04006604 /* The size for the image must always be specified, unless we have a backing
6605 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006606 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006607 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6608 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006609 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006610 int back_flags;
6611 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006612
Max Reitz645ae7d2019-02-01 20:29:14 +01006613 full_backing =
6614 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6615 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006616 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006617 goto out;
6618 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006619 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006620
6621 /* backing files always opened read-only */
6622 back_flags = flags;
6623 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6624
Fam Zhengcc954f02017-12-15 16:04:45 +08006625 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006626 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006627 qdict_put_str(backing_options, "driver", backing_fmt);
6628 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006629 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006630
6631 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6632 &local_err);
6633 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006634 if (!bs) {
6635 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006636 goto out;
6637 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006638 if (!backing_fmt) {
6639 warn_report("Deprecated use of backing file without explicit "
6640 "backing format (detected format of %s)",
6641 bs->drv->format_name);
6642 if (bs->drv != &bdrv_raw) {
6643 /*
6644 * A probe of raw deserves the most attention:
6645 * leaving the backing format out of the image
6646 * will ensure bs->probed is set (ensuring we
6647 * don't accidentally commit into the backing
6648 * file), and allow more spots to warn the users
6649 * to fix their toolchain when opening this image
6650 * later. For other images, we can safely record
6651 * the format that we probed.
6652 */
6653 backing_fmt = bs->drv->format_name;
6654 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
6655 NULL);
6656 }
6657 }
John Snow6e6e55f2017-07-17 20:34:22 -04006658 if (size == -1) {
6659 /* Opened BS, have no size */
6660 size = bdrv_getlength(bs);
6661 if (size < 0) {
6662 error_setg_errno(errp, -size, "Could not get size of '%s'",
6663 backing_file);
6664 bdrv_unref(bs);
6665 goto out;
6666 }
6667 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6668 }
6669 bdrv_unref(bs);
6670 }
Eric Blaked9f059a2020-07-06 15:39:54 -05006671 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6672 } else if (backing_file && !backing_fmt) {
6673 warn_report("Deprecated use of unopened backing file without "
6674 "explicit backing format, use of this image requires "
6675 "potentially unsafe format probing");
6676 }
John Snow6e6e55f2017-07-17 20:34:22 -04006677
6678 if (size == -1) {
6679 error_setg(errp, "Image creation needs a size parameter");
6680 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006681 }
6682
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006683 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02006684 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08006685 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006686 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05006687 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006688 }
Chunyan Liu83d05212014-06-05 17:20:51 +08006689
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006690 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08006691
Max Reitzcc84d902013-09-06 17:14:26 +02006692 if (ret == -EFBIG) {
6693 /* This is generally a better message than whatever the driver would
6694 * deliver (especially because of the cluster_size_hint), since that
6695 * is most probably not much different from "image too large". */
6696 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08006697 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02006698 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006699 }
Max Reitzcc84d902013-09-06 17:14:26 +02006700 error_setg(errp, "The image size is too large for file format '%s'"
6701 "%s", fmt, cluster_size_hint);
6702 error_free(local_err);
6703 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006704 }
6705
6706out:
Chunyan Liu83d05212014-06-05 17:20:51 +08006707 qemu_opts_del(opts);
6708 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03006709 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006710}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006711
6712AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6713{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00006714 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006715}
6716
Kevin Wolfe336fd42020-10-05 17:58:53 +02006717AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6718{
6719 Coroutine *self = qemu_coroutine_self();
6720 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6721 AioContext *new_ctx;
6722
6723 /*
6724 * Increase bs->in_flight to ensure that this operation is completed before
6725 * moving the node to a different AioContext. Read new_ctx only afterwards.
6726 */
6727 bdrv_inc_in_flight(bs);
6728
6729 new_ctx = bdrv_get_aio_context(bs);
6730 aio_co_reschedule_self(new_ctx);
6731 return old_ctx;
6732}
6733
6734void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6735{
6736 aio_co_reschedule_self(old_ctx);
6737 bdrv_dec_in_flight(bs);
6738}
6739
Kevin Wolf18c6ac12020-10-05 17:58:54 +02006740void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6741{
6742 AioContext *ctx = bdrv_get_aio_context(bs);
6743
6744 /* In the main thread, bs->aio_context won't change concurrently */
6745 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6746
6747 /*
6748 * We're in coroutine context, so we already hold the lock of the main
6749 * loop AioContext. Don't lock it twice to avoid deadlocks.
6750 */
6751 assert(qemu_in_coroutine());
6752 if (ctx != qemu_get_aio_context()) {
6753 aio_context_acquire(ctx);
6754 }
6755}
6756
6757void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6758{
6759 AioContext *ctx = bdrv_get_aio_context(bs);
6760
6761 assert(qemu_in_coroutine());
6762 if (ctx != qemu_get_aio_context()) {
6763 aio_context_release(ctx);
6764 }
6765}
6766
Fam Zheng052a7572017-04-10 20:09:25 +08006767void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6768{
6769 aio_co_enter(bdrv_get_aio_context(bs), co);
6770}
6771
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006772static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6773{
6774 QLIST_REMOVE(ban, list);
6775 g_free(ban);
6776}
6777
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006778static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006779{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006780 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006781
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006782 assert(!bs->walking_aio_notifiers);
6783 bs->walking_aio_notifiers = true;
6784 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6785 if (baf->deleted) {
6786 bdrv_do_remove_aio_context_notifier(baf);
6787 } else {
6788 baf->detach_aio_context(baf->opaque);
6789 }
Max Reitz33384422014-06-20 21:57:33 +02006790 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006791 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6792 * remove remaining aio notifiers if we aren't called again.
6793 */
6794 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02006795
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006796 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006797 bs->drv->bdrv_detach_aio_context(bs);
6798 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006799
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006800 if (bs->quiesce_counter) {
6801 aio_enable_external(bs->aio_context);
6802 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006803 bs->aio_context = NULL;
6804}
6805
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006806static void bdrv_attach_aio_context(BlockDriverState *bs,
6807 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006808{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006809 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006810
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006811 if (bs->quiesce_counter) {
6812 aio_disable_external(new_context);
6813 }
6814
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006815 bs->aio_context = new_context;
6816
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006817 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006818 bs->drv->bdrv_attach_aio_context(bs, new_context);
6819 }
Max Reitz33384422014-06-20 21:57:33 +02006820
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006821 assert(!bs->walking_aio_notifiers);
6822 bs->walking_aio_notifiers = true;
6823 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6824 if (ban->deleted) {
6825 bdrv_do_remove_aio_context_notifier(ban);
6826 } else {
6827 ban->attached_aio_context(new_context, ban->opaque);
6828 }
Max Reitz33384422014-06-20 21:57:33 +02006829 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006830 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006831}
6832
Kevin Wolf42a65f02019-05-07 18:31:38 +02006833/*
6834 * Changes the AioContext used for fd handlers, timers, and BHs by this
6835 * BlockDriverState and all its children and parents.
6836 *
Max Reitz43eaaae2019-07-22 15:30:54 +02006837 * Must be called from the main AioContext.
6838 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02006839 * The caller must own the AioContext lock for the old AioContext of bs, but it
6840 * must not own the AioContext lock for new_context (unless new_context is the
6841 * same as the current context of bs).
6842 *
6843 * @ignore will accumulate all visited BdrvChild object. The caller is
6844 * responsible for freeing the list afterwards.
6845 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02006846void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6847 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006848{
Max Reitze037c092019-07-19 11:26:14 +02006849 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006850 GSList *children_to_process = NULL;
6851 GSList *parents_to_process = NULL;
6852 GSList *entry;
6853 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02006854
Max Reitz43eaaae2019-07-22 15:30:54 +02006855 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6856
Max Reitze037c092019-07-19 11:26:14 +02006857 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03006858 return;
6859 }
6860
Kevin Wolfd70d5952019-02-08 16:53:37 +01006861 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02006862
6863 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006864 if (g_slist_find(*ignore, child)) {
6865 continue;
6866 }
6867 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006868 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02006869 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006870
6871 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6872 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006873 continue;
6874 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006875 *ignore = g_slist_prepend(*ignore, parent);
6876 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02006877 }
6878
Sergio Lopez722d8e72021-02-01 13:50:31 +01006879 for (entry = children_to_process;
6880 entry != NULL;
6881 entry = g_slist_next(entry)) {
6882 child = entry->data;
6883 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6884 }
6885 g_slist_free(children_to_process);
6886
6887 for (entry = parents_to_process;
6888 entry != NULL;
6889 entry = g_slist_next(entry)) {
6890 parent = entry->data;
6891 assert(parent->klass->set_aio_ctx);
6892 parent->klass->set_aio_ctx(parent, new_context, ignore);
6893 }
6894 g_slist_free(parents_to_process);
6895
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006896 bdrv_detach_aio_context(bs);
6897
Max Reitze037c092019-07-19 11:26:14 +02006898 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02006899 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006900 aio_context_acquire(new_context);
6901 }
6902
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006903 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02006904
6905 /*
6906 * If this function was recursively called from
6907 * bdrv_set_aio_context_ignore(), there may be nodes in the
6908 * subtree that have not yet been moved to the new AioContext.
6909 * Release the old one so bdrv_drained_end() can poll them.
6910 */
Max Reitz43eaaae2019-07-22 15:30:54 +02006911 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006912 aio_context_release(old_context);
6913 }
6914
Kevin Wolfd70d5952019-02-08 16:53:37 +01006915 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02006916
Max Reitz43eaaae2019-07-22 15:30:54 +02006917 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006918 aio_context_acquire(old_context);
6919 }
Max Reitz43eaaae2019-07-22 15:30:54 +02006920 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006921 aio_context_release(new_context);
6922 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006923}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02006924
Kevin Wolf5d231842019-05-06 19:17:56 +02006925static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6926 GSList **ignore, Error **errp)
6927{
6928 if (g_slist_find(*ignore, c)) {
6929 return true;
6930 }
6931 *ignore = g_slist_prepend(*ignore, c);
6932
Max Reitzbd86fb92020-05-13 13:05:13 +02006933 /*
6934 * A BdrvChildClass that doesn't handle AioContext changes cannot
6935 * tolerate any AioContext changes
6936 */
6937 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006938 char *user = bdrv_child_user_desc(c);
6939 error_setg(errp, "Changing iothreads is not supported by %s", user);
6940 g_free(user);
6941 return false;
6942 }
Max Reitzbd86fb92020-05-13 13:05:13 +02006943 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006944 assert(!errp || *errp);
6945 return false;
6946 }
6947 return true;
6948}
6949
6950bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6951 GSList **ignore, Error **errp)
6952{
6953 if (g_slist_find(*ignore, c)) {
6954 return true;
6955 }
6956 *ignore = g_slist_prepend(*ignore, c);
6957 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6958}
6959
6960/* @ignore will accumulate all visited BdrvChild object. The caller is
6961 * responsible for freeing the list afterwards. */
6962bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6963 GSList **ignore, Error **errp)
6964{
6965 BdrvChild *c;
6966
6967 if (bdrv_get_aio_context(bs) == ctx) {
6968 return true;
6969 }
6970
6971 QLIST_FOREACH(c, &bs->parents, next_parent) {
6972 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6973 return false;
6974 }
6975 }
6976 QLIST_FOREACH(c, &bs->children, next) {
6977 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6978 return false;
6979 }
6980 }
6981
6982 return true;
6983}
6984
6985int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6986 BdrvChild *ignore_child, Error **errp)
6987{
6988 GSList *ignore;
6989 bool ret;
6990
6991 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6992 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6993 g_slist_free(ignore);
6994
6995 if (!ret) {
6996 return -EPERM;
6997 }
6998
Kevin Wolf53a7d042019-05-06 19:17:59 +02006999 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7000 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7001 g_slist_free(ignore);
7002
Kevin Wolf5d231842019-05-06 19:17:56 +02007003 return 0;
7004}
7005
7006int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7007 Error **errp)
7008{
7009 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7010}
7011
Max Reitz33384422014-06-20 21:57:33 +02007012void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7013 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7014 void (*detach_aio_context)(void *opaque), void *opaque)
7015{
7016 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7017 *ban = (BdrvAioNotifier){
7018 .attached_aio_context = attached_aio_context,
7019 .detach_aio_context = detach_aio_context,
7020 .opaque = opaque
7021 };
7022
7023 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7024}
7025
7026void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7027 void (*attached_aio_context)(AioContext *,
7028 void *),
7029 void (*detach_aio_context)(void *),
7030 void *opaque)
7031{
7032 BdrvAioNotifier *ban, *ban_next;
7033
7034 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7035 if (ban->attached_aio_context == attached_aio_context &&
7036 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007037 ban->opaque == opaque &&
7038 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02007039 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01007040 if (bs->walking_aio_notifiers) {
7041 ban->deleted = true;
7042 } else {
7043 bdrv_do_remove_aio_context_notifier(ban);
7044 }
Max Reitz33384422014-06-20 21:57:33 +02007045 return;
7046 }
7047 }
7048
7049 abort();
7050}
7051
Max Reitz77485432014-10-27 11:12:50 +01007052int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02007053 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007054 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02007055 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02007056{
Max Reitzd470ad42017-11-10 21:31:09 +01007057 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02007058 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01007059 return -ENOMEDIUM;
7060 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08007061 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02007062 error_setg(errp, "Block driver '%s' does not support option amendment",
7063 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02007064 return -ENOTSUP;
7065 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02007066 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7067 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02007068}
Benoît Canetf6186f42013-10-02 14:33:48 +02007069
Max Reitz5d69b5a2020-02-18 11:34:41 +01007070/*
7071 * This function checks whether the given @to_replace is allowed to be
7072 * replaced by a node that always shows the same data as @bs. This is
7073 * used for example to verify whether the mirror job can replace
7074 * @to_replace by the target mirrored from @bs.
7075 * To be replaceable, @bs and @to_replace may either be guaranteed to
7076 * always show the same data (because they are only connected through
7077 * filters), or some driver may allow replacing one of its children
7078 * because it can guarantee that this child's data is not visible at
7079 * all (for example, for dissenting quorum children that have no other
7080 * parents).
7081 */
7082bool bdrv_recurse_can_replace(BlockDriverState *bs,
7083 BlockDriverState *to_replace)
7084{
Max Reitz93393e62019-06-12 17:03:38 +02007085 BlockDriverState *filtered;
7086
Max Reitz5d69b5a2020-02-18 11:34:41 +01007087 if (!bs || !bs->drv) {
7088 return false;
7089 }
7090
7091 if (bs == to_replace) {
7092 return true;
7093 }
7094
7095 /* See what the driver can do */
7096 if (bs->drv->bdrv_recurse_can_replace) {
7097 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7098 }
7099
7100 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02007101 filtered = bdrv_filter_bs(bs);
7102 if (filtered) {
7103 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01007104 }
7105
7106 /* Safe default */
7107 return false;
7108}
7109
Max Reitz810803a2020-02-18 11:34:44 +01007110/*
7111 * Check whether the given @node_name can be replaced by a node that
7112 * has the same data as @parent_bs. If so, return @node_name's BDS;
7113 * NULL otherwise.
7114 *
7115 * @node_name must be a (recursive) *child of @parent_bs (or this
7116 * function will return NULL).
7117 *
7118 * The result (whether the node can be replaced or not) is only valid
7119 * for as long as no graph or permission changes occur.
7120 */
Wen Congyange12f3782015-07-17 10:12:22 +08007121BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7122 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02007123{
7124 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007125 AioContext *aio_context;
7126
Benoît Canet09158f02014-06-27 18:25:25 +02007127 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06007128 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02007129 return NULL;
7130 }
7131
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007132 aio_context = bdrv_get_aio_context(to_replace_bs);
7133 aio_context_acquire(aio_context);
7134
Benoît Canet09158f02014-06-27 18:25:25 +02007135 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007136 to_replace_bs = NULL;
7137 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007138 }
7139
7140 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7141 * most non filter in order to prevent data corruption.
7142 * Another benefit is that this tests exclude backing files which are
7143 * blocked by the backing blockers.
7144 */
Max Reitz810803a2020-02-18 11:34:44 +01007145 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7146 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7147 "because it cannot be guaranteed that doing so would not "
7148 "lead to an abrupt change of visible data",
7149 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007150 to_replace_bs = NULL;
7151 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02007152 }
7153
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01007154out:
7155 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02007156 return to_replace_bs;
7157}
Ming Lei448ad912014-07-04 18:04:33 +08007158
Max Reitz97e2f022019-02-01 20:29:27 +01007159/**
7160 * Iterates through the list of runtime option keys that are said to
7161 * be "strong" for a BDS. An option is called "strong" if it changes
7162 * a BDS's data. For example, the null block driver's "size" and
7163 * "read-zeroes" options are strong, but its "latency-ns" option is
7164 * not.
7165 *
7166 * If a key returned by this function ends with a dot, all options
7167 * starting with that prefix are strong.
7168 */
7169static const char *const *strong_options(BlockDriverState *bs,
7170 const char *const *curopt)
7171{
7172 static const char *const global_options[] = {
7173 "driver", "filename", NULL
7174 };
7175
7176 if (!curopt) {
7177 return &global_options[0];
7178 }
7179
7180 curopt++;
7181 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7182 curopt = bs->drv->strong_runtime_opts;
7183 }
7184
7185 return (curopt && *curopt) ? curopt : NULL;
7186}
7187
7188/**
7189 * Copies all strong runtime options from bs->options to the given
7190 * QDict. The set of strong option keys is determined by invoking
7191 * strong_options().
7192 *
7193 * Returns true iff any strong option was present in bs->options (and
7194 * thus copied to the target QDict) with the exception of "filename"
7195 * and "driver". The caller is expected to use this value to decide
7196 * whether the existence of strong options prevents the generation of
7197 * a plain filename.
7198 */
7199static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7200{
7201 bool found_any = false;
7202 const char *const *option_name = NULL;
7203
7204 if (!bs->drv) {
7205 return false;
7206 }
7207
7208 while ((option_name = strong_options(bs, option_name))) {
7209 bool option_given = false;
7210
7211 assert(strlen(*option_name) > 0);
7212 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7213 QObject *entry = qdict_get(bs->options, *option_name);
7214 if (!entry) {
7215 continue;
7216 }
7217
7218 qdict_put_obj(d, *option_name, qobject_ref(entry));
7219 option_given = true;
7220 } else {
7221 const QDictEntry *entry;
7222 for (entry = qdict_first(bs->options); entry;
7223 entry = qdict_next(bs->options, entry))
7224 {
7225 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7226 qdict_put_obj(d, qdict_entry_key(entry),
7227 qobject_ref(qdict_entry_value(entry)));
7228 option_given = true;
7229 }
7230 }
7231 }
7232
7233 /* While "driver" and "filename" need to be included in a JSON filename,
7234 * their existence does not prohibit generation of a plain filename. */
7235 if (!found_any && option_given &&
7236 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7237 {
7238 found_any = true;
7239 }
7240 }
7241
Max Reitz62a01a272019-02-01 20:29:34 +01007242 if (!qdict_haskey(d, "driver")) {
7243 /* Drivers created with bdrv_new_open_driver() may not have a
7244 * @driver option. Add it here. */
7245 qdict_put_str(d, "driver", bs->drv->format_name);
7246 }
7247
Max Reitz97e2f022019-02-01 20:29:27 +01007248 return found_any;
7249}
7250
Max Reitz90993622019-02-01 20:29:09 +01007251/* Note: This function may return false positives; it may return true
7252 * even if opening the backing file specified by bs's image header
7253 * would result in exactly bs->backing. */
Max Reitz0b877d02018-08-01 20:34:11 +02007254bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01007255{
7256 if (bs->backing) {
7257 return strcmp(bs->auto_backing_file,
7258 bs->backing->bs->filename);
7259 } else {
7260 /* No backing BDS, so if the image header reports any backing
7261 * file, it must have been suppressed */
7262 return bs->auto_backing_file[0] != '\0';
7263 }
7264}
7265
Max Reitz91af7012014-07-18 20:24:56 +02007266/* Updates the following BDS fields:
7267 * - exact_filename: A filename which may be used for opening a block device
7268 * which (mostly) equals the given BDS (even without any
7269 * other options; so reading and writing must return the same
7270 * results, but caching etc. may be different)
7271 * - full_open_options: Options which, when given when opening a block device
7272 * (without a filename), result in a BDS (mostly)
7273 * equalling the given one
7274 * - filename: If exact_filename is set, it is copied here. Otherwise,
7275 * full_open_options is converted to a JSON object, prefixed with
7276 * "json:" (for use through the JSON pseudo protocol) and put here.
7277 */
7278void bdrv_refresh_filename(BlockDriverState *bs)
7279{
7280 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007281 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007282 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007283 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007284 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007285 bool generate_json_filename; /* Whether our default implementation should
7286 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007287
7288 if (!drv) {
7289 return;
7290 }
7291
Max Reitze24518e2019-02-01 20:29:06 +01007292 /* This BDS's file name may depend on any of its children's file names, so
7293 * refresh those first */
7294 QLIST_FOREACH(child, &bs->children, next) {
7295 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007296 }
7297
Max Reitzbb808d52019-02-01 20:29:07 +01007298 if (bs->implicit) {
7299 /* For implicit nodes, just copy everything from the single child */
7300 child = QLIST_FIRST(&bs->children);
7301 assert(QLIST_NEXT(child, next) == NULL);
7302
7303 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7304 child->bs->exact_filename);
7305 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7306
Pan Nengyuancb895612020-01-16 16:56:00 +08007307 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007308 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7309
7310 return;
7311 }
7312
Max Reitz90993622019-02-01 20:29:09 +01007313 backing_overridden = bdrv_backing_overridden(bs);
7314
7315 if (bs->open_flags & BDRV_O_NO_IO) {
7316 /* Without I/O, the backing file does not change anything.
7317 * Therefore, in such a case (primarily qemu-img), we can
7318 * pretend the backing file has not been overridden even if
7319 * it technically has been. */
7320 backing_overridden = false;
7321 }
7322
Max Reitz97e2f022019-02-01 20:29:27 +01007323 /* Gather the options QDict */
7324 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007325 generate_json_filename = append_strong_runtime_options(opts, bs);
7326 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007327
7328 if (drv->bdrv_gather_child_options) {
7329 /* Some block drivers may not want to present all of their children's
7330 * options, or name them differently from BdrvChild.name */
7331 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7332 } else {
7333 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007334 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007335 /* We can skip the backing BDS if it has not been overridden */
7336 continue;
7337 }
7338
7339 qdict_put(opts, child->name,
7340 qobject_ref(child->bs->full_open_options));
7341 }
7342
7343 if (backing_overridden && !bs->backing) {
7344 /* Force no backing file */
7345 qdict_put_null(opts, "backing");
7346 }
7347 }
7348
7349 qobject_unref(bs->full_open_options);
7350 bs->full_open_options = opts;
7351
Max Reitz52f72d62019-06-12 17:43:03 +02007352 primary_child_bs = bdrv_primary_bs(bs);
7353
Max Reitz998b3a12019-02-01 20:29:28 +01007354 if (drv->bdrv_refresh_filename) {
7355 /* Obsolete information is of no use here, so drop the old file name
7356 * information before refreshing it */
7357 bs->exact_filename[0] = '\0';
7358
7359 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007360 } else if (primary_child_bs) {
7361 /*
7362 * Try to reconstruct valid information from the underlying
7363 * file -- this only works for format nodes (filter nodes
7364 * cannot be probed and as such must be selected by the user
7365 * either through an options dict, or through a special
7366 * filename which the filter driver must construct in its
7367 * .bdrv_refresh_filename() implementation).
7368 */
Max Reitz998b3a12019-02-01 20:29:28 +01007369
7370 bs->exact_filename[0] = '\0';
7371
Max Reitzfb695c72019-02-01 20:29:29 +01007372 /*
7373 * We can use the underlying file's filename if:
7374 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007375 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007376 * - the file is a protocol BDS, and
7377 * - opening that file (as this BDS's format) will automatically create
7378 * the BDS tree we have right now, that is:
7379 * - the user did not significantly change this BDS's behavior with
7380 * some explicit (strong) options
7381 * - no non-file child of this BDS has been overridden by the user
7382 * Both of these conditions are represented by generate_json_filename.
7383 */
Max Reitz52f72d62019-06-12 17:43:03 +02007384 if (primary_child_bs->exact_filename[0] &&
7385 primary_child_bs->drv->bdrv_file_open &&
7386 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007387 {
Max Reitz52f72d62019-06-12 17:43:03 +02007388 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007389 }
7390 }
7391
Max Reitz91af7012014-07-18 20:24:56 +02007392 if (bs->exact_filename[0]) {
7393 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007394 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007395 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007396 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007397 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007398 /* Give user a hint if we truncated things. */
7399 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7400 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007401 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007402 }
7403}
Wen Congyange06018a2016-05-10 15:36:37 +08007404
Max Reitz1e89d0f2019-02-01 20:29:18 +01007405char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7406{
7407 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007408 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007409
7410 if (!drv) {
7411 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7412 return NULL;
7413 }
7414
7415 if (drv->bdrv_dirname) {
7416 return drv->bdrv_dirname(bs, errp);
7417 }
7418
Max Reitz52f72d62019-06-12 17:43:03 +02007419 child_bs = bdrv_primary_bs(bs);
7420 if (child_bs) {
7421 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007422 }
7423
7424 bdrv_refresh_filename(bs);
7425 if (bs->exact_filename[0] != '\0') {
7426 return path_combine(bs->exact_filename, "");
7427 }
7428
7429 error_setg(errp, "Cannot generate a base directory for %s nodes",
7430 drv->format_name);
7431 return NULL;
7432}
7433
Wen Congyange06018a2016-05-10 15:36:37 +08007434/*
7435 * Hot add/remove a BDS's child. So the user can take a child offline when
7436 * it is broken and take a new child online
7437 */
7438void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7439 Error **errp)
7440{
7441
7442 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7443 error_setg(errp, "The node %s does not support adding a child",
7444 bdrv_get_device_or_node_name(parent_bs));
7445 return;
7446 }
7447
7448 if (!QLIST_EMPTY(&child_bs->parents)) {
7449 error_setg(errp, "The node %s already has a parent",
7450 child_bs->node_name);
7451 return;
7452 }
7453
7454 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7455}
7456
7457void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7458{
7459 BdrvChild *tmp;
7460
7461 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7462 error_setg(errp, "The node %s does not support removing a child",
7463 bdrv_get_device_or_node_name(parent_bs));
7464 return;
7465 }
7466
7467 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7468 if (tmp == child) {
7469 break;
7470 }
7471 }
7472
7473 if (!tmp) {
7474 error_setg(errp, "The node %s does not have a child named %s",
7475 bdrv_get_device_or_node_name(parent_bs),
7476 bdrv_get_device_or_node_name(child->bs));
7477 return;
7478 }
7479
7480 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7481}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007482
7483int bdrv_make_empty(BdrvChild *c, Error **errp)
7484{
7485 BlockDriver *drv = c->bs->drv;
7486 int ret;
7487
7488 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7489
7490 if (!drv->bdrv_make_empty) {
7491 error_setg(errp, "%s does not support emptying nodes",
7492 drv->format_name);
7493 return -ENOTSUP;
7494 }
7495
7496 ret = drv->bdrv_make_empty(c->bs);
7497 if (ret < 0) {
7498 error_setg_errno(errp, -ret, "Failed to empty %s",
7499 c->bs->filename);
7500 return ret;
7501 }
7502
7503 return 0;
7504}
Max Reitz9a6fc882019-05-31 15:23:11 +02007505
7506/*
7507 * Return the child that @bs acts as an overlay for, and from which data may be
7508 * copied in COW or COR operations. Usually this is the backing file.
7509 */
7510BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7511{
7512 if (!bs || !bs->drv) {
7513 return NULL;
7514 }
7515
7516 if (bs->drv->is_filter) {
7517 return NULL;
7518 }
7519
7520 if (!bs->backing) {
7521 return NULL;
7522 }
7523
7524 assert(bs->backing->role & BDRV_CHILD_COW);
7525 return bs->backing;
7526}
7527
7528/*
7529 * If @bs acts as a filter for exactly one of its children, return
7530 * that child.
7531 */
7532BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7533{
7534 BdrvChild *c;
7535
7536 if (!bs || !bs->drv) {
7537 return NULL;
7538 }
7539
7540 if (!bs->drv->is_filter) {
7541 return NULL;
7542 }
7543
7544 /* Only one of @backing or @file may be used */
7545 assert(!(bs->backing && bs->file));
7546
7547 c = bs->backing ?: bs->file;
7548 if (!c) {
7549 return NULL;
7550 }
7551
7552 assert(c->role & BDRV_CHILD_FILTERED);
7553 return c;
7554}
7555
7556/*
7557 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7558 * whichever is non-NULL.
7559 *
7560 * Return NULL if both are NULL.
7561 */
7562BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7563{
7564 BdrvChild *cow_child = bdrv_cow_child(bs);
7565 BdrvChild *filter_child = bdrv_filter_child(bs);
7566
7567 /* Filter nodes cannot have COW backing files */
7568 assert(!(cow_child && filter_child));
7569
7570 return cow_child ?: filter_child;
7571}
7572
7573/*
7574 * Return the primary child of this node: For filters, that is the
7575 * filtered child. For other nodes, that is usually the child storing
7576 * metadata.
7577 * (A generally more helpful description is that this is (usually) the
7578 * child that has the same filename as @bs.)
7579 *
7580 * Drivers do not necessarily have a primary child; for example quorum
7581 * does not.
7582 */
7583BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7584{
7585 BdrvChild *c, *found = NULL;
7586
7587 QLIST_FOREACH(c, &bs->children, next) {
7588 if (c->role & BDRV_CHILD_PRIMARY) {
7589 assert(!found);
7590 found = c;
7591 }
7592 }
7593
7594 return found;
7595}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007596
7597static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7598 bool stop_on_explicit_filter)
7599{
7600 BdrvChild *c;
7601
7602 if (!bs) {
7603 return NULL;
7604 }
7605
7606 while (!(stop_on_explicit_filter && !bs->implicit)) {
7607 c = bdrv_filter_child(bs);
7608 if (!c) {
7609 /*
7610 * A filter that is embedded in a working block graph must
7611 * have a child. Assert this here so this function does
7612 * not return a filter node that is not expected by the
7613 * caller.
7614 */
7615 assert(!bs->drv || !bs->drv->is_filter);
7616 break;
7617 }
7618 bs = c->bs;
7619 }
7620 /*
7621 * Note that this treats nodes with bs->drv == NULL as not being
7622 * filters (bs->drv == NULL should be replaced by something else
7623 * anyway).
7624 * The advantage of this behavior is that this function will thus
7625 * always return a non-NULL value (given a non-NULL @bs).
7626 */
7627
7628 return bs;
7629}
7630
7631/*
7632 * Return the first BDS that has not been added implicitly or that
7633 * does not have a filtered child down the chain starting from @bs
7634 * (including @bs itself).
7635 */
7636BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7637{
7638 return bdrv_do_skip_filters(bs, true);
7639}
7640
7641/*
7642 * Return the first BDS that does not have a filtered child down the
7643 * chain starting from @bs (including @bs itself).
7644 */
7645BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7646{
7647 return bdrv_do_skip_filters(bs, false);
7648}
7649
7650/*
7651 * For a backing chain, return the first non-filter backing image of
7652 * the first non-filter image.
7653 */
7654BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7655{
7656 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7657}