blob: 0ee0c2f29aca743f4cca54d8eefbfd1ca24a8b28 [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-Ogievskiy53e96d12021-04-28 18:17:35 +030086static int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue
87 *queue, Error **errp);
88static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
89static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
90
Markus Armbrustereb852012009-10-27 18:41:44 +010091/* If non-zero, use only whitelisted block drivers */
92static int use_bdrv_whitelist;
93
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000094#ifdef _WIN32
95static int is_windows_drive_prefix(const char *filename)
96{
97 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
98 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
99 filename[1] == ':');
100}
101
102int is_windows_drive(const char *filename)
103{
104 if (is_windows_drive_prefix(filename) &&
105 filename[2] == '\0')
106 return 1;
107 if (strstart(filename, "\\\\.\\", NULL) ||
108 strstart(filename, "//./", NULL))
109 return 1;
110 return 0;
111}
112#endif
113
Kevin Wolf339064d2013-11-28 10:23:32 +0100114size_t bdrv_opt_mem_align(BlockDriverState *bs)
115{
116 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300117 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800118 return MAX(4096, qemu_real_host_page_size);
Kevin Wolf339064d2013-11-28 10:23:32 +0100119 }
120
121 return bs->bl.opt_mem_alignment;
122}
123
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300124size_t bdrv_min_mem_align(BlockDriverState *bs)
125{
126 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300127 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800128 return MAX(4096, qemu_real_host_page_size);
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300129 }
130
131 return bs->bl.min_mem_alignment;
132}
133
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000134/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100135int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000136{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200137 const char *p;
138
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000139#ifdef _WIN32
140 if (is_windows_drive(path) ||
141 is_windows_drive_prefix(path)) {
142 return 0;
143 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200144 p = path + strcspn(path, ":/\\");
145#else
146 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000147#endif
148
Paolo Bonzini947995c2012-05-08 16:51:48 +0200149 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000150}
151
bellard83f64092006-08-01 16:21:11 +0000152int path_is_absolute(const char *path)
153{
bellard21664422007-01-07 18:22:37 +0000154#ifdef _WIN32
155 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200156 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000157 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200158 }
159 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000160#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200161 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000162#endif
bellard83f64092006-08-01 16:21:11 +0000163}
164
Max Reitz009b03a2019-02-01 20:29:13 +0100165/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000166 path to it by considering it is relative to base_path. URL are
167 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100168char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000169{
Max Reitz009b03a2019-02-01 20:29:13 +0100170 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000171 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100172 char *result;
bellard83f64092006-08-01 16:21:11 +0000173 int len;
174
bellard83f64092006-08-01 16:21:11 +0000175 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100176 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000177 }
Max Reitz009b03a2019-02-01 20:29:13 +0100178
179 if (path_has_protocol(base_path)) {
180 protocol_stripped = strchr(base_path, ':');
181 if (protocol_stripped) {
182 protocol_stripped++;
183 }
184 }
185 p = protocol_stripped ?: base_path;
186
187 p1 = strrchr(base_path, '/');
188#ifdef _WIN32
189 {
190 const char *p2;
191 p2 = strrchr(base_path, '\\');
192 if (!p1 || p2 > p1) {
193 p1 = p2;
194 }
195 }
196#endif
197 if (p1) {
198 p1++;
199 } else {
200 p1 = base_path;
201 }
202 if (p1 > p) {
203 p = p1;
204 }
205 len = p - base_path;
206
207 result = g_malloc(len + strlen(filename) + 1);
208 memcpy(result, base_path, len);
209 strcpy(result + len, filename);
210
211 return result;
212}
213
Max Reitz03c320d2017-05-22 21:52:16 +0200214/*
215 * Helper function for bdrv_parse_filename() implementations to remove optional
216 * protocol prefixes (especially "file:") from a filename and for putting the
217 * stripped filename into the options QDict if there is such a prefix.
218 */
219void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
220 QDict *options)
221{
222 if (strstart(filename, prefix, &filename)) {
223 /* Stripping the explicit protocol prefix may result in a protocol
224 * prefix being (wrongly) detected (if the filename contains a colon) */
225 if (path_has_protocol(filename)) {
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100226 GString *fat_filename;
Max Reitz03c320d2017-05-22 21:52:16 +0200227
228 /* This means there is some colon before the first slash; therefore,
229 * this cannot be an absolute path */
230 assert(!path_is_absolute(filename));
231
232 /* And we can thus fix the protocol detection issue by prefixing it
233 * by "./" */
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100234 fat_filename = g_string_new("./");
235 g_string_append(fat_filename, filename);
Max Reitz03c320d2017-05-22 21:52:16 +0200236
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100237 assert(!path_has_protocol(fat_filename->str));
Max Reitz03c320d2017-05-22 21:52:16 +0200238
Markus Armbruster18cf67c2020-12-11 18:11:51 +0100239 qdict_put(options, "filename",
240 qstring_from_gstring(fat_filename));
Max Reitz03c320d2017-05-22 21:52:16 +0200241 } else {
242 /* If no protocol prefix was detected, we can use the shortened
243 * filename as-is */
244 qdict_put_str(options, "filename", filename);
245 }
246 }
247}
248
249
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200250/* Returns whether the image file is opened as read-only. Note that this can
251 * return false and writing to the image file is still not possible because the
252 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400253bool bdrv_is_read_only(BlockDriverState *bs)
254{
255 return bs->read_only;
256}
257
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200258int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
259 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400260{
Jeff Codye2b82472017-04-07 16:55:26 -0400261 /* Do not set read_only if copy_on_read is enabled */
262 if (bs->copy_on_read && read_only) {
263 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
264 bdrv_get_device_or_node_name(bs));
265 return -EINVAL;
266 }
267
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400268 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200269 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
270 !ignore_allow_rdw)
271 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400272 error_setg(errp, "Node '%s' is read only",
273 bdrv_get_device_or_node_name(bs));
274 return -EPERM;
275 }
276
Jeff Cody45803a02017-04-07 16:55:29 -0400277 return 0;
278}
279
Kevin Wolfeaa24102018-10-12 11:27:41 +0200280/*
281 * Called by a driver that can only provide a read-only image.
282 *
283 * Returns 0 if the node is already read-only or it could switch the node to
284 * read-only because BDRV_O_AUTO_RDONLY is set.
285 *
286 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
287 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
288 * is not NULL, it is used as the error message for the Error object.
289 */
290int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
291 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400292{
293 int ret = 0;
294
Kevin Wolfeaa24102018-10-12 11:27:41 +0200295 if (!(bs->open_flags & BDRV_O_RDWR)) {
296 return 0;
297 }
298 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
299 goto fail;
300 }
301
302 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400303 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200304 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400305 }
306
Kevin Wolfeaa24102018-10-12 11:27:41 +0200307 bs->read_only = true;
308 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200309
Jeff Codye2b82472017-04-07 16:55:26 -0400310 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200311
312fail:
313 error_setg(errp, "%s", errmsg ?: "Image is read-only");
314 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400315}
316
Max Reitz645ae7d2019-02-01 20:29:14 +0100317/*
318 * If @backing is empty, this function returns NULL without setting
319 * @errp. In all other cases, NULL will only be returned with @errp
320 * set.
321 *
322 * Therefore, a return value of NULL without @errp set means that
323 * there is no backing file; if @errp is set, there is one but its
324 * absolute filename cannot be generated.
325 */
326char *bdrv_get_full_backing_filename_from_filename(const char *backed,
327 const char *backing,
328 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100329{
Max Reitz645ae7d2019-02-01 20:29:14 +0100330 if (backing[0] == '\0') {
331 return NULL;
332 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
333 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100334 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
335 error_setg(errp, "Cannot use relative backing file names for '%s'",
336 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100337 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100338 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100339 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100340 }
341}
342
Max Reitz9f4793d2019-02-01 20:29:16 +0100343/*
344 * If @filename is empty or NULL, this function returns NULL without
345 * setting @errp. In all other cases, NULL will only be returned with
346 * @errp set.
347 */
348static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
349 const char *filename, Error **errp)
350{
Max Reitz8df68612019-02-01 20:29:23 +0100351 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100352
Max Reitz8df68612019-02-01 20:29:23 +0100353 if (!filename || filename[0] == '\0') {
354 return NULL;
355 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
356 return g_strdup(filename);
357 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100358
Max Reitz8df68612019-02-01 20:29:23 +0100359 dir = bdrv_dirname(relative_to, errp);
360 if (!dir) {
361 return NULL;
362 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100363
Max Reitz8df68612019-02-01 20:29:23 +0100364 full_name = g_strconcat(dir, filename, NULL);
365 g_free(dir);
366 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100367}
368
Max Reitz6b6833c2019-02-01 20:29:15 +0100369char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200370{
Max Reitz9f4793d2019-02-01 20:29:16 +0100371 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200372}
373
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100374void bdrv_register(BlockDriver *bdrv)
375{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100376 assert(bdrv->format_name);
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100377 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000378}
bellardb3380822004-03-14 21:38:54 +0000379
Markus Armbrustere4e99862014-10-07 13:59:03 +0200380BlockDriverState *bdrv_new(void)
381{
382 BlockDriverState *bs;
383 int i;
384
Markus Armbruster5839e532014-08-19 10:31:08 +0200385 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800386 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800387 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
388 QLIST_INIT(&bs->op_blockers[i]);
389 }
Stefan Hajnoczid616b222013-06-24 17:13:10 +0200390 notifier_with_return_list_init(&bs->before_write_notifiers);
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200391 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200392 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800393 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200394 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200395
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300396 qemu_co_queue_init(&bs->flush_queue);
397
Kevin Wolf0f122642018-03-28 18:29:18 +0200398 for (i = 0; i < bdrv_drain_all_count; i++) {
399 bdrv_drained_begin(bs);
400 }
401
Max Reitz2c1d04e2016-01-29 16:36:11 +0100402 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
403
bellardb3380822004-03-14 21:38:54 +0000404 return bs;
405}
406
Marc Mari88d88792016-08-12 09:27:03 -0400407static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000408{
409 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400410
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100411 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
412 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000413 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100414 }
bellardea2384d2004-08-01 21:59:26 +0000415 }
Marc Mari88d88792016-08-12 09:27:03 -0400416
bellardea2384d2004-08-01 21:59:26 +0000417 return NULL;
418}
419
Marc Mari88d88792016-08-12 09:27:03 -0400420BlockDriver *bdrv_find_format(const char *format_name)
421{
422 BlockDriver *drv1;
423 int i;
424
425 drv1 = bdrv_do_find_format(format_name);
426 if (drv1) {
427 return drv1;
428 }
429
430 /* The driver isn't registered, maybe we need to load a module */
431 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
432 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
433 block_module_load_one(block_driver_modules[i].library_name);
434 break;
435 }
436 }
437
438 return bdrv_do_find_format(format_name);
439}
440
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300441static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100442{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800443 static const char *whitelist_rw[] = {
444 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200445 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800446 };
447 static const char *whitelist_ro[] = {
448 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200449 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100450 };
451 const char **p;
452
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800453 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100454 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800455 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100456
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800457 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300458 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100459 return 1;
460 }
461 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800462 if (read_only) {
463 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300464 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800465 return 1;
466 }
467 }
468 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100469 return 0;
470}
471
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300472int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
473{
474 return bdrv_format_is_whitelisted(drv->format_name, read_only);
475}
476
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000477bool bdrv_uses_whitelist(void)
478{
479 return use_bdrv_whitelist;
480}
481
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800482typedef struct CreateCo {
483 BlockDriver *drv;
484 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800485 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800486 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200487 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800488} CreateCo;
489
490static void coroutine_fn bdrv_create_co_entry(void *opaque)
491{
Max Reitzcc84d902013-09-06 17:14:26 +0200492 Error *local_err = NULL;
493 int ret;
494
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800495 CreateCo *cco = opaque;
496 assert(cco->drv);
497
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200498 ret = cco->drv->bdrv_co_create_opts(cco->drv,
499 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300500 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200501 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800502}
503
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200504int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800505 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000506{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800507 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200508
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800509 Coroutine *co;
510 CreateCo cco = {
511 .drv = drv,
512 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800513 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800514 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200515 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800516 };
517
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100518 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200519 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300520 ret = -ENOTSUP;
521 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800522 }
523
524 if (qemu_in_coroutine()) {
525 /* Fast-path if already in coroutine context */
526 bdrv_create_co_entry(&cco);
527 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200528 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
529 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800530 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200531 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800532 }
533 }
534
535 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200536 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100537 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200538 error_propagate(errp, cco.err);
539 } else {
540 error_setg_errno(errp, -ret, "Could not create image");
541 }
542 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800543
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300544out:
545 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800546 return ret;
bellardea2384d2004-08-01 21:59:26 +0000547}
548
Max Reitzfd171462020-01-22 17:45:29 +0100549/**
550 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
551 * least the given @minimum_size.
552 *
553 * On success, return @blk's actual length.
554 * Otherwise, return -errno.
555 */
556static int64_t create_file_fallback_truncate(BlockBackend *blk,
557 int64_t minimum_size, Error **errp)
558{
559 Error *local_err = NULL;
560 int64_t size;
561 int ret;
562
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200563 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
564 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100565 if (ret < 0 && ret != -ENOTSUP) {
566 error_propagate(errp, local_err);
567 return ret;
568 }
569
570 size = blk_getlength(blk);
571 if (size < 0) {
572 error_free(local_err);
573 error_setg_errno(errp, -size,
574 "Failed to inquire the new image file's length");
575 return size;
576 }
577
578 if (size < minimum_size) {
579 /* Need to grow the image, but we failed to do that */
580 error_propagate(errp, local_err);
581 return -ENOTSUP;
582 }
583
584 error_free(local_err);
585 local_err = NULL;
586
587 return size;
588}
589
590/**
591 * Helper function for bdrv_create_file_fallback(): Zero the first
592 * sector to remove any potentially pre-existing image header.
593 */
594static int create_file_fallback_zero_first_sector(BlockBackend *blk,
595 int64_t current_size,
596 Error **errp)
597{
598 int64_t bytes_to_clear;
599 int ret;
600
601 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
602 if (bytes_to_clear) {
603 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
604 if (ret < 0) {
605 error_setg_errno(errp, -ret,
606 "Failed to clear the new image's first sector");
607 return ret;
608 }
609 }
610
611 return 0;
612}
613
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200614/**
615 * Simple implementation of bdrv_co_create_opts for protocol drivers
616 * which only support creation via opening a file
617 * (usually existing raw storage device)
618 */
619int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
620 const char *filename,
621 QemuOpts *opts,
622 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100623{
624 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100625 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100626 int64_t size = 0;
627 char *buf = NULL;
628 PreallocMode prealloc;
629 Error *local_err = NULL;
630 int ret;
631
632 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
633 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
634 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
635 PREALLOC_MODE_OFF, &local_err);
636 g_free(buf);
637 if (local_err) {
638 error_propagate(errp, local_err);
639 return -EINVAL;
640 }
641
642 if (prealloc != PREALLOC_MODE_OFF) {
643 error_setg(errp, "Unsupported preallocation mode '%s'",
644 PreallocMode_str(prealloc));
645 return -ENOTSUP;
646 }
647
Max Reitzeeea1fa2020-02-25 16:56:18 +0100648 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100649 qdict_put_str(options, "driver", drv->format_name);
650
651 blk = blk_new_open(filename, NULL, options,
652 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
653 if (!blk) {
654 error_prepend(errp, "Protocol driver '%s' does not support image "
655 "creation, and opening the image failed: ",
656 drv->format_name);
657 return -EINVAL;
658 }
659
660 size = create_file_fallback_truncate(blk, size, errp);
661 if (size < 0) {
662 ret = size;
663 goto out;
664 }
665
666 ret = create_file_fallback_zero_first_sector(blk, size, errp);
667 if (ret < 0) {
668 goto out;
669 }
670
671 ret = 0;
672out:
673 blk_unref(blk);
674 return ret;
675}
676
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800677int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200678{
Stefano Garzarella729222a2021-03-08 17:12:32 +0100679 QemuOpts *protocol_opts;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200680 BlockDriver *drv;
Stefano Garzarella729222a2021-03-08 17:12:32 +0100681 QDict *qdict;
682 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200683
Max Reitzb65a5e12015-02-05 13:58:12 -0500684 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200685 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000686 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200687 }
688
Stefano Garzarella729222a2021-03-08 17:12:32 +0100689 if (!drv->create_opts) {
690 error_setg(errp, "Driver '%s' does not support image creation",
691 drv->format_name);
692 return -ENOTSUP;
693 }
694
695 /*
696 * 'opts' contains a QemuOptsList with a combination of format and protocol
697 * default values.
698 *
699 * The format properly removes its options, but the default values remain
700 * in 'opts->list'. So if the protocol has options with the same name
701 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
702 * of the format, since for overlapping options, the format wins.
703 *
704 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
705 * only the set options, and then convert it back to QemuOpts, using the
706 * create_opts of the protocol. So the new QemuOpts, will contain only the
707 * protocol defaults.
708 */
709 qdict = qemu_opts_to_qdict(opts, NULL);
710 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
711 if (protocol_opts == NULL) {
712 ret = -EINVAL;
713 goto out;
714 }
715
716 ret = bdrv_create(drv, filename, protocol_opts, errp);
717out:
718 qemu_opts_del(protocol_opts);
719 qobject_unref(qdict);
720 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200721}
722
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300723int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
724{
725 Error *local_err = NULL;
726 int ret;
727
728 assert(bs != NULL);
729
730 if (!bs->drv) {
731 error_setg(errp, "Block node '%s' is not opened", bs->filename);
732 return -ENOMEDIUM;
733 }
734
735 if (!bs->drv->bdrv_co_delete_file) {
736 error_setg(errp, "Driver '%s' does not support image deletion",
737 bs->drv->format_name);
738 return -ENOTSUP;
739 }
740
741 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
742 if (ret < 0) {
743 error_propagate(errp, local_err);
744 }
745
746 return ret;
747}
748
Maxim Levitskya890f082020-12-17 19:09:03 +0200749void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
750{
751 Error *local_err = NULL;
752 int ret;
753
754 if (!bs) {
755 return;
756 }
757
758 ret = bdrv_co_delete_file(bs, &local_err);
759 /*
760 * ENOTSUP will happen if the block driver doesn't support
761 * the 'bdrv_co_delete_file' interface. This is a predictable
762 * scenario and shouldn't be reported back to the user.
763 */
764 if (ret == -ENOTSUP) {
765 error_free(local_err);
766 } else if (ret < 0) {
767 error_report_err(local_err);
768 }
769}
770
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100771/**
772 * Try to get @bs's logical and physical block size.
773 * On success, store them in @bsz struct and return 0.
774 * On failure return -errno.
775 * @bs must not be empty.
776 */
777int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
778{
779 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200780 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100781
782 if (drv && drv->bdrv_probe_blocksizes) {
783 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200784 } else if (filtered) {
785 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100786 }
787
788 return -ENOTSUP;
789}
790
791/**
792 * Try to get @bs's geometry (cyls, heads, sectors).
793 * On success, store them in @geo struct and return 0.
794 * On failure return -errno.
795 * @bs must not be empty.
796 */
797int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
798{
799 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200800 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100801
802 if (drv && drv->bdrv_probe_geometry) {
803 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200804 } else if (filtered) {
805 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100806 }
807
808 return -ENOTSUP;
809}
810
Jim Meyeringeba25052012-05-28 09:27:54 +0200811/*
812 * Create a uniquely-named empty temporary file.
813 * Return 0 upon success, otherwise a negative errno value.
814 */
815int get_tmp_filename(char *filename, int size)
816{
bellardd5249392004-08-03 21:14:23 +0000817#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000818 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200819 /* GetTempFileName requires that its output buffer (4th param)
820 have length MAX_PATH or greater. */
821 assert(size >= MAX_PATH);
822 return (GetTempPath(MAX_PATH, temp_dir)
823 && GetTempFileName(temp_dir, "qem", 0, filename)
824 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000825#else
bellardea2384d2004-08-01 21:59:26 +0000826 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000827 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000828 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530829 if (!tmpdir) {
830 tmpdir = "/var/tmp";
831 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200832 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
833 return -EOVERFLOW;
834 }
bellardea2384d2004-08-01 21:59:26 +0000835 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800836 if (fd < 0) {
837 return -errno;
838 }
839 if (close(fd) != 0) {
840 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200841 return -errno;
842 }
843 return 0;
bellardd5249392004-08-03 21:14:23 +0000844#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200845}
bellardea2384d2004-08-01 21:59:26 +0000846
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200847/*
848 * Detect host devices. By convention, /dev/cdrom[N] is always
849 * recognized as a host CDROM.
850 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200851static BlockDriver *find_hdev_driver(const char *filename)
852{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200853 int score_max = 0, score;
854 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200855
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100856 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200857 if (d->bdrv_probe_device) {
858 score = d->bdrv_probe_device(filename);
859 if (score > score_max) {
860 score_max = score;
861 drv = d;
862 }
863 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200864 }
865
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200866 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200867}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200868
Marc Mari88d88792016-08-12 09:27:03 -0400869static BlockDriver *bdrv_do_find_protocol(const char *protocol)
870{
871 BlockDriver *drv1;
872
873 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
874 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
875 return drv1;
876 }
877 }
878
879 return NULL;
880}
881
Kevin Wolf98289622013-07-10 15:47:39 +0200882BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500883 bool allow_protocol_prefix,
884 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200885{
886 BlockDriver *drv1;
887 char protocol[128];
888 int len;
889 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400890 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200891
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200892 /* TODO Drivers without bdrv_file_open must be specified explicitly */
893
Christoph Hellwig39508e72010-06-23 12:25:17 +0200894 /*
895 * XXX(hch): we really should not let host device detection
896 * override an explicit protocol specification, but moving this
897 * later breaks access to device names with colons in them.
898 * Thanks to the brain-dead persistent naming schemes on udev-
899 * based Linux systems those actually are quite common.
900 */
901 drv1 = find_hdev_driver(filename);
902 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200903 return drv1;
904 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200905
Kevin Wolf98289622013-07-10 15:47:39 +0200906 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100907 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200908 }
Kevin Wolf98289622013-07-10 15:47:39 +0200909
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000910 p = strchr(filename, ':');
911 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200912 len = p - filename;
913 if (len > sizeof(protocol) - 1)
914 len = sizeof(protocol) - 1;
915 memcpy(protocol, filename, len);
916 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400917
918 drv1 = bdrv_do_find_protocol(protocol);
919 if (drv1) {
920 return drv1;
921 }
922
923 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
924 if (block_driver_modules[i].protocol_name &&
925 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
926 block_module_load_one(block_driver_modules[i].library_name);
927 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200928 }
929 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500930
Marc Mari88d88792016-08-12 09:27:03 -0400931 drv1 = bdrv_do_find_protocol(protocol);
932 if (!drv1) {
933 error_setg(errp, "Unknown protocol '%s'", protocol);
934 }
935 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200936}
937
Markus Armbrusterc6684242014-11-20 16:27:10 +0100938/*
939 * Guess image format by probing its contents.
940 * This is not a good idea when your image is raw (CVE-2008-2004), but
941 * we do it anyway for backward compatibility.
942 *
943 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100944 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
945 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100946 * @filename is its filename.
947 *
948 * For all block drivers, call the bdrv_probe() method to get its
949 * probing score.
950 * Return the first block driver with the highest probing score.
951 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100952BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
953 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100954{
955 int score_max = 0, score;
956 BlockDriver *drv = NULL, *d;
957
958 QLIST_FOREACH(d, &bdrv_drivers, list) {
959 if (d->bdrv_probe) {
960 score = d->bdrv_probe(buf, buf_size, filename);
961 if (score > score_max) {
962 score_max = score;
963 drv = d;
964 }
965 }
966 }
967
968 return drv;
969}
970
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100971static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200972 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000973{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100974 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100975 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100976 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700977
Kevin Wolf08a00552010-06-01 18:37:31 +0200978 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100979 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100980 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200981 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700982 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700983
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100984 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +0000985 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200986 error_setg_errno(errp, -ret, "Could not read image for determining its "
987 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +0200988 *pdrv = NULL;
989 return ret;
bellard83f64092006-08-01 16:21:11 +0000990 }
991
Markus Armbrusterc6684242014-11-20 16:27:10 +0100992 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +0200993 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200994 error_setg(errp, "Could not determine image format: No compatible "
995 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +0200996 ret = -ENOENT;
997 }
998 *pdrv = drv;
999 return ret;
bellardea2384d2004-08-01 21:59:26 +00001000}
1001
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001002/**
1003 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +02001004 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001005 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +02001006int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001007{
1008 BlockDriver *drv = bs->drv;
1009
Max Reitzd470ad42017-11-10 21:31:09 +01001010 if (!drv) {
1011 return -ENOMEDIUM;
1012 }
1013
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001014 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +03001015 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -07001016 return 0;
1017
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001018 /* query actual device if possible, otherwise just trust the hint */
1019 if (drv->bdrv_getlength) {
1020 int64_t length = drv->bdrv_getlength(bs);
1021 if (length < 0) {
1022 return length;
1023 }
Fam Zheng7e382002013-11-06 19:48:06 +08001024 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001025 }
1026
1027 bs->total_sectors = hint;
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03001028
1029 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1030 return -EFBIG;
1031 }
1032
Stefan Hajnoczi51762282010-04-19 16:56:41 +01001033 return 0;
1034}
1035
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001036/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001037 * Combines a QDict of new block driver @options with any missing options taken
1038 * from @old_options, so that leaving out an option defaults to its old value.
1039 */
1040static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1041 QDict *old_options)
1042{
1043 if (bs->drv && bs->drv->bdrv_join_options) {
1044 bs->drv->bdrv_join_options(options, old_options);
1045 } else {
1046 qdict_join(options, old_options, false);
1047 }
1048}
1049
Alberto Garcia543770b2018-09-06 12:37:09 +03001050static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1051 int open_flags,
1052 Error **errp)
1053{
1054 Error *local_err = NULL;
1055 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1056 BlockdevDetectZeroesOptions detect_zeroes =
1057 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1058 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1059 g_free(value);
1060 if (local_err) {
1061 error_propagate(errp, local_err);
1062 return detect_zeroes;
1063 }
1064
1065 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1066 !(open_flags & BDRV_O_UNMAP))
1067 {
1068 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1069 "without setting discard operation to unmap");
1070 }
1071
1072 return detect_zeroes;
1073}
1074
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001075/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001076 * Set open flags for aio engine
1077 *
1078 * Return 0 on success, -1 if the engine specified is invalid
1079 */
1080int bdrv_parse_aio(const char *mode, int *flags)
1081{
1082 if (!strcmp(mode, "threads")) {
1083 /* do nothing, default */
1084 } else if (!strcmp(mode, "native")) {
1085 *flags |= BDRV_O_NATIVE_AIO;
1086#ifdef CONFIG_LINUX_IO_URING
1087 } else if (!strcmp(mode, "io_uring")) {
1088 *flags |= BDRV_O_IO_URING;
1089#endif
1090 } else {
1091 return -1;
1092 }
1093
1094 return 0;
1095}
1096
1097/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001098 * Set open flags for a given discard mode
1099 *
1100 * Return 0 on success, -1 if the discard mode was invalid.
1101 */
1102int bdrv_parse_discard_flags(const char *mode, int *flags)
1103{
1104 *flags &= ~BDRV_O_UNMAP;
1105
1106 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1107 /* do nothing */
1108 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1109 *flags |= BDRV_O_UNMAP;
1110 } else {
1111 return -1;
1112 }
1113
1114 return 0;
1115}
1116
1117/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001118 * Set open flags for a given cache mode
1119 *
1120 * Return 0 on success, -1 if the cache mode was invalid.
1121 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001122int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001123{
1124 *flags &= ~BDRV_O_CACHE_MASK;
1125
1126 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001127 *writethrough = false;
1128 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001129 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001130 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001131 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001132 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001133 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001134 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001135 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001136 *flags |= BDRV_O_NO_FLUSH;
1137 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001138 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001139 } else {
1140 return -1;
1141 }
1142
1143 return 0;
1144}
1145
Kevin Wolfb5411552017-01-17 15:56:16 +01001146static char *bdrv_child_get_parent_desc(BdrvChild *c)
1147{
1148 BlockDriverState *parent = c->opaque;
1149 return g_strdup(bdrv_get_device_or_node_name(parent));
1150}
1151
Kevin Wolf20018e12016-05-23 18:46:59 +02001152static void bdrv_child_cb_drained_begin(BdrvChild *child)
1153{
1154 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001155 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001156}
1157
Kevin Wolf89bd0302018-03-22 14:11:20 +01001158static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1159{
1160 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001161 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001162}
1163
Max Reitze037c092019-07-19 11:26:14 +02001164static void bdrv_child_cb_drained_end(BdrvChild *child,
1165 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001166{
1167 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001168 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001169}
1170
Kevin Wolf38701b62017-05-04 18:52:39 +02001171static int bdrv_child_cb_inactivate(BdrvChild *child)
1172{
1173 BlockDriverState *bs = child->opaque;
1174 assert(bs->open_flags & BDRV_O_INACTIVE);
1175 return 0;
1176}
1177
Kevin Wolf5d231842019-05-06 19:17:56 +02001178static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1179 GSList **ignore, Error **errp)
1180{
1181 BlockDriverState *bs = child->opaque;
1182 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1183}
1184
Kevin Wolf53a7d042019-05-06 19:17:59 +02001185static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1186 GSList **ignore)
1187{
1188 BlockDriverState *bs = child->opaque;
1189 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1190}
1191
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001192/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001193 * Returns the options and flags that a temporary snapshot should get, based on
1194 * the originally requested flags (the originally requested image will have
1195 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001196 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001197static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1198 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001199{
Kevin Wolf73176be2016-03-07 13:02:15 +01001200 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1201
1202 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001203 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1204 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001205
Kevin Wolf3f486862019-04-04 17:04:43 +02001206 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001207 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001208 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001209
Kevin Wolf41869042016-06-16 12:59:30 +02001210 /* aio=native doesn't work for cache.direct=off, so disable it for the
1211 * temporary snapshot */
1212 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001213}
1214
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001215static void bdrv_backing_attach(BdrvChild *c)
1216{
1217 BlockDriverState *parent = c->opaque;
1218 BlockDriverState *backing_hd = c->bs;
1219
1220 assert(!parent->backing_blocker);
1221 error_setg(&parent->backing_blocker,
1222 "node is used as backing hd of '%s'",
1223 bdrv_get_device_or_node_name(parent));
1224
Max Reitzf30c66b2019-02-01 20:29:05 +01001225 bdrv_refresh_filename(backing_hd);
1226
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001227 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001228
1229 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1230 /* Otherwise we won't be able to commit or stream */
1231 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1232 parent->backing_blocker);
1233 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1234 parent->backing_blocker);
1235 /*
1236 * We do backup in 3 ways:
1237 * 1. drive backup
1238 * The target bs is new opened, and the source is top BDS
1239 * 2. blockdev backup
1240 * Both the source and the target are top BDSes.
1241 * 3. internal backup(used for block replication)
1242 * Both the source and the target are backing file
1243 *
1244 * In case 1 and 2, neither the source nor the target is the backing file.
1245 * In case 3, we will block the top BDS, so there is only one block job
1246 * for the top BDS and its backing chain.
1247 */
1248 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1249 parent->backing_blocker);
1250 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1251 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001252}
Kevin Wolfd736f112017-12-18 16:05:48 +01001253
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001254static void bdrv_backing_detach(BdrvChild *c)
1255{
1256 BlockDriverState *parent = c->opaque;
1257
1258 assert(parent->backing_blocker);
1259 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1260 error_free(parent->backing_blocker);
1261 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001262}
Kevin Wolfd736f112017-12-18 16:05:48 +01001263
Kevin Wolf6858eba2017-06-29 19:32:21 +02001264static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1265 const char *filename, Error **errp)
1266{
1267 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001268 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001269 int ret;
1270
Alberto Garciae94d3db2018-11-12 16:00:34 +02001271 if (read_only) {
1272 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001273 if (ret < 0) {
1274 return ret;
1275 }
1276 }
1277
Kevin Wolf6858eba2017-06-29 19:32:21 +02001278 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001279 base->drv ? base->drv->format_name : "",
1280 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001281 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001282 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001283 }
1284
Alberto Garciae94d3db2018-11-12 16:00:34 +02001285 if (read_only) {
1286 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001287 }
1288
Kevin Wolf6858eba2017-06-29 19:32:21 +02001289 return ret;
1290}
1291
Max Reitzfae8bd32020-05-13 13:05:20 +02001292/*
1293 * Returns the options and flags that a generic child of a BDS should
1294 * get, based on the given options and flags for the parent BDS.
1295 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001296static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1297 int *child_flags, QDict *child_options,
1298 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001299{
1300 int flags = parent_flags;
1301
1302 /*
1303 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1304 * Generally, the question to answer is: Should this child be
1305 * format-probed by default?
1306 */
1307
1308 /*
1309 * Pure and non-filtered data children of non-format nodes should
1310 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1311 * set). This only affects a very limited set of drivers (namely
1312 * quorum and blkverify when this comment was written).
1313 * Force-clear BDRV_O_PROTOCOL then.
1314 */
1315 if (!parent_is_format &&
1316 (role & BDRV_CHILD_DATA) &&
1317 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1318 {
1319 flags &= ~BDRV_O_PROTOCOL;
1320 }
1321
1322 /*
1323 * All children of format nodes (except for COW children) and all
1324 * metadata children in general should never be format-probed.
1325 * Force-set BDRV_O_PROTOCOL then.
1326 */
1327 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1328 (role & BDRV_CHILD_METADATA))
1329 {
1330 flags |= BDRV_O_PROTOCOL;
1331 }
1332
1333 /*
1334 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1335 * the parent.
1336 */
1337 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1338 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1339 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1340
1341 if (role & BDRV_CHILD_COW) {
1342 /* backing files are opened read-only by default */
1343 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1344 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1345 } else {
1346 /* Inherit the read-only option from the parent if it's not set */
1347 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1348 qdict_copy_default(child_options, parent_options,
1349 BDRV_OPT_AUTO_READ_ONLY);
1350 }
1351
1352 /*
1353 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1354 * can default to enable it on lower layers regardless of the
1355 * parent option.
1356 */
1357 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1358
1359 /* Clear flags that only apply to the top layer */
1360 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1361
1362 if (role & BDRV_CHILD_METADATA) {
1363 flags &= ~BDRV_O_NO_IO;
1364 }
1365 if (role & BDRV_CHILD_COW) {
1366 flags &= ~BDRV_O_TEMPORARY;
1367 }
1368
1369 *child_flags = flags;
1370}
1371
Max Reitzca2f1232020-05-13 13:05:22 +02001372static void bdrv_child_cb_attach(BdrvChild *child)
1373{
1374 BlockDriverState *bs = child->opaque;
1375
1376 if (child->role & BDRV_CHILD_COW) {
1377 bdrv_backing_attach(child);
1378 }
1379
1380 bdrv_apply_subtree_drain(child, bs);
1381}
1382
Max Reitz48e08282020-05-13 13:05:23 +02001383static void bdrv_child_cb_detach(BdrvChild *child)
1384{
1385 BlockDriverState *bs = child->opaque;
1386
1387 if (child->role & BDRV_CHILD_COW) {
1388 bdrv_backing_detach(child);
1389 }
1390
1391 bdrv_unapply_subtree_drain(child, bs);
1392}
1393
Max Reitz43483552020-05-13 13:05:24 +02001394static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1395 const char *filename, Error **errp)
1396{
1397 if (c->role & BDRV_CHILD_COW) {
1398 return bdrv_backing_update_filename(c, base, filename, errp);
1399 }
1400 return 0;
1401}
1402
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001403static AioContext *bdrv_child_cb_get_parent_aio_context(BdrvChild *c)
1404{
1405 BlockDriverState *bs = c->opaque;
1406
1407 return bdrv_get_aio_context(bs);
1408}
1409
Max Reitz43483552020-05-13 13:05:24 +02001410const BdrvChildClass child_of_bds = {
1411 .parent_is_bds = true,
1412 .get_parent_desc = bdrv_child_get_parent_desc,
1413 .inherit_options = bdrv_inherited_options,
1414 .drained_begin = bdrv_child_cb_drained_begin,
1415 .drained_poll = bdrv_child_cb_drained_poll,
1416 .drained_end = bdrv_child_cb_drained_end,
1417 .attach = bdrv_child_cb_attach,
1418 .detach = bdrv_child_cb_detach,
1419 .inactivate = bdrv_child_cb_inactivate,
1420 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1421 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1422 .update_filename = bdrv_child_cb_update_filename,
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001423 .get_parent_aio_context = bdrv_child_cb_get_parent_aio_context,
Max Reitz43483552020-05-13 13:05:24 +02001424};
1425
Vladimir Sementsov-Ogievskiy3ca1f322021-04-28 18:17:33 +03001426AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1427{
1428 return c->klass->get_parent_aio_context(c);
1429}
1430
Kevin Wolf7b272452012-11-12 17:05:39 +01001431static int bdrv_open_flags(BlockDriverState *bs, int flags)
1432{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001433 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001434
1435 /*
1436 * Clear flags that are internal to the block layer before opening the
1437 * image.
1438 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001439 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001440
Kevin Wolf7b272452012-11-12 17:05:39 +01001441 return open_flags;
1442}
1443
Kevin Wolf91a097e2015-05-08 17:49:53 +02001444static void update_flags_from_options(int *flags, QemuOpts *opts)
1445{
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001446 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001447
Alberto Garcia57f9db92018-09-06 12:37:06 +03001448 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001449 *flags |= BDRV_O_NO_FLUSH;
1450 }
1451
Alberto Garcia57f9db92018-09-06 12:37:06 +03001452 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001453 *flags |= BDRV_O_NOCACHE;
1454 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001455
Alberto Garcia57f9db92018-09-06 12:37:06 +03001456 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001457 *flags |= BDRV_O_RDWR;
1458 }
1459
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001460 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1461 *flags |= BDRV_O_AUTO_RDONLY;
1462 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001463}
1464
1465static void update_options_from_flags(QDict *options, int flags)
1466{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001467 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001468 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001469 }
1470 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001471 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1472 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001473 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001474 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001475 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001476 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001477 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1478 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1479 flags & BDRV_O_AUTO_RDONLY);
1480 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001481}
1482
Kevin Wolf636ea372014-01-24 14:11:52 +01001483static void bdrv_assign_node_name(BlockDriverState *bs,
1484 const char *node_name,
1485 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001486{
Jeff Cody15489c72015-10-12 19:36:50 -04001487 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001488
Jeff Cody15489c72015-10-12 19:36:50 -04001489 if (!node_name) {
1490 node_name = gen_node_name = id_generate(ID_BLOCK);
1491 } else if (!id_wellformed(node_name)) {
1492 /*
1493 * Check for empty string or invalid characters, but not if it is
1494 * generated (generated names use characters not available to the user)
1495 */
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001496 error_setg(errp, "Invalid node-name: '%s'", node_name);
Kevin Wolf636ea372014-01-24 14:11:52 +01001497 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001498 }
1499
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001500 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001501 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001502 error_setg(errp, "node-name=%s is conflicting with a device id",
1503 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001504 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001505 }
1506
Benoît Canet6913c0c2014-01-23 21:31:33 +01001507 /* takes care of avoiding duplicates node names */
1508 if (bdrv_find_node(node_name)) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06001509 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001510 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001511 }
1512
Kevin Wolf824808d2018-07-04 13:28:29 +02001513 /* Make sure that the node name isn't truncated */
1514 if (strlen(node_name) >= sizeof(bs->node_name)) {
1515 error_setg(errp, "Node name too long");
1516 goto out;
1517 }
1518
Benoît Canet6913c0c2014-01-23 21:31:33 +01001519 /* copy node name into the bs and insert it into the graph list */
1520 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1521 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001522out:
1523 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001524}
1525
Kevin Wolf01a56502017-01-18 15:51:56 +01001526static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1527 const char *node_name, QDict *options,
1528 int open_flags, Error **errp)
1529{
1530 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001531 int i, ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001532
1533 bdrv_assign_node_name(bs, node_name, &local_err);
1534 if (local_err) {
1535 error_propagate(errp, local_err);
1536 return -EINVAL;
1537 }
1538
1539 bs->drv = drv;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001540 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Kevin Wolf01a56502017-01-18 15:51:56 +01001541 bs->opaque = g_malloc0(drv->instance_size);
1542
1543 if (drv->bdrv_file_open) {
1544 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1545 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001546 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001547 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001548 } else {
1549 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001550 }
1551
1552 if (ret < 0) {
1553 if (local_err) {
1554 error_propagate(errp, local_err);
1555 } else if (bs->filename[0]) {
1556 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1557 } else {
1558 error_setg_errno(errp, -ret, "Could not open image");
1559 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001560 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001561 }
1562
1563 ret = refresh_total_sectors(bs, bs->total_sectors);
1564 if (ret < 0) {
1565 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001566 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001567 }
1568
1569 bdrv_refresh_limits(bs, &local_err);
1570 if (local_err) {
1571 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001572 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001573 }
1574
1575 assert(bdrv_opt_mem_align(bs) != 0);
1576 assert(bdrv_min_mem_align(bs) != 0);
1577 assert(is_power_of_2(bs->bl.request_alignment));
1578
Kevin Wolf0f122642018-03-28 18:29:18 +02001579 for (i = 0; i < bs->quiesce_counter; i++) {
1580 if (drv->bdrv_co_drain_begin) {
1581 drv->bdrv_co_drain_begin(bs);
1582 }
1583 }
1584
Kevin Wolf01a56502017-01-18 15:51:56 +01001585 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001586open_failed:
1587 bs->drv = NULL;
1588 if (bs->file != NULL) {
1589 bdrv_unref_child(bs, bs->file);
1590 bs->file = NULL;
1591 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001592 g_free(bs->opaque);
1593 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001594 return ret;
1595}
1596
Kevin Wolf680c7f92017-01-18 17:16:41 +01001597BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1598 int flags, Error **errp)
1599{
1600 BlockDriverState *bs;
1601 int ret;
1602
1603 bs = bdrv_new();
1604 bs->open_flags = flags;
1605 bs->explicit_options = qdict_new();
1606 bs->options = qdict_new();
1607 bs->opaque = NULL;
1608
1609 update_options_from_flags(bs->options, flags);
1610
1611 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1612 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001613 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001614 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001615 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001616 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001617 bdrv_unref(bs);
1618 return NULL;
1619 }
1620
1621 return bs;
1622}
1623
Kevin Wolfc5f30142016-10-06 11:33:17 +02001624QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001625 .name = "bdrv_common",
1626 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1627 .desc = {
1628 {
1629 .name = "node-name",
1630 .type = QEMU_OPT_STRING,
1631 .help = "Node name of the block device node",
1632 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001633 {
1634 .name = "driver",
1635 .type = QEMU_OPT_STRING,
1636 .help = "Block driver to use for the node",
1637 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001638 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001639 .name = BDRV_OPT_CACHE_DIRECT,
1640 .type = QEMU_OPT_BOOL,
1641 .help = "Bypass software writeback cache on the host",
1642 },
1643 {
1644 .name = BDRV_OPT_CACHE_NO_FLUSH,
1645 .type = QEMU_OPT_BOOL,
1646 .help = "Ignore flush requests",
1647 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001648 {
1649 .name = BDRV_OPT_READ_ONLY,
1650 .type = QEMU_OPT_BOOL,
1651 .help = "Node is opened in read-only mode",
1652 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001653 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001654 .name = BDRV_OPT_AUTO_READ_ONLY,
1655 .type = QEMU_OPT_BOOL,
1656 .help = "Node can become read-only if opening read-write fails",
1657 },
1658 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001659 .name = "detect-zeroes",
1660 .type = QEMU_OPT_STRING,
1661 .help = "try to optimize zero writes (off, on, unmap)",
1662 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001663 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001664 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001665 .type = QEMU_OPT_STRING,
1666 .help = "discard operation (ignore/off, unmap/on)",
1667 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001668 {
1669 .name = BDRV_OPT_FORCE_SHARE,
1670 .type = QEMU_OPT_BOOL,
1671 .help = "always accept other writers (default: off)",
1672 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001673 { /* end of list */ }
1674 },
1675};
1676
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001677QemuOptsList bdrv_create_opts_simple = {
1678 .name = "simple-create-opts",
1679 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001680 .desc = {
1681 {
1682 .name = BLOCK_OPT_SIZE,
1683 .type = QEMU_OPT_SIZE,
1684 .help = "Virtual disk size"
1685 },
1686 {
1687 .name = BLOCK_OPT_PREALLOC,
1688 .type = QEMU_OPT_STRING,
1689 .help = "Preallocation mode (allowed values: off)"
1690 },
1691 { /* end of list */ }
1692 }
1693};
1694
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001695/*
Kevin Wolf57915332010-04-14 15:24:50 +02001696 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001697 *
1698 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001699 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001700static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001701 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001702{
1703 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001704 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001705 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001706 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001707 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001708 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001709 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001710 Error *local_err = NULL;
Kevin Wolf57915332010-04-14 15:24:50 +02001711
Paolo Bonzini64058752012-05-08 16:51:49 +02001712 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001713 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001714
Kevin Wolf62392eb2015-04-24 16:38:02 +02001715 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001716 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001717 ret = -EINVAL;
1718 goto fail_opts;
1719 }
1720
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001721 update_flags_from_options(&bs->open_flags, opts);
1722
Kevin Wolf62392eb2015-04-24 16:38:02 +02001723 driver_name = qemu_opt_get(opts, "driver");
1724 drv = bdrv_find_format(driver_name);
1725 assert(drv != NULL);
1726
Fam Zheng5a9347c2017-05-03 00:35:37 +08001727 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1728
1729 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1730 error_setg(errp,
1731 BDRV_OPT_FORCE_SHARE
1732 "=on can only be used with read-only images");
1733 ret = -EINVAL;
1734 goto fail_opts;
1735 }
1736
Kevin Wolf45673672013-04-22 17:48:40 +02001737 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001738 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001739 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001740 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001741 /*
1742 * Caution: while qdict_get_try_str() is fine, getting
1743 * non-string types would require more care. When @options
1744 * come from -blockdev or blockdev_add, its members are typed
1745 * according to the QAPI schema, but when they come from
1746 * -drive, they're all QString.
1747 */
Kevin Wolf45673672013-04-22 17:48:40 +02001748 filename = qdict_get_try_str(options, "filename");
1749 }
1750
Max Reitz4a008242017-04-13 18:06:24 +02001751 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001752 error_setg(errp, "The '%s' block driver requires a file name",
1753 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001754 ret = -EINVAL;
1755 goto fail_opts;
1756 }
1757
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001758 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1759 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001760
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001761 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001762
1763 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001764 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1765 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1766 } else {
1767 ret = -ENOTSUP;
1768 }
1769 if (ret < 0) {
1770 error_setg(errp,
1771 !bs->read_only && bdrv_is_whitelisted(drv, true)
1772 ? "Driver '%s' can only be used for read-only devices"
1773 : "Driver '%s' is not whitelisted",
1774 drv->format_name);
1775 goto fail_opts;
1776 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001777 }
Kevin Wolf57915332010-04-14 15:24:50 +02001778
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001779 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001780 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001781
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001782 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001783 if (!bs->read_only) {
1784 bdrv_enable_copy_on_read(bs);
1785 } else {
1786 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001787 ret = -EINVAL;
1788 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001789 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001790 }
1791
Alberto Garcia415bbca2018-10-03 13:23:13 +03001792 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001793 if (discard != NULL) {
1794 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1795 error_setg(errp, "Invalid discard option");
1796 ret = -EINVAL;
1797 goto fail_opts;
1798 }
1799 }
1800
Alberto Garcia543770b2018-09-06 12:37:09 +03001801 bs->detect_zeroes =
1802 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1803 if (local_err) {
1804 error_propagate(errp, local_err);
1805 ret = -EINVAL;
1806 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001807 }
1808
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001809 if (filename != NULL) {
1810 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1811 } else {
1812 bs->filename[0] = '\0';
1813 }
Max Reitz91af7012014-07-18 20:24:56 +02001814 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001815
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001816 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001817 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001818 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001819
Kevin Wolf01a56502017-01-18 15:51:56 +01001820 assert(!drv->bdrv_file_open || file == NULL);
1821 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001822 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001823 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001824 }
1825
Kevin Wolf18edf282015-04-07 17:12:56 +02001826 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001827 return 0;
1828
Kevin Wolf18edf282015-04-07 17:12:56 +02001829fail_opts:
1830 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001831 return ret;
1832}
1833
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001834static QDict *parse_json_filename(const char *filename, Error **errp)
1835{
1836 QObject *options_obj;
1837 QDict *options;
1838 int ret;
1839
1840 ret = strstart(filename, "json:", &filename);
1841 assert(ret);
1842
Markus Armbruster5577fff2017-02-28 22:26:59 +01001843 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001844 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001845 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001846 return NULL;
1847 }
1848
Max Reitz7dc847e2018-02-24 16:40:29 +01001849 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001850 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001851 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001852 error_setg(errp, "Invalid JSON object given");
1853 return NULL;
1854 }
1855
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001856 qdict_flatten(options);
1857
1858 return options;
1859}
1860
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001861static void parse_json_protocol(QDict *options, const char **pfilename,
1862 Error **errp)
1863{
1864 QDict *json_options;
1865 Error *local_err = NULL;
1866
1867 /* Parse json: pseudo-protocol */
1868 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1869 return;
1870 }
1871
1872 json_options = parse_json_filename(*pfilename, &local_err);
1873 if (local_err) {
1874 error_propagate(errp, local_err);
1875 return;
1876 }
1877
1878 /* Options given in the filename have lower priority than options
1879 * specified directly */
1880 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001881 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001882 *pfilename = NULL;
1883}
1884
Kevin Wolf57915332010-04-14 15:24:50 +02001885/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001886 * Fills in default options for opening images and converts the legacy
1887 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001888 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1889 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001890 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001891static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001892 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001893{
1894 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001895 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001896 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001897 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001898 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001899
Markus Armbruster129c7d12017-03-30 19:43:12 +02001900 /*
1901 * Caution: while qdict_get_try_str() is fine, getting non-string
1902 * types would require more care. When @options come from
1903 * -blockdev or blockdev_add, its members are typed according to
1904 * the QAPI schema, but when they come from -drive, they're all
1905 * QString.
1906 */
Max Reitz53a29512015-03-19 14:53:16 -04001907 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001908 if (drvname) {
1909 drv = bdrv_find_format(drvname);
1910 if (!drv) {
1911 error_setg(errp, "Unknown driver '%s'", drvname);
1912 return -ENOENT;
1913 }
1914 /* If the user has explicitly specified the driver, this choice should
1915 * override the BDRV_O_PROTOCOL flag */
1916 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001917 }
1918
1919 if (protocol) {
1920 *flags |= BDRV_O_PROTOCOL;
1921 } else {
1922 *flags &= ~BDRV_O_PROTOCOL;
1923 }
1924
Kevin Wolf91a097e2015-05-08 17:49:53 +02001925 /* Translate cache options from flags into options */
1926 update_options_from_flags(*options, *flags);
1927
Kevin Wolff54120f2014-05-26 11:09:59 +02001928 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001929 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001930 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001931 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001932 parse_filename = true;
1933 } else {
1934 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1935 "the same time");
1936 return -EINVAL;
1937 }
1938 }
1939
1940 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001941 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001942 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001943
Max Reitz053e1572015-08-26 19:47:51 +02001944 if (!drvname && protocol) {
1945 if (filename) {
1946 drv = bdrv_find_protocol(filename, parse_filename, errp);
1947 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001948 return -EINVAL;
1949 }
Max Reitz053e1572015-08-26 19:47:51 +02001950
1951 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05001952 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02001953 } else {
1954 error_setg(errp, "Must specify either driver or file");
1955 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001956 }
1957 }
1958
Kevin Wolf17b005f2014-05-27 10:50:29 +02001959 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001960
1961 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001962 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001963 drv->bdrv_parse_filename(filename, *options, &local_err);
1964 if (local_err) {
1965 error_propagate(errp, local_err);
1966 return -EINVAL;
1967 }
1968
1969 if (!drv->bdrv_needs_filename) {
1970 qdict_del(*options, "filename");
1971 }
1972 }
1973
1974 return 0;
1975}
1976
Kevin Wolf3121fb42017-09-14 14:42:12 +02001977static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1978 uint64_t perm, uint64_t shared,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03001979 GSList *ignore_children, Error **errp);
Fam Zhengc1cef672017-03-14 10:30:50 +08001980static void bdrv_child_abort_perm_update(BdrvChild *c);
Vladimir Sementsov-Ogievskiy6e0c9162020-11-06 15:42:40 +03001981static void bdrv_child_set_perm(BdrvChild *c);
Fam Zhengc1cef672017-03-14 10:30:50 +08001982
Kevin Wolf148eb132017-09-14 14:32:04 +02001983typedef struct BlockReopenQueueEntry {
1984 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01001985 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02001986 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03001987 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02001988} BlockReopenQueueEntry;
1989
1990/*
1991 * Return the flags that @bs will have after the reopens in @q have
1992 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1993 * return the current flags.
1994 */
1995static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1996{
1997 BlockReopenQueueEntry *entry;
1998
1999 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03002000 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02002001 if (entry->state.bs == bs) {
2002 return entry->state.flags;
2003 }
2004 }
2005 }
2006
2007 return bs->open_flags;
2008}
2009
2010/* Returns whether the image file can be written to after the reopen queue @q
2011 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02002012static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2013 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02002014{
2015 int flags = bdrv_reopen_get_flags(q, bs);
2016
2017 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2018}
2019
Max Reitzcc022142018-06-06 21:37:00 +02002020/*
2021 * Return whether the BDS can be written to. This is not necessarily
2022 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2023 * be written to but do not count as read-only images.
2024 */
2025bool bdrv_is_writable(BlockDriverState *bs)
2026{
2027 return bdrv_is_writable_after_reopen(bs, NULL);
2028}
2029
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002030static char *bdrv_child_user_desc(BdrvChild *c)
2031{
2032 if (c->klass->get_parent_desc) {
2033 return c->klass->get_parent_desc(c);
2034 }
2035
2036 return g_strdup("another user");
2037}
2038
2039static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2040{
2041 g_autofree char *user = NULL;
2042 g_autofree char *perm_names = NULL;
2043
2044 if ((b->perm & a->shared_perm) == b->perm) {
2045 return true;
2046 }
2047
2048 perm_names = bdrv_perm_names(b->perm & ~a->shared_perm);
2049 user = bdrv_child_user_desc(a);
2050 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2051 "allow '%s' on %s",
2052 user, a->name, perm_names, bdrv_get_node_name(b->bs));
2053
2054 return false;
2055}
2056
2057static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2058{
2059 BdrvChild *a, *b;
2060
2061 /*
2062 * During the loop we'll look at each pair twice. That's correct because
2063 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2064 * directions.
2065 */
2066 QLIST_FOREACH(a, &bs->parents, next_parent) {
2067 QLIST_FOREACH(b, &bs->parents, next_parent) {
2068 if (a == b) {
2069 continue;
2070 }
2071
2072 if (!bdrv_a_allow_b(a, b, errp)) {
2073 return true;
2074 }
2075 }
2076 }
2077
2078 return false;
2079}
2080
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002081static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02002082 BdrvChild *c, BdrvChildRole role,
2083 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002084 uint64_t parent_perm, uint64_t parent_shared,
2085 uint64_t *nperm, uint64_t *nshared)
2086{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002087 assert(bs->drv && bs->drv->bdrv_child_perm);
Max Reitze5d8a402020-05-13 13:05:44 +02002088 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03002089 parent_perm, parent_shared,
2090 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02002091 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002092 if (child_bs && child_bs->force_share) {
2093 *nshared = BLK_PERM_ALL;
2094 }
2095}
2096
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002097static void bdrv_child_set_perm_commit(void *opaque)
2098{
2099 BdrvChild *c = opaque;
2100
2101 c->has_backup_perm = false;
2102}
2103
2104static void bdrv_child_set_perm_abort(void *opaque)
2105{
2106 BdrvChild *c = opaque;
2107 /*
2108 * We may have child->has_backup_perm unset at this point, as in case of
2109 * _check_ stage of permission update failure we may _check_ not the whole
2110 * subtree. Still, _abort_ is called on the whole subtree anyway.
2111 */
2112 if (c->has_backup_perm) {
2113 c->perm = c->backup_perm;
2114 c->shared_perm = c->backup_shared_perm;
2115 c->has_backup_perm = false;
2116 }
2117}
2118
2119static TransactionActionDrv bdrv_child_set_pem_drv = {
2120 .abort = bdrv_child_set_perm_abort,
2121 .commit = bdrv_child_set_perm_commit,
2122};
2123
2124/*
2125 * With tran=NULL needs to be followed by direct call to either
2126 * bdrv_child_set_perm_commit() or bdrv_child_set_perm_abort().
2127 *
2128 * With non-NULL tran needs to be followed by tran_abort() or tran_commit()
2129 * instead.
2130 */
2131static void bdrv_child_set_perm_safe(BdrvChild *c, uint64_t perm,
2132 uint64_t shared, Transaction *tran)
2133{
2134 if (!c->has_backup_perm) {
2135 c->has_backup_perm = true;
2136 c->backup_perm = c->perm;
2137 c->backup_shared_perm = c->shared_perm;
2138 }
2139 /*
2140 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2141 * same c twice during check_perm procedure
2142 */
2143
2144 c->perm = perm;
2145 c->shared_perm = shared;
2146
2147 if (tran) {
2148 tran_add(tran, &bdrv_child_set_pem_drv, c);
2149 }
2150}
2151
Kevin Wolf33a610c2016-12-15 13:04:20 +01002152/*
2153 * Check whether permissions on this node can be changed in a way that
2154 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
2155 * permissions of all its parents. This involves checking whether all necessary
2156 * permission changes to child nodes can be performed.
2157 *
2158 * A call to this function must always be followed by a call to bdrv_set_perm()
2159 * or bdrv_abort_perm_update().
2160 */
Kevin Wolf3121fb42017-09-14 14:42:12 +02002161static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
2162 uint64_t cumulative_perms,
Kevin Wolf46181122017-03-06 15:00:13 +01002163 uint64_t cumulative_shared_perms,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002164 GSList *ignore_children, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002165{
2166 BlockDriver *drv = bs->drv;
2167 BdrvChild *c;
2168 int ret;
2169
2170 /* Write permissions never work with read-only images */
2171 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002172 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002173 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002174 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2175 error_setg(errp, "Block node is read-only");
2176 } else {
2177 uint64_t current_perms, current_shared;
2178 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2179 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2180 error_setg(errp, "Cannot make block node read-only, there is "
2181 "a writer on it");
2182 } else {
2183 error_setg(errp, "Cannot make block node read-only and create "
2184 "a writer on it");
2185 }
2186 }
2187
Kevin Wolf33a610c2016-12-15 13:04:20 +01002188 return -EPERM;
2189 }
2190
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002191 /*
2192 * Unaligned requests will automatically be aligned to bl.request_alignment
2193 * and without RESIZE we can't extend requests to write to space beyond the
2194 * end of the image, so it's required that the image size is aligned.
2195 */
2196 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2197 !(cumulative_perms & BLK_PERM_RESIZE))
2198 {
2199 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2200 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2201 "Image size is not a multiple of request "
2202 "alignment");
2203 return -EPERM;
2204 }
2205 }
2206
Kevin Wolf33a610c2016-12-15 13:04:20 +01002207 /* Check this node */
2208 if (!drv) {
2209 return 0;
2210 }
2211
2212 if (drv->bdrv_check_perm) {
Vladimir Sementsov-Ogievskiy9530a252020-10-21 17:58:45 +03002213 ret = drv->bdrv_check_perm(bs, cumulative_perms,
2214 cumulative_shared_perms, errp);
2215 if (ret < 0) {
2216 return ret;
2217 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002218 }
2219
Kevin Wolf78e421c2016-12-20 23:25:12 +01002220 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002221 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002222 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002223 return 0;
2224 }
2225
2226 /* Check all children */
2227 QLIST_FOREACH(c, &bs->children, next) {
2228 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002229
Max Reitze5d8a402020-05-13 13:05:44 +02002230 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002231 cumulative_perms, cumulative_shared_perms,
2232 &cur_perm, &cur_shared);
Max Reitz9eab1542019-05-22 19:03:50 +02002233 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
Max Reitz9eab1542019-05-22 19:03:50 +02002234 errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002235 if (ret < 0) {
2236 return ret;
2237 }
2238 }
2239
2240 return 0;
2241}
2242
2243/*
2244 * Notifies drivers that after a previous bdrv_check_perm() call, the
2245 * permission update is not performed and any preparations made for it (e.g.
2246 * taken file locks) need to be undone.
2247 *
2248 * This function recursively notifies all child nodes.
2249 */
2250static void bdrv_abort_perm_update(BlockDriverState *bs)
2251{
2252 BlockDriver *drv = bs->drv;
2253 BdrvChild *c;
2254
2255 if (!drv) {
2256 return;
2257 }
2258
2259 if (drv->bdrv_abort_perm_update) {
2260 drv->bdrv_abort_perm_update(bs);
2261 }
2262
2263 QLIST_FOREACH(c, &bs->children, next) {
2264 bdrv_child_abort_perm_update(c);
2265 }
2266}
2267
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002268static void bdrv_set_perm(BlockDriverState *bs)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002269{
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002270 uint64_t cumulative_perms, cumulative_shared_perms;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002271 BlockDriver *drv = bs->drv;
2272 BdrvChild *c;
2273
2274 if (!drv) {
2275 return;
2276 }
2277
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002278 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2279
Kevin Wolf33a610c2016-12-15 13:04:20 +01002280 /* Update this node */
2281 if (drv->bdrv_set_perm) {
2282 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2283 }
2284
Kevin Wolf78e421c2016-12-20 23:25:12 +01002285 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002286 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002287 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002288 return;
2289 }
2290
2291 /* Update all children */
2292 QLIST_FOREACH(c, &bs->children, next) {
Vladimir Sementsov-Ogievskiy6e0c9162020-11-06 15:42:40 +03002293 bdrv_child_set_perm(c);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002294 }
2295}
2296
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002297void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2298 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002299{
2300 BdrvChild *c;
2301 uint64_t cumulative_perms = 0;
2302 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2303
2304 QLIST_FOREACH(c, &bs->parents, next_parent) {
2305 cumulative_perms |= c->perm;
2306 cumulative_shared_perms &= c->shared_perm;
2307 }
2308
2309 *perm = cumulative_perms;
2310 *shared_perm = cumulative_shared_perms;
2311}
2312
Fam Zheng51761962017-05-03 00:35:36 +08002313char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002314{
2315 struct perm_name {
2316 uint64_t perm;
2317 const char *name;
2318 } permissions[] = {
2319 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2320 { BLK_PERM_WRITE, "write" },
2321 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2322 { BLK_PERM_RESIZE, "resize" },
2323 { BLK_PERM_GRAPH_MOD, "change children" },
2324 { 0, NULL }
2325 };
2326
Alberto Garciae2a74232020-01-10 18:15:18 +01002327 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002328 struct perm_name *p;
2329
2330 for (p = permissions; p->name; p++) {
2331 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002332 if (result->len > 0) {
2333 g_string_append(result, ", ");
2334 }
2335 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002336 }
2337 }
2338
Alberto Garciae2a74232020-01-10 18:15:18 +01002339 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002340}
2341
Kevin Wolf33a610c2016-12-15 13:04:20 +01002342/*
2343 * Checks whether a new reference to @bs can be added if the new user requires
Kevin Wolf46181122017-03-06 15:00:13 +01002344 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2345 * set, the BdrvChild objects in this list are ignored in the calculations;
2346 * this allows checking permission updates for an existing reference.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002347 *
2348 * Needs to be followed by a call to either bdrv_set_perm() or
2349 * bdrv_abort_perm_update(). */
Kevin Wolf3121fb42017-09-14 14:42:12 +02002350static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2351 uint64_t new_used_perm,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002352 uint64_t new_shared_perm,
Max Reitz9eab1542019-05-22 19:03:50 +02002353 GSList *ignore_children,
Max Reitz9eab1542019-05-22 19:03:50 +02002354 Error **errp)
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002355{
2356 BdrvChild *c;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002357 uint64_t cumulative_perms = new_used_perm;
2358 uint64_t cumulative_shared_perms = new_shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002359
Max Reitz9eab1542019-05-22 19:03:50 +02002360
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002361 /* There is no reason why anyone couldn't tolerate write_unchanged */
2362 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2363
2364 QLIST_FOREACH(c, &bs->parents, next_parent) {
Kevin Wolf46181122017-03-06 15:00:13 +01002365 if (g_slist_find(ignore_children, c)) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002366 continue;
2367 }
2368
Kevin Wolfd0833192017-01-16 18:26:20 +01002369 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2370 char *user = bdrv_child_user_desc(c);
2371 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
Max Reitz9eab1542019-05-22 19:03:50 +02002372
Kevin Wolfd0833192017-01-16 18:26:20 +01002373 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2374 "allow '%s' on %s",
2375 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2376 g_free(user);
2377 g_free(perm_names);
2378 return -EPERM;
2379 }
2380
2381 if ((c->perm & new_shared_perm) != c->perm) {
2382 char *user = bdrv_child_user_desc(c);
2383 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
Max Reitz9eab1542019-05-22 19:03:50 +02002384
Kevin Wolfd0833192017-01-16 18:26:20 +01002385 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2386 "'%s' on %s",
2387 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2388 g_free(user);
2389 g_free(perm_names);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002390 return -EPERM;
2391 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002392
2393 cumulative_perms |= c->perm;
2394 cumulative_shared_perms &= c->shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002395 }
2396
Kevin Wolf3121fb42017-09-14 14:42:12 +02002397 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002398 ignore_children, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002399}
2400
2401/* Needs to be followed by a call to either bdrv_child_set_perm() or
2402 * bdrv_child_abort_perm_update(). */
Kevin Wolf3121fb42017-09-14 14:42:12 +02002403static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2404 uint64_t perm, uint64_t shared,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002405 GSList *ignore_children, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002406{
Kevin Wolf46181122017-03-06 15:00:13 +01002407 int ret;
2408
2409 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002410 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children, errp);
Kevin Wolf46181122017-03-06 15:00:13 +01002411 g_slist_free(ignore_children);
2412
Vladimir Sementsov-Ogievskiyf962e962019-02-23 22:20:40 +03002413 if (ret < 0) {
2414 return ret;
2415 }
2416
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002417 bdrv_child_set_perm_safe(c, perm, shared, NULL);
Vladimir Sementsov-Ogievskiyf962e962019-02-23 22:20:40 +03002418
2419 return 0;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002420}
2421
Vladimir Sementsov-Ogievskiy6e0c9162020-11-06 15:42:40 +03002422static void bdrv_child_set_perm(BdrvChild *c)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002423{
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002424 bdrv_child_set_perm_commit(c);
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002425 bdrv_set_perm(c->bs);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002426}
2427
Fam Zhengc1cef672017-03-14 10:30:50 +08002428static void bdrv_child_abort_perm_update(BdrvChild *c)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002429{
Vladimir Sementsov-Ogievskiyb0defa82021-04-28 18:17:38 +03002430 bdrv_child_set_perm_abort(c);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002431 bdrv_abort_perm_update(c->bs);
2432}
2433
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002434static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002435{
2436 int ret;
2437 uint64_t perm, shared_perm;
2438
Vladimir Sementsov-Ogievskiy3bf416b2021-04-28 18:17:37 +03002439 if (bdrv_parent_perms_conflict(bs, errp)) {
2440 return -EPERM;
2441 }
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002442 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002443 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, errp);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002444 if (ret < 0) {
2445 bdrv_abort_perm_update(bs);
2446 return ret;
2447 }
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002448 bdrv_set_perm(bs);
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002449
2450 return 0;
2451}
2452
Kevin Wolf33a610c2016-12-15 13:04:20 +01002453int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2454 Error **errp)
2455{
Max Reitz10467792019-05-22 19:03:51 +02002456 Error *local_err = NULL;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002457 int ret;
2458
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002459 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL, &local_err);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002460 if (ret < 0) {
2461 bdrv_child_abort_perm_update(c);
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002462 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2463 /* tighten permissions */
Max Reitz10467792019-05-22 19:03:51 +02002464 error_propagate(errp, local_err);
2465 } else {
2466 /*
2467 * Our caller may intend to only loosen restrictions and
2468 * does not expect this function to fail. Errors are not
2469 * fatal in such a case, so we can just hide them from our
2470 * caller.
2471 */
2472 error_free(local_err);
2473 ret = 0;
2474 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002475 return ret;
2476 }
2477
Vladimir Sementsov-Ogievskiy6e0c9162020-11-06 15:42:40 +03002478 bdrv_child_set_perm(c);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002479
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002480 return 0;
2481}
2482
Max Reitzc1087f12019-05-22 19:03:46 +02002483int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2484{
2485 uint64_t parent_perms, parent_shared;
2486 uint64_t perms, shared;
2487
2488 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002489 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002490 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002491
2492 return bdrv_child_try_set_perm(c, perms, shared, errp);
2493}
2494
Max Reitz87278af2020-05-13 13:05:40 +02002495/*
2496 * Default implementation for .bdrv_child_perm() for block filters:
2497 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2498 * filtered child.
2499 */
2500static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002501 BdrvChildRole role,
2502 BlockReopenQueue *reopen_queue,
2503 uint64_t perm, uint64_t shared,
2504 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002505{
Kevin Wolfe444fa82019-08-02 15:59:41 +02002506 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2507 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002508}
2509
Max Reitz70082db2020-05-13 13:05:26 +02002510static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002511 BdrvChildRole role,
2512 BlockReopenQueue *reopen_queue,
2513 uint64_t perm, uint64_t shared,
2514 uint64_t *nperm, uint64_t *nshared)
2515{
Max Reitze5d8a402020-05-13 13:05:44 +02002516 assert(role & BDRV_CHILD_COW);
Max Reitz70082db2020-05-13 13:05:26 +02002517
2518 /*
2519 * We want consistent read from backing files if the parent needs it.
2520 * No other operations are performed on backing files.
2521 */
2522 perm &= BLK_PERM_CONSISTENT_READ;
2523
2524 /*
2525 * If the parent can deal with changing data, we're okay with a
2526 * writable and resizable backing file.
2527 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2528 */
2529 if (shared & BLK_PERM_WRITE) {
2530 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2531 } else {
2532 shared = 0;
2533 }
2534
2535 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2536 BLK_PERM_WRITE_UNCHANGED;
2537
2538 if (bs->open_flags & BDRV_O_INACTIVE) {
2539 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2540 }
2541
2542 *nperm = perm;
2543 *nshared = shared;
2544}
2545
Max Reitz6f838a42020-05-13 13:05:27 +02002546static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002547 BdrvChildRole role,
2548 BlockReopenQueue *reopen_queue,
2549 uint64_t perm, uint64_t shared,
2550 uint64_t *nperm, uint64_t *nshared)
2551{
2552 int flags;
2553
Max Reitze5d8a402020-05-13 13:05:44 +02002554 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002555
2556 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2557
2558 /*
2559 * Apart from the modifications below, the same permissions are
2560 * forwarded and left alone as for filters
2561 */
Max Reitze5d8a402020-05-13 13:05:44 +02002562 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002563 perm, shared, &perm, &shared);
2564
Max Reitzf8890542020-05-13 13:05:28 +02002565 if (role & BDRV_CHILD_METADATA) {
2566 /* Format drivers may touch metadata even if the guest doesn't write */
2567 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2568 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2569 }
2570
2571 /*
2572 * bs->file always needs to be consistent because of the
2573 * metadata. We can never allow other users to resize or write
2574 * to it.
2575 */
2576 if (!(flags & BDRV_O_NO_IO)) {
2577 perm |= BLK_PERM_CONSISTENT_READ;
2578 }
2579 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002580 }
2581
Max Reitzf8890542020-05-13 13:05:28 +02002582 if (role & BDRV_CHILD_DATA) {
2583 /*
2584 * Technically, everything in this block is a subset of the
2585 * BDRV_CHILD_METADATA path taken above, and so this could
2586 * be an "else if" branch. However, that is not obvious, and
2587 * this function is not performance critical, therefore we let
2588 * this be an independent "if".
2589 */
2590
2591 /*
2592 * We cannot allow other users to resize the file because the
2593 * format driver might have some assumptions about the size
2594 * (e.g. because it is stored in metadata, or because the file
2595 * is split into fixed-size data files).
2596 */
2597 shared &= ~BLK_PERM_RESIZE;
2598
2599 /*
2600 * WRITE_UNCHANGED often cannot be performed as such on the
2601 * data file. For example, the qcow2 driver may still need to
2602 * write copied clusters on copy-on-read.
2603 */
2604 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2605 perm |= BLK_PERM_WRITE;
2606 }
2607
2608 /*
2609 * If the data file is written to, the format driver may
2610 * expect to be able to resize it by writing beyond the EOF.
2611 */
2612 if (perm & BLK_PERM_WRITE) {
2613 perm |= BLK_PERM_RESIZE;
2614 }
Max Reitz6f838a42020-05-13 13:05:27 +02002615 }
Max Reitz6f838a42020-05-13 13:05:27 +02002616
2617 if (bs->open_flags & BDRV_O_INACTIVE) {
2618 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2619 }
2620
2621 *nperm = perm;
2622 *nshared = shared;
2623}
2624
Max Reitz2519f542020-05-13 13:05:29 +02002625void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002626 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002627 uint64_t perm, uint64_t shared,
2628 uint64_t *nperm, uint64_t *nshared)
2629{
Max Reitz2519f542020-05-13 13:05:29 +02002630 if (role & BDRV_CHILD_FILTERED) {
2631 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2632 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002633 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002634 perm, shared, nperm, nshared);
2635 } else if (role & BDRV_CHILD_COW) {
2636 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002637 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002638 perm, shared, nperm, nshared);
2639 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002640 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002641 perm, shared, nperm, nshared);
2642 } else {
2643 g_assert_not_reached();
2644 }
2645}
2646
Max Reitz7b1d9c42019-11-08 13:34:51 +01002647uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2648{
2649 static const uint64_t permissions[] = {
2650 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2651 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2652 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2653 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2654 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2655 };
2656
2657 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2658 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2659
2660 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2661
2662 return permissions[qapi_perm];
2663}
2664
Kevin Wolf8ee03992017-03-06 13:45:28 +01002665static void bdrv_replace_child_noperm(BdrvChild *child,
2666 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002667{
2668 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002669 int new_bs_quiesce_counter;
2670 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002671
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002672 assert(!child->frozen);
2673
Fam Zhengbb2614e2017-04-07 14:54:10 +08002674 if (old_bs && new_bs) {
2675 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2676 }
Max Reitzdebc2922019-07-22 15:33:44 +02002677
2678 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2679 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2680
2681 /*
2682 * If the new child node is drained but the old one was not, flush
2683 * all outstanding requests to the old child node.
2684 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002685 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002686 bdrv_parent_drained_begin_single(child, true);
2687 drain_saldo--;
2688 }
2689
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002690 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002691 /* Detach first so that the recursive drain sections coming from @child
2692 * are already gone and we only end the drain sections that came from
2693 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002694 if (child->klass->detach) {
2695 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002696 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002697 QLIST_REMOVE(child, next_parent);
2698 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002699
2700 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002701
2702 if (new_bs) {
2703 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002704
2705 /*
2706 * Detaching the old node may have led to the new node's
2707 * quiesce_counter having been decreased. Not a problem, we
2708 * just need to recognize this here and then invoke
2709 * drained_end appropriately more often.
2710 */
2711 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2712 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002713
Kevin Wolfd736f112017-12-18 16:05:48 +01002714 /* Attach only after starting new drained sections, so that recursive
2715 * drain sections coming from @child don't get an extra .drained_begin
2716 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002717 if (child->klass->attach) {
2718 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002719 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002720 }
Max Reitzdebc2922019-07-22 15:33:44 +02002721
2722 /*
2723 * If the old child node was drained but the new one is not, allow
2724 * requests to come in only after the new node has been attached.
2725 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002726 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002727 bdrv_parent_drained_end_single(child);
2728 drain_saldo++;
2729 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002730}
2731
Kevin Wolf466787f2017-03-08 14:44:07 +01002732/*
2733 * Updates @child to change its reference to point to @new_bs, including
zhaolichange3a6e0d2020-09-17 15:50:20 +08002734 * checking and applying the necessary permission updates both to the old node
Kevin Wolf466787f2017-03-08 14:44:07 +01002735 * and to @new_bs.
2736 *
2737 * NULL is passed as @new_bs for removing the reference before freeing @child.
2738 *
2739 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2740 * function uses bdrv_set_perm() to update the permissions according to the new
2741 * reference that @new_bs gets.
Max Reitz7b99a262019-06-12 16:07:11 +02002742 *
2743 * Callers must ensure that child->frozen is false.
Kevin Wolf466787f2017-03-08 14:44:07 +01002744 */
2745static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
Kevin Wolf8ee03992017-03-06 13:45:28 +01002746{
2747 BlockDriverState *old_bs = child->bs;
Kevin Wolf8ee03992017-03-06 13:45:28 +01002748
Max Reitz7b99a262019-06-12 16:07:11 +02002749 /* Asserts that child->frozen == false */
Kevin Wolf8aecf1d2017-08-03 17:02:57 +02002750 bdrv_replace_child_noperm(child, new_bs);
2751
Max Reitz87ace5f2019-05-22 19:03:49 +02002752 /*
2753 * Start with the new node's permissions. If @new_bs is a (direct
2754 * or indirect) child of @old_bs, we must complete the permission
2755 * update on @new_bs before we loosen the restrictions on @old_bs.
2756 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2757 * updating the permissions of @new_bs, and thus not purely loosen
2758 * restrictions.
2759 */
2760 if (new_bs) {
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03002761 bdrv_set_perm(new_bs);
Max Reitz87ace5f2019-05-22 19:03:49 +02002762 }
2763
Kevin Wolf8ee03992017-03-06 13:45:28 +01002764 if (old_bs) {
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03002765 /*
2766 * Update permissions for old node. We're just taking a parent away, so
2767 * we're loosening restrictions. Errors of permission update are not
2768 * fatal in this case, ignore them.
2769 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002770 bdrv_refresh_perms(old_bs, NULL);
Kevin Wolfad943dc2019-04-24 18:04:42 +02002771
2772 /* When the parent requiring a non-default AioContext is removed, the
2773 * node moves back to the main AioContext */
2774 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
Kevin Wolf8ee03992017-03-06 13:45:28 +01002775 }
Kevin Wolff54120f2014-05-26 11:09:59 +02002776}
2777
Alberto Garciab441dc72019-05-13 16:46:18 +03002778/*
2779 * This function steals the reference to child_bs from the caller.
2780 * That reference is later dropped by bdrv_root_unref_child().
2781 *
2782 * On failure NULL is returned, errp is set and the reference to
2783 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02002784 *
2785 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2786 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03002787 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01002788BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2789 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02002790 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002791 BdrvChildRole child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002792 uint64_t perm, uint64_t shared_perm,
2793 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02002794{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002795 BdrvChild *child;
Kevin Wolf132ada82019-04-24 17:41:46 +02002796 Error *local_err = NULL;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002797 int ret;
Vladimir Sementsov-Ogievskiy228ca372021-04-28 18:17:34 +03002798 AioContext *ctx;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002799
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03002800 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002801 if (ret < 0) {
Kevin Wolf33a610c2016-12-15 13:04:20 +01002802 bdrv_abort_perm_update(child_bs);
Alberto Garciab441dc72019-05-13 16:46:18 +03002803 bdrv_unref(child_bs);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002804 return NULL;
2805 }
2806
2807 child = g_new(BdrvChild, 1);
Kevin Wolfdf581792015-06-15 11:53:47 +02002808 *child = (BdrvChild) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002809 .bs = NULL,
2810 .name = g_strdup(child_name),
Max Reitzbd86fb92020-05-13 13:05:13 +02002811 .klass = child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002812 .role = child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002813 .perm = perm,
2814 .shared_perm = shared_perm,
2815 .opaque = opaque,
Kevin Wolfdf581792015-06-15 11:53:47 +02002816 };
2817
Vladimir Sementsov-Ogievskiy228ca372021-04-28 18:17:34 +03002818 ctx = bdrv_child_get_parent_aio_context(child);
2819
Kevin Wolf132ada82019-04-24 17:41:46 +02002820 /* If the AioContexts don't match, first try to move the subtree of
2821 * child_bs into the AioContext of the new parent. If this doesn't work,
2822 * try moving the parent into the AioContext of child_bs instead. */
2823 if (bdrv_get_aio_context(child_bs) != ctx) {
2824 ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
Max Reitzbd86fb92020-05-13 13:05:13 +02002825 if (ret < 0 && child_class->can_set_aio_ctx) {
Philippe Mathieu-Daudé0beab812020-02-18 10:43:52 +01002826 GSList *ignore = g_slist_prepend(NULL, child);
Kevin Wolf132ada82019-04-24 17:41:46 +02002827 ctx = bdrv_get_aio_context(child_bs);
Max Reitzbd86fb92020-05-13 13:05:13 +02002828 if (child_class->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
Kevin Wolf132ada82019-04-24 17:41:46 +02002829 error_free(local_err);
2830 ret = 0;
2831 g_slist_free(ignore);
Philippe Mathieu-Daudé0beab812020-02-18 10:43:52 +01002832 ignore = g_slist_prepend(NULL, child);
Max Reitzbd86fb92020-05-13 13:05:13 +02002833 child_class->set_aio_ctx(child, ctx, &ignore);
Kevin Wolf132ada82019-04-24 17:41:46 +02002834 }
2835 g_slist_free(ignore);
2836 }
2837 if (ret < 0) {
2838 error_propagate(errp, local_err);
2839 g_free(child);
2840 bdrv_abort_perm_update(child_bs);
Vladimir Sementsov-Ogievskiy7a26df22020-03-24 18:59:21 +03002841 bdrv_unref(child_bs);
Kevin Wolf132ada82019-04-24 17:41:46 +02002842 return NULL;
2843 }
2844 }
2845
Kevin Wolf33a610c2016-12-15 13:04:20 +01002846 /* This performs the matching bdrv_set_perm() for the above check. */
Kevin Wolf466787f2017-03-08 14:44:07 +01002847 bdrv_replace_child(child, child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02002848
2849 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02002850}
2851
Alberto Garciab441dc72019-05-13 16:46:18 +03002852/*
2853 * This function transfers the reference to child_bs from the caller
2854 * to parent_bs. That reference is later dropped by parent_bs on
2855 * bdrv_close() or if someone calls bdrv_unref_child().
2856 *
2857 * On failure NULL is returned, errp is set and the reference to
2858 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02002859 *
2860 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2861 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03002862 */
Wen Congyang98292c62016-05-10 15:36:38 +08002863BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2864 BlockDriverState *child_bs,
2865 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02002866 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002867 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002868 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01002869{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002870 BdrvChild *child;
Kevin Wolff68c5982016-12-20 15:51:12 +01002871 uint64_t perm, shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002872
Kevin Wolff68c5982016-12-20 15:51:12 +01002873 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2874
2875 assert(parent_bs->drv);
Max Reitze5d8a402020-05-13 13:05:44 +02002876 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002877 perm, shared_perm, &perm, &shared_perm);
Kevin Wolff68c5982016-12-20 15:51:12 +01002878
Max Reitzbd86fb92020-05-13 13:05:13 +02002879 child = bdrv_root_attach_child(child_bs, child_name, child_class,
Vladimir Sementsov-Ogievskiy228ca372021-04-28 18:17:34 +03002880 child_role, perm, shared_perm, parent_bs,
2881 errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002882 if (child == NULL) {
2883 return NULL;
2884 }
2885
Kevin Wolff21d96d2016-03-08 13:47:46 +01002886 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2887 return child;
2888}
2889
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02002890static void bdrv_detach_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02002891{
Stefan Hajnoczi195ed8c2020-02-14 17:17:10 +00002892 QLIST_SAFE_REMOVE(child, next);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002893
Kevin Wolf466787f2017-03-08 14:44:07 +01002894 bdrv_replace_child(child, NULL);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002895
Kevin Wolf260fecf2015-04-27 13:46:22 +02002896 g_free(child->name);
Kevin Wolf33a60402015-06-15 13:51:04 +02002897 g_free(child);
2898}
2899
Max Reitz7b99a262019-06-12 16:07:11 +02002900/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01002901void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02002902{
Kevin Wolf779020c2015-10-13 14:09:44 +02002903 BlockDriverState *child_bs;
2904
Kevin Wolff21d96d2016-03-08 13:47:46 +01002905 child_bs = child->bs;
2906 bdrv_detach_child(child);
2907 bdrv_unref(child_bs);
2908}
2909
Max Reitz3cf746b2019-07-03 19:28:07 +02002910/**
2911 * Clear all inherits_from pointers from children and grandchildren of
2912 * @root that point to @root, where necessary.
2913 */
2914static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
Kevin Wolff21d96d2016-03-08 13:47:46 +01002915{
Max Reitz3cf746b2019-07-03 19:28:07 +02002916 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02002917
Max Reitz3cf746b2019-07-03 19:28:07 +02002918 if (child->bs->inherits_from == root) {
2919 /*
2920 * Remove inherits_from only when the last reference between root and
2921 * child->bs goes away.
2922 */
2923 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002924 if (c != child && c->bs == child->bs) {
2925 break;
2926 }
2927 }
2928 if (c == NULL) {
2929 child->bs->inherits_from = NULL;
2930 }
Kevin Wolf33a60402015-06-15 13:51:04 +02002931 }
2932
Max Reitz3cf746b2019-07-03 19:28:07 +02002933 QLIST_FOREACH(c, &child->bs->children, next) {
2934 bdrv_unset_inherits_from(root, c);
2935 }
2936}
2937
Max Reitz7b99a262019-06-12 16:07:11 +02002938/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02002939void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2940{
2941 if (child == NULL) {
2942 return;
2943 }
2944
2945 bdrv_unset_inherits_from(parent, child);
Kevin Wolff21d96d2016-03-08 13:47:46 +01002946 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02002947}
2948
Kevin Wolf5c8cab42016-02-24 15:13:35 +01002949
2950static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2951{
2952 BdrvChild *c;
2953 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02002954 if (c->klass->change_media) {
2955 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01002956 }
2957 }
2958}
2959
Alberto Garcia0065c452018-10-31 18:16:37 +02002960/* Return true if you can reach parent going through child->inherits_from
2961 * recursively. If parent or child are NULL, return false */
2962static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2963 BlockDriverState *parent)
2964{
2965 while (child && child != parent) {
2966 child = child->inherits_from;
2967 }
2968
2969 return child != NULL;
2970}
2971
Kevin Wolf5db15a52015-09-14 15:33:33 +02002972/*
Max Reitz25191e52020-05-13 13:05:33 +02002973 * Return the BdrvChildRole for @bs's backing child. bs->backing is
2974 * mostly used for COW backing children (role = COW), but also for
2975 * filtered children (role = FILTERED | PRIMARY).
2976 */
2977static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
2978{
2979 if (bs->drv && bs->drv->is_filter) {
2980 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
2981 } else {
2982 return BDRV_CHILD_COW;
2983 }
2984}
2985
2986/*
Max Reitz9ee413c2019-06-12 18:42:34 +02002987 * Sets the bs->backing link of a BDS. A new reference is created; callers
Kevin Wolf5db15a52015-09-14 15:33:33 +02002988 * which don't need their own reference any more must call bdrv_unref().
2989 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03002990int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2991 Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08002992{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03002993 int ret = 0;
Alberto Garcia0065c452018-10-31 18:16:37 +02002994 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2995 bdrv_inherits_from_recursive(backing_hd, bs);
2996
Max Reitz9ee413c2019-06-12 18:42:34 +02002997 if (bdrv_is_backing_chain_frozen(bs, child_bs(bs->backing), errp)) {
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03002998 return -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002999 }
3000
Kevin Wolf5db15a52015-09-14 15:33:33 +02003001 if (backing_hd) {
3002 bdrv_ref(backing_hd);
3003 }
Fam Zheng8d24cce2014-05-23 21:29:45 +08003004
Kevin Wolf760e0062015-06-17 14:55:21 +02003005 if (bs->backing) {
Max Reitz7b99a262019-06-12 16:07:11 +02003006 /* Cannot be frozen, we checked that above */
Kevin Wolf5db15a52015-09-14 15:33:33 +02003007 bdrv_unref_child(bs, bs->backing);
Vladimir Sementsov-Ogievskiy6e579632020-03-16 09:06:30 +03003008 bs->backing = NULL;
Fam Zheng826b6ca2014-05-23 21:29:47 +08003009 }
3010
Fam Zheng8d24cce2014-05-23 21:29:45 +08003011 if (!backing_hd) {
3012 goto out;
3013 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003014
Max Reitz25191e52020-05-13 13:05:33 +02003015 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_of_bds,
3016 bdrv_backing_role(bs), errp);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003017 if (!bs->backing) {
3018 ret = -EPERM;
3019 goto out;
3020 }
3021
Alberto Garcia0065c452018-10-31 18:16:37 +02003022 /* If backing_hd was already part of bs's backing chain, and
3023 * inherits_from pointed recursively to bs then let's update it to
3024 * point directly to bs (else it will become NULL). */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003025 if (update_inherits_from) {
Alberto Garcia0065c452018-10-31 18:16:37 +02003026 backing_hd->inherits_from = bs;
3027 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08003028
Fam Zheng8d24cce2014-05-23 21:29:45 +08003029out:
Kevin Wolf3baca892014-07-16 17:48:16 +02003030 bdrv_refresh_limits(bs, NULL);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03003031
3032 return ret;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003033}
3034
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003035/*
3036 * Opens the backing file for a BlockDriverState if not yet open
3037 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003038 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3039 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3040 * itself, all options starting with "${bdref_key}." are considered part of the
3041 * BlockdevRef.
3042 *
3043 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003044 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003045int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3046 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02003047{
Max Reitz6b6833c2019-02-01 20:29:15 +01003048 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003049 char *bdref_key_dot;
3050 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02003051 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01003052 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08003053 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003054 QDict *options;
3055 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003056 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003057
Kevin Wolf760e0062015-06-17 14:55:21 +02003058 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003059 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003060 }
3061
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003062 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003063 if (parent_options == NULL) {
3064 tmp_parent_options = qdict_new();
3065 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01003066 }
3067
Paolo Bonzini9156df12012-10-18 16:49:17 +02003068 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003069
3070 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3071 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3072 g_free(bdref_key_dot);
3073
Markus Armbruster129c7d12017-03-30 19:43:12 +02003074 /*
3075 * Caution: while qdict_get_try_str() is fine, getting non-string
3076 * types would require more care. When @parent_options come from
3077 * -blockdev or blockdev_add, its members are typed according to
3078 * the QAPI schema, but when they come from -drive, they're all
3079 * QString.
3080 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003081 reference = qdict_get_try_str(parent_options, bdref_key);
3082 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01003083 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02003084 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003085 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003086 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08003087 } else {
Max Reitz998c2012019-02-01 20:29:08 +01003088 if (qdict_size(options) == 0) {
3089 /* If the user specifies options that do not modify the
3090 * backing file's behavior, we might still consider it the
3091 * implicit backing file. But it's easier this way, and
3092 * just specifying some of the backing BDS's options is
3093 * only possible with -drive anyway (otherwise the QAPI
3094 * schema forces the user to specify everything). */
3095 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3096 }
3097
Max Reitz6b6833c2019-02-01 20:29:15 +01003098 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01003099 if (local_err) {
3100 ret = -EINVAL;
3101 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003102 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01003103 goto free_exit;
3104 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02003105 }
3106
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003107 if (!bs->drv || !bs->drv->supports_backing) {
3108 ret = -EINVAL;
3109 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003110 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02003111 goto free_exit;
3112 }
3113
Peter Krempa6bff5972017-10-12 16:14:10 +02003114 if (!reference &&
3115 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05003116 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02003117 }
3118
Max Reitz6b6833c2019-02-01 20:29:15 +01003119 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02003120 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02003121 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02003122 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003123 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02003124 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003125 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003126 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003127
Max Reitz998c2012019-02-01 20:29:08 +01003128 if (implicit_backing) {
3129 bdrv_refresh_filename(backing_hd);
3130 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3131 backing_hd->filename);
3132 }
3133
Kevin Wolf5db15a52015-09-14 15:33:33 +02003134 /* Hook up the backing file link; drop our reference, bs owns the
3135 * backing_hd reference now */
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003136 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003137 bdrv_unref(backing_hd);
Vladimir Sementsov-Ogievskiydc9c10a2021-02-02 15:49:47 +03003138 if (ret < 0) {
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003139 goto free_exit;
3140 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003141
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003142 qdict_del(parent_options, bdref_key);
3143
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003144free_exit:
3145 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003146 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003147 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003148}
3149
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003150static BlockDriverState *
3151bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003152 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003153 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003154{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003155 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003156 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003157 char *bdref_key_dot;
3158 const char *reference;
3159
Max Reitzbd86fb92020-05-13 13:05:13 +02003160 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003161
Max Reitzda557aa2013-12-20 19:28:11 +01003162 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3163 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3164 g_free(bdref_key_dot);
3165
Markus Armbruster129c7d12017-03-30 19:43:12 +02003166 /*
3167 * Caution: while qdict_get_try_str() is fine, getting non-string
3168 * types would require more care. When @options come from
3169 * -blockdev or blockdev_add, its members are typed according to
3170 * the QAPI schema, but when they come from -drive, they're all
3171 * QString.
3172 */
Max Reitzda557aa2013-12-20 19:28:11 +01003173 reference = qdict_get_try_str(options, bdref_key);
3174 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003175 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003176 error_setg(errp, "A block device must be specified for \"%s\"",
3177 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003178 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003179 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003180 goto done;
3181 }
3182
Max Reitz5b363932016-05-17 16:41:31 +02003183 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003184 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003185 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003186 goto done;
3187 }
3188
Max Reitzda557aa2013-12-20 19:28:11 +01003189done:
3190 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003191 return bs;
3192}
3193
3194/*
3195 * Opens a disk image whose options are given as BlockdevRef in another block
3196 * device's options.
3197 *
3198 * If allow_none is true, no image will be opened if filename is false and no
3199 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3200 *
3201 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3202 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3203 * itself, all options starting with "${bdref_key}." are considered part of the
3204 * BlockdevRef.
3205 *
3206 * The BlockdevRef will be removed from the options QDict.
3207 */
3208BdrvChild *bdrv_open_child(const char *filename,
3209 QDict *options, const char *bdref_key,
3210 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003211 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003212 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003213 bool allow_none, Error **errp)
3214{
3215 BlockDriverState *bs;
3216
Max Reitzbd86fb92020-05-13 13:05:13 +02003217 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003218 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003219 if (bs == NULL) {
3220 return NULL;
3221 }
3222
Max Reitz258b7762020-05-13 13:05:15 +02003223 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3224 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003225}
3226
Max Reitzbd86fb92020-05-13 13:05:13 +02003227/*
3228 * TODO Future callers may need to specify parent/child_class in order for
3229 * option inheritance to work. Existing callers use it for the root node.
3230 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003231BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3232{
3233 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003234 QObject *obj = NULL;
3235 QDict *qdict = NULL;
3236 const char *reference = NULL;
3237 Visitor *v = NULL;
3238
3239 if (ref->type == QTYPE_QSTRING) {
3240 reference = ref->u.reference;
3241 } else {
3242 BlockdevOptions *options = &ref->u.definition;
3243 assert(ref->type == QTYPE_QDICT);
3244
3245 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003246 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003247 visit_complete(v, &obj);
3248
Max Reitz7dc847e2018-02-24 16:40:29 +01003249 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003250 qdict_flatten(qdict);
3251
3252 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3253 * compatibility with other callers) rather than what we want as the
3254 * real defaults. Apply the defaults here instead. */
3255 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3256 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3257 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003258 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3259
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003260 }
3261
Max Reitz272c02e2020-05-13 13:05:17 +02003262 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003263 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003264 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003265 visit_free(v);
3266 return bs;
3267}
3268
Max Reitz66836182016-05-17 16:41:27 +02003269static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3270 int flags,
3271 QDict *snapshot_options,
3272 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003273{
3274 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003275 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003276 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003277 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003278 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003279 int ret;
3280
3281 /* if snapshot, we create a temporary backing file and open it
3282 instead of opening 'filename' directly */
3283
3284 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003285 total_size = bdrv_getlength(bs);
3286 if (total_size < 0) {
3287 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003288 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003289 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003290
3291 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003292 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003293 if (ret < 0) {
3294 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003295 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003296 }
3297
Max Reitzef810432014-12-02 18:32:42 +01003298 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003299 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003300 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003301 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003302 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003303 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003304 error_prepend(errp, "Could not create temporary overlay '%s': ",
3305 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003306 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003307 }
3308
Kevin Wolf73176be2016-03-07 13:02:15 +01003309 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003310 qdict_put_str(snapshot_options, "file.driver", "file");
3311 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3312 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003313
Max Reitz5b363932016-05-17 16:41:31 +02003314 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003315 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003316 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003317 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003318 }
3319
Vladimir Sementsov-Ogievskiy934aee12021-02-02 15:49:44 +03003320 ret = bdrv_append(bs_snapshot, bs, errp);
3321 if (ret < 0) {
Eric Blakeff6ed712017-04-27 16:58:18 -05003322 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003323 goto out;
3324 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003325
3326out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003327 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003328 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003329 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003330}
3331
Max Reitzda557aa2013-12-20 19:28:11 +01003332/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003333 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003334 *
3335 * options is a QDict of options to pass to the block drivers, or NULL for an
3336 * empty set of options. The reference to the QDict belongs to the block layer
3337 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003338 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003339 *
3340 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3341 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003342 *
3343 * The reference parameter may be used to specify an existing block device which
3344 * should be opened. If specified, neither options nor a filename may be given,
3345 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003346 */
Max Reitz5b363932016-05-17 16:41:31 +02003347static BlockDriverState *bdrv_open_inherit(const char *filename,
3348 const char *reference,
3349 QDict *options, int flags,
3350 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003351 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003352 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003353 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003354{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003355 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003356 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003357 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003358 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003359 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003360 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003361 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003362 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003363 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003364 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003365
Max Reitzbd86fb92020-05-13 13:05:13 +02003366 assert(!child_class || !flags);
3367 assert(!child_class == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01003368
Max Reitzddf56362014-02-18 18:33:06 +01003369 if (reference) {
3370 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003371 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003372
Max Reitzddf56362014-02-18 18:33:06 +01003373 if (filename || options_non_empty) {
3374 error_setg(errp, "Cannot reference an existing block device with "
3375 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003376 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003377 }
3378
3379 bs = bdrv_lookup_bs(reference, reference, errp);
3380 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003381 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003382 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003383
Max Reitzddf56362014-02-18 18:33:06 +01003384 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003385 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003386 }
3387
Max Reitz5b363932016-05-17 16:41:31 +02003388 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003389
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003390 /* NULL means an empty set of options */
3391 if (options == NULL) {
3392 options = qdict_new();
3393 }
3394
Kevin Wolf145f5982015-05-08 16:15:03 +02003395 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003396 parse_json_protocol(options, &filename, &local_err);
3397 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003398 goto fail;
3399 }
3400
Kevin Wolf145f5982015-05-08 16:15:03 +02003401 bs->explicit_options = qdict_clone_shallow(options);
3402
Max Reitzbd86fb92020-05-13 13:05:13 +02003403 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003404 bool parent_is_format;
3405
3406 if (parent->drv) {
3407 parent_is_format = parent->drv->is_format;
3408 } else {
3409 /*
3410 * parent->drv is not set yet because this node is opened for
3411 * (potential) format probing. That means that @parent is going
3412 * to be a format node.
3413 */
3414 parent_is_format = true;
3415 }
3416
Kevin Wolfbddcec32015-04-09 18:47:50 +02003417 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003418 child_class->inherit_options(child_role, parent_is_format,
3419 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003420 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003421 }
3422
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003423 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003424 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003425 goto fail;
3426 }
3427
Markus Armbruster129c7d12017-03-30 19:43:12 +02003428 /*
3429 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3430 * Caution: getting a boolean member of @options requires care.
3431 * When @options come from -blockdev or blockdev_add, members are
3432 * typed according to the QAPI schema, but when they come from
3433 * -drive, they're all QString.
3434 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003435 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3436 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3437 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3438 } else {
3439 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003440 }
3441
3442 if (flags & BDRV_O_SNAPSHOT) {
3443 snapshot_options = qdict_new();
3444 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3445 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003446 /* Let bdrv_backing_options() override "read-only" */
3447 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003448 bdrv_inherited_options(BDRV_CHILD_COW, true,
3449 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003450 }
3451
Kevin Wolf62392eb2015-04-24 16:38:02 +02003452 bs->open_flags = flags;
3453 bs->options = options;
3454 options = qdict_clone_shallow(options);
3455
Kevin Wolf76c591b2014-06-04 14:19:44 +02003456 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003457 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003458 drvname = qdict_get_try_str(options, "driver");
3459 if (drvname) {
3460 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003461 if (!drv) {
3462 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003463 goto fail;
3464 }
3465 }
3466
3467 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003468
Markus Armbruster129c7d12017-03-30 19:43:12 +02003469 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003470 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003471 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3472 (backing && *backing == '\0'))
3473 {
Max Reitz4f7be282018-02-24 16:40:33 +01003474 if (backing) {
3475 warn_report("Use of \"backing\": \"\" is deprecated; "
3476 "use \"backing\": null instead");
3477 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003478 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003479 qdict_del(bs->explicit_options, "backing");
3480 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003481 qdict_del(options, "backing");
3482 }
3483
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003484 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003485 * probing, the block drivers will do their own bdrv_open_child() for the
3486 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003487 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003488 BlockDriverState *file_bs;
3489
3490 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003491 &child_of_bds, BDRV_CHILD_IMAGE,
3492 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003493 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003494 goto fail;
3495 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003496 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003497 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3498 * looking at the header to guess the image format. This works even
3499 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003500 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003501 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003502 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003503 if (local_err) {
3504 goto fail;
3505 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003506
Eric Blake46f5ac22017-04-27 16:58:17 -05003507 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003508 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003509 }
3510
Kevin Wolf76c591b2014-06-04 14:19:44 +02003511 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003512 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003513 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003514 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003515 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003516 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003517 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003518 /*
3519 * This option update would logically belong in bdrv_fill_options(),
3520 * but we first need to open bs->file for the probing to work, while
3521 * opening bs->file already requires the (mostly) final set of options
3522 * so that cache mode etc. can be inherited.
3523 *
3524 * Adding the driver later is somewhat ugly, but it's not an option
3525 * that would ever be inherited, so it's correct. We just need to make
3526 * sure to update both bs->options (which has the full effective
3527 * options for bs) and options (which has file.* already removed).
3528 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003529 qdict_put_str(bs->options, "driver", drv->format_name);
3530 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003531 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003532 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003533 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003534 }
3535
Max Reitz53a29512015-03-19 14:53:16 -04003536 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3537 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3538 /* file must be NULL if a protocol BDS is about to be created
3539 * (the inverse results in an error message from bdrv_open_common()) */
3540 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3541
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003542 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003543 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003544 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003545 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003546 }
3547
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003548 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003549 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003550 file = NULL;
3551 }
3552
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003553 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003554 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003555 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003556 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003557 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003558 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003559 }
3560
Alberto Garcia50196d72018-09-06 12:37:03 +03003561 /* Remove all children options and references
3562 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003563 QLIST_FOREACH(child, &bs->children, next) {
3564 char *child_key_dot;
3565 child_key_dot = g_strdup_printf("%s.", child->name);
3566 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3567 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003568 qdict_del(bs->explicit_options, child->name);
3569 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003570 g_free(child_key_dot);
3571 }
3572
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003573 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003574 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003575 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003576 if (flags & BDRV_O_PROTOCOL) {
3577 error_setg(errp, "Block protocol '%s' doesn't support the option "
3578 "'%s'", drv->format_name, entry->key);
3579 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003580 error_setg(errp,
3581 "Block format '%s' does not support the option '%s'",
3582 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003583 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003584
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003585 goto close_and_fail;
3586 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003587
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003588 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003589
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003590 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003591 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003592
3593 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3594 * temporary snapshot afterwards. */
3595 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003596 BlockDriverState *snapshot_bs;
3597 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3598 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003599 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003600 if (local_err) {
3601 goto close_and_fail;
3602 }
Max Reitz5b363932016-05-17 16:41:31 +02003603 /* We are not going to return bs but the overlay on top of it
3604 * (snapshot_bs); thus, we have to drop the strong reference to bs
3605 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3606 * though, because the overlay still has a reference to it. */
3607 bdrv_unref(bs);
3608 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003609 }
3610
Max Reitz5b363932016-05-17 16:41:31 +02003611 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003612
Kevin Wolf8bfea152014-04-11 19:16:36 +02003613fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003614 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003615 qobject_unref(snapshot_options);
3616 qobject_unref(bs->explicit_options);
3617 qobject_unref(bs->options);
3618 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003619 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003620 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003621 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003622 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003623 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003624
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003625close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02003626 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003627 qobject_unref(snapshot_options);
3628 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003629 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003630 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003631}
3632
Max Reitz5b363932016-05-17 16:41:31 +02003633BlockDriverState *bdrv_open(const char *filename, const char *reference,
3634 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02003635{
Max Reitz5b363932016-05-17 16:41:31 +02003636 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02003637 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003638}
3639
Alberto Garciafaf116b2019-03-12 18:48:49 +02003640/* Return true if the NULL-terminated @list contains @str */
3641static bool is_str_in_list(const char *str, const char *const *list)
3642{
3643 if (str && list) {
3644 int i;
3645 for (i = 0; list[i] != NULL; i++) {
3646 if (!strcmp(str, list[i])) {
3647 return true;
3648 }
3649 }
3650 }
3651 return false;
3652}
3653
3654/*
3655 * Check that every option set in @bs->options is also set in
3656 * @new_opts.
3657 *
3658 * Options listed in the common_options list and in
3659 * @bs->drv->mutable_opts are skipped.
3660 *
3661 * Return 0 on success, otherwise return -EINVAL and set @errp.
3662 */
3663static int bdrv_reset_options_allowed(BlockDriverState *bs,
3664 const QDict *new_opts, Error **errp)
3665{
3666 const QDictEntry *e;
3667 /* These options are common to all block drivers and are handled
3668 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3669 const char *const common_options[] = {
3670 "node-name", "discard", "cache.direct", "cache.no-flush",
3671 "read-only", "auto-read-only", "detect-zeroes", NULL
3672 };
3673
3674 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3675 if (!qdict_haskey(new_opts, e->key) &&
3676 !is_str_in_list(e->key, common_options) &&
3677 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3678 error_setg(errp, "Option '%s' cannot be reset "
3679 "to its default value", e->key);
3680 return -EINVAL;
3681 }
3682 }
3683
3684 return 0;
3685}
3686
Jeff Codye971aa12012-09-20 15:13:19 -04003687/*
Alberto Garciacb828c32019-03-12 18:48:47 +02003688 * Returns true if @child can be reached recursively from @bs
3689 */
3690static bool bdrv_recurse_has_child(BlockDriverState *bs,
3691 BlockDriverState *child)
3692{
3693 BdrvChild *c;
3694
3695 if (bs == child) {
3696 return true;
3697 }
3698
3699 QLIST_FOREACH(c, &bs->children, next) {
3700 if (bdrv_recurse_has_child(c->bs, child)) {
3701 return true;
3702 }
3703 }
3704
3705 return false;
3706}
3707
3708/*
Jeff Codye971aa12012-09-20 15:13:19 -04003709 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3710 * reopen of multiple devices.
3711 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003712 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04003713 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3714 * be created and initialized. This newly created BlockReopenQueue should be
3715 * passed back in for subsequent calls that are intended to be of the same
3716 * atomic 'set'.
3717 *
3718 * bs is the BlockDriverState to add to the reopen queue.
3719 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003720 * options contains the changed options for the associated bs
3721 * (the BlockReopenQueue takes ownership)
3722 *
Jeff Codye971aa12012-09-20 15:13:19 -04003723 * flags contains the open flags for the associated bs
3724 *
3725 * returns a pointer to bs_queue, which is either the newly allocated
3726 * bs_queue, or the existing bs_queue being used.
3727 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01003728 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04003729 */
Kevin Wolf28518102015-05-08 17:07:31 +02003730static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3731 BlockDriverState *bs,
3732 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003733 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02003734 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02003735 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02003736 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02003737 int parent_flags,
3738 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04003739{
3740 assert(bs != NULL);
3741
3742 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02003743 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003744 QDict *old_options, *explicit_options, *options_copy;
3745 int flags;
3746 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02003747
Kevin Wolf1a63a902017-12-06 20:24:44 +01003748 /* Make sure that the caller remembered to use a drained section. This is
3749 * important to avoid graph changes between the recursive queuing here and
3750 * bdrv_reopen_multiple(). */
3751 assert(bs->quiesce_counter > 0);
3752
Jeff Codye971aa12012-09-20 15:13:19 -04003753 if (bs_queue == NULL) {
3754 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003755 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04003756 }
3757
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003758 if (!options) {
3759 options = qdict_new();
3760 }
3761
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003762 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003763 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003764 if (bs == bs_entry->state.bs) {
3765 break;
3766 }
3767 }
3768
Kevin Wolf28518102015-05-08 17:07:31 +02003769 /*
3770 * Precedence of options:
3771 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003772 * 2. Retained from explicitly set options of bs
3773 * 3. Inherited from parent node
3774 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02003775 */
3776
Kevin Wolf145f5982015-05-08 16:15:03 +02003777 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02003778 if (bs_entry || keep_old_opts) {
3779 old_options = qdict_clone_shallow(bs_entry ?
3780 bs_entry->state.explicit_options :
3781 bs->explicit_options);
3782 bdrv_join_options(bs, options, old_options);
3783 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003784 }
Kevin Wolf145f5982015-05-08 16:15:03 +02003785
3786 explicit_options = qdict_clone_shallow(options);
3787
Kevin Wolf28518102015-05-08 17:07:31 +02003788 /* Inherit from parent node */
3789 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003790 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003791 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02003792 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003793 } else {
3794 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02003795 }
3796
Alberto Garcia077e8e22019-03-12 18:48:44 +02003797 if (keep_old_opts) {
3798 /* Old values are used for options that aren't set yet */
3799 old_options = qdict_clone_shallow(bs->options);
3800 bdrv_join_options(bs, options, old_options);
3801 qobject_unref(old_options);
3802 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003803
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003804 /* We have the final set of options so let's update the flags */
3805 options_copy = qdict_clone_shallow(options);
3806 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3807 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3808 update_flags_from_options(&flags, opts);
3809 qemu_opts_del(opts);
3810 qobject_unref(options_copy);
3811
Kevin Wolffd452022017-08-03 17:02:59 +02003812 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02003813 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02003814 if (flags & BDRV_O_RDWR) {
3815 flags |= BDRV_O_ALLOW_RDWR;
3816 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02003817
Kevin Wolf1857c972017-09-14 14:53:46 +02003818 if (!bs_entry) {
3819 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003820 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02003821 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003822 qobject_unref(bs_entry->state.options);
3823 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02003824 }
3825
3826 bs_entry->state.bs = bs;
3827 bs_entry->state.options = options;
3828 bs_entry->state.explicit_options = explicit_options;
3829 bs_entry->state.flags = flags;
3830
Kevin Wolf30450252017-07-03 17:07:35 +02003831 /* This needs to be overwritten in bdrv_reopen_prepare() */
3832 bs_entry->state.perm = UINT64_MAX;
3833 bs_entry->state.shared_perm = 0;
3834
Alberto Garcia85466322019-03-12 18:48:45 +02003835 /*
3836 * If keep_old_opts is false then it means that unspecified
3837 * options must be reset to their original value. We don't allow
3838 * resetting 'backing' but we need to know if the option is
3839 * missing in order to decide if we have to return an error.
3840 */
3841 if (!keep_old_opts) {
3842 bs_entry->state.backing_missing =
3843 !qdict_haskey(options, "backing") &&
3844 !qdict_haskey(options, "backing.driver");
3845 }
3846
Kevin Wolf67251a32015-04-09 18:54:04 +02003847 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02003848 QDict *new_child_options = NULL;
3849 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02003850
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02003851 /* reopen can only change the options of block devices that were
3852 * implicitly created and inherited options. For other (referenced)
3853 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02003854 if (child->bs->inherits_from != bs) {
3855 continue;
3856 }
3857
Alberto Garcia85466322019-03-12 18:48:45 +02003858 /* Check if the options contain a child reference */
3859 if (qdict_haskey(options, child->name)) {
3860 const char *childref = qdict_get_try_str(options, child->name);
3861 /*
3862 * The current child must not be reopened if the child
3863 * reference is null or points to a different node.
3864 */
3865 if (g_strcmp0(childref, child->bs->node_name)) {
3866 continue;
3867 }
3868 /*
3869 * If the child reference points to the current child then
3870 * reopen it with its existing set of options (note that
3871 * it can still inherit new options from the parent).
3872 */
3873 child_keep_old = true;
3874 } else {
3875 /* Extract child options ("child-name.*") */
3876 char *child_key_dot = g_strdup_printf("%s.", child->name);
3877 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3878 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3879 g_free(child_key_dot);
3880 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02003881
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003882 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02003883 child->klass, child->role, bs->drv->is_format,
3884 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04003885 }
3886
Jeff Codye971aa12012-09-20 15:13:19 -04003887 return bs_queue;
3888}
3889
Kevin Wolf28518102015-05-08 17:07:31 +02003890BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3891 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02003892 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02003893{
Max Reitz3cdc69d2020-05-13 13:05:18 +02003894 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
3895 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02003896}
3897
Jeff Codye971aa12012-09-20 15:13:19 -04003898/*
3899 * Reopen multiple BlockDriverStates atomically & transactionally.
3900 *
3901 * The queue passed in (bs_queue) must have been built up previous
3902 * via bdrv_reopen_queue().
3903 *
3904 * Reopens all BDS specified in the queue, with the appropriate
3905 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02003906 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04003907 * data cleaned up.
3908 *
3909 * If all devices prepare successfully, then the changes are committed
3910 * to all devices.
3911 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01003912 * All affected nodes must be drained between bdrv_reopen_queue() and
3913 * bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04003914 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02003915int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04003916{
3917 int ret = -1;
3918 BlockReopenQueueEntry *bs_entry, *next;
Jeff Codye971aa12012-09-20 15:13:19 -04003919
3920 assert(bs_queue != NULL);
3921
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003922 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01003923 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolfa4615ab2019-03-05 16:51:13 +01003924 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
Jeff Codye971aa12012-09-20 15:13:19 -04003925 goto cleanup;
3926 }
3927 bs_entry->prepared = true;
3928 }
3929
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003930 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01003931 BDRVReopenState *state = &bs_entry->state;
3932 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03003933 state->shared_perm, NULL, errp);
Kevin Wolf69b736e2019-03-05 17:18:22 +01003934 if (ret < 0) {
3935 goto cleanup_perm;
3936 }
Alberto Garciacb828c32019-03-12 18:48:47 +02003937 /* Check if new_backing_bs would accept the new permissions */
3938 if (state->replace_backing_bs && state->new_backing_bs) {
3939 uint64_t nperm, nshared;
3940 bdrv_child_perm(state->bs, state->new_backing_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02003941 NULL, bdrv_backing_role(state->bs),
Max Reitz25191e52020-05-13 13:05:33 +02003942 bs_queue, state->perm, state->shared_perm,
Alberto Garciacb828c32019-03-12 18:48:47 +02003943 &nperm, &nshared);
3944 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03003945 nperm, nshared, NULL, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02003946 if (ret < 0) {
3947 goto cleanup_perm;
3948 }
3949 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01003950 bs_entry->perms_checked = true;
3951 }
3952
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03003953 /*
3954 * If we reach this point, we have success and just need to apply the
3955 * changes.
3956 *
3957 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3958 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3959 * children are usually goes after parents in reopen-queue, so go from last
3960 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04003961 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03003962 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Jeff Codye971aa12012-09-20 15:13:19 -04003963 bdrv_reopen_commit(&bs_entry->state);
3964 }
3965
3966 ret = 0;
Kevin Wolf69b736e2019-03-05 17:18:22 +01003967cleanup_perm:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003968 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01003969 BDRVReopenState *state = &bs_entry->state;
Jeff Codye971aa12012-09-20 15:13:19 -04003970
Kevin Wolf69b736e2019-03-05 17:18:22 +01003971 if (!bs_entry->perms_checked) {
3972 continue;
3973 }
3974
3975 if (ret == 0) {
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03003976 uint64_t perm, shared;
3977
3978 bdrv_get_cumulative_perm(state->bs, &perm, &shared);
3979 assert(perm == state->perm);
3980 assert(shared == state->shared_perm);
3981
3982 bdrv_set_perm(state->bs);
Kevin Wolf69b736e2019-03-05 17:18:22 +01003983 } else {
3984 bdrv_abort_perm_update(state->bs);
Alberto Garciacb828c32019-03-12 18:48:47 +02003985 if (state->replace_backing_bs && state->new_backing_bs) {
3986 bdrv_abort_perm_update(state->new_backing_bs);
3987 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01003988 }
3989 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01003990
3991 if (ret == 0) {
3992 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3993 BlockDriverState *bs = bs_entry->state.bs;
3994
3995 if (bs->drv->bdrv_reopen_commit_post)
3996 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
3997 }
3998 }
Jeff Codye971aa12012-09-20 15:13:19 -04003999cleanup:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004000 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Alberto Garcia1bab38e2018-06-29 14:37:01 +03004001 if (ret) {
4002 if (bs_entry->prepared) {
4003 bdrv_reopen_abort(&bs_entry->state);
4004 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004005 qobject_unref(bs_entry->state.explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004006 qobject_unref(bs_entry->state.options);
Jeff Codye971aa12012-09-20 15:13:19 -04004007 }
Alberto Garciacb828c32019-03-12 18:48:47 +02004008 if (bs_entry->state.new_backing_bs) {
4009 bdrv_unref(bs_entry->state.new_backing_bs);
4010 }
Jeff Codye971aa12012-09-20 15:13:19 -04004011 g_free(bs_entry);
4012 }
4013 g_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03004014
Jeff Codye971aa12012-09-20 15:13:19 -04004015 return ret;
4016}
4017
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004018int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4019 Error **errp)
4020{
4021 int ret;
4022 BlockReopenQueue *queue;
4023 QDict *opts = qdict_new();
4024
4025 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4026
4027 bdrv_subtree_drained_begin(bs);
Alberto Garcia077e8e22019-03-12 18:48:44 +02004028 queue = bdrv_reopen_queue(NULL, bs, opts, true);
Alberto Garcia5019aec2019-03-12 18:48:50 +02004029 ret = bdrv_reopen_multiple(queue, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02004030 bdrv_subtree_drained_end(bs);
4031
4032 return ret;
4033}
4034
Kevin Wolf30450252017-07-03 17:07:35 +02004035static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
4036 BdrvChild *c)
4037{
4038 BlockReopenQueueEntry *entry;
4039
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03004040 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf30450252017-07-03 17:07:35 +02004041 BlockDriverState *bs = entry->state.bs;
4042 BdrvChild *child;
4043
4044 QLIST_FOREACH(child, &bs->children, next) {
4045 if (child == c) {
4046 return entry;
4047 }
4048 }
4049 }
4050
4051 return NULL;
4052}
4053
4054static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
4055 uint64_t *perm, uint64_t *shared)
4056{
4057 BdrvChild *c;
4058 BlockReopenQueueEntry *parent;
4059 uint64_t cumulative_perms = 0;
4060 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
4061
4062 QLIST_FOREACH(c, &bs->parents, next_parent) {
4063 parent = find_parent_in_reopen_queue(q, c);
4064 if (!parent) {
4065 cumulative_perms |= c->perm;
4066 cumulative_shared_perms &= c->shared_perm;
4067 } else {
4068 uint64_t nperm, nshared;
4069
Max Reitze5d8a402020-05-13 13:05:44 +02004070 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
Kevin Wolf30450252017-07-03 17:07:35 +02004071 parent->state.perm, parent->state.shared_perm,
4072 &nperm, &nshared);
4073
4074 cumulative_perms |= nperm;
4075 cumulative_shared_perms &= nshared;
4076 }
4077 }
4078 *perm = cumulative_perms;
4079 *shared = cumulative_shared_perms;
4080}
Jeff Codye971aa12012-09-20 15:13:19 -04004081
Kevin Wolf1de6b452020-03-06 15:14:13 +01004082static bool bdrv_reopen_can_attach(BlockDriverState *parent,
4083 BdrvChild *child,
4084 BlockDriverState *new_child,
4085 Error **errp)
4086{
4087 AioContext *parent_ctx = bdrv_get_aio_context(parent);
4088 AioContext *child_ctx = bdrv_get_aio_context(new_child);
4089 GSList *ignore;
4090 bool ret;
4091
4092 ignore = g_slist_prepend(NULL, child);
4093 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
4094 g_slist_free(ignore);
4095 if (ret) {
4096 return ret;
4097 }
4098
4099 ignore = g_slist_prepend(NULL, child);
4100 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
4101 g_slist_free(ignore);
4102 return ret;
4103}
4104
Jeff Codye971aa12012-09-20 15:13:19 -04004105/*
Alberto Garciacb828c32019-03-12 18:48:47 +02004106 * Take a BDRVReopenState and check if the value of 'backing' in the
4107 * reopen_state->options QDict is valid or not.
4108 *
4109 * If 'backing' is missing from the QDict then return 0.
4110 *
4111 * If 'backing' contains the node name of the backing file of
4112 * reopen_state->bs then return 0.
4113 *
4114 * If 'backing' contains a different node name (or is null) then check
4115 * whether the current backing file can be replaced with the new one.
4116 * If that's the case then reopen_state->replace_backing_bs is set to
4117 * true and reopen_state->new_backing_bs contains a pointer to the new
4118 * backing BlockDriverState (or NULL).
4119 *
4120 * Return 0 on success, otherwise return < 0 and set @errp.
4121 */
4122static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
4123 Error **errp)
4124{
4125 BlockDriverState *bs = reopen_state->bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004126 BlockDriverState *overlay_bs, *below_bs, *new_backing_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004127 QObject *value;
4128 const char *str;
4129
4130 value = qdict_get(reopen_state->options, "backing");
4131 if (value == NULL) {
4132 return 0;
4133 }
4134
4135 switch (qobject_type(value)) {
4136 case QTYPE_QNULL:
4137 new_backing_bs = NULL;
4138 break;
4139 case QTYPE_QSTRING:
Markus Armbruster410f44f2020-12-11 18:11:42 +01004140 str = qstring_get_str(qobject_to(QString, value));
Alberto Garciacb828c32019-03-12 18:48:47 +02004141 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4142 if (new_backing_bs == NULL) {
4143 return -EINVAL;
4144 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4145 error_setg(errp, "Making '%s' a backing file of '%s' "
4146 "would create a cycle", str, bs->node_name);
4147 return -EINVAL;
4148 }
4149 break;
4150 default:
4151 /* 'backing' does not allow any other data type */
4152 g_assert_not_reached();
4153 }
4154
4155 /*
Kevin Wolf1de6b452020-03-06 15:14:13 +01004156 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4157 * bdrv_reopen_commit() won't fail.
Alberto Garciacb828c32019-03-12 18:48:47 +02004158 */
4159 if (new_backing_bs) {
Kevin Wolf1de6b452020-03-06 15:14:13 +01004160 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004161 return -EINVAL;
4162 }
4163 }
4164
4165 /*
Max Reitz1d42f482019-06-12 17:24:39 +02004166 * Ensure that @bs can really handle backing files, because we are
4167 * about to give it one (or swap the existing one)
4168 */
4169 if (bs->drv->is_filter) {
4170 /* Filters always have a file or a backing child */
4171 if (!bs->backing) {
4172 error_setg(errp, "'%s' is a %s filter node that does not support a "
4173 "backing child", bs->node_name, bs->drv->format_name);
4174 return -EINVAL;
4175 }
4176 } else if (!bs->drv->supports_backing) {
4177 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
4178 "files", bs->drv->format_name, bs->node_name);
4179 return -EINVAL;
4180 }
4181
4182 /*
Alberto Garciacb828c32019-03-12 18:48:47 +02004183 * Find the "actual" backing file by skipping all links that point
4184 * to an implicit node, if any (e.g. a commit filter node).
Max Reitz1d42f482019-06-12 17:24:39 +02004185 * We cannot use any of the bdrv_skip_*() functions here because
4186 * those return the first explicit node, while we are looking for
4187 * its overlay here.
Alberto Garciacb828c32019-03-12 18:48:47 +02004188 */
4189 overlay_bs = bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004190 for (below_bs = bdrv_filter_or_cow_bs(overlay_bs);
4191 below_bs && below_bs->implicit;
4192 below_bs = bdrv_filter_or_cow_bs(overlay_bs))
4193 {
4194 overlay_bs = below_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004195 }
4196
4197 /* If we want to replace the backing file we need some extra checks */
Max Reitz1d42f482019-06-12 17:24:39 +02004198 if (new_backing_bs != bdrv_filter_or_cow_bs(overlay_bs)) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004199 /* Check for implicit nodes between bs and its backing file */
4200 if (bs != overlay_bs) {
4201 error_setg(errp, "Cannot change backing link if '%s' has "
4202 "an implicit backing file", bs->node_name);
4203 return -EPERM;
4204 }
Max Reitz1d42f482019-06-12 17:24:39 +02004205 /*
4206 * Check if the backing link that we want to replace is frozen.
4207 * Note that
4208 * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4209 * because we know that overlay_bs == bs, and that @bs
4210 * either is a filter that uses ->backing or a COW format BDS
4211 * with bs->drv->supports_backing == true.
4212 */
4213 if (bdrv_is_backing_chain_frozen(overlay_bs,
4214 child_bs(overlay_bs->backing), errp))
4215 {
Alberto Garciacb828c32019-03-12 18:48:47 +02004216 return -EPERM;
4217 }
4218 reopen_state->replace_backing_bs = true;
4219 if (new_backing_bs) {
4220 bdrv_ref(new_backing_bs);
4221 reopen_state->new_backing_bs = new_backing_bs;
4222 }
4223 }
4224
4225 return 0;
4226}
4227
4228/*
Jeff Codye971aa12012-09-20 15:13:19 -04004229 * Prepares a BlockDriverState for reopen. All changes are staged in the
4230 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4231 * the block driver layer .bdrv_reopen_prepare()
4232 *
4233 * bs is the BlockDriverState to reopen
4234 * flags are the new open flags
4235 * queue is the reopen queue
4236 *
4237 * Returns 0 on success, non-zero on error. On error errp will be set
4238 * as well.
4239 *
4240 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4241 * It is the responsibility of the caller to then call the abort() or
4242 * commit() for any other BDS that have been left in a prepare() state
4243 *
4244 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004245static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4246 BlockReopenQueue *queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04004247{
4248 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004249 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004250 Error *local_err = NULL;
4251 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004252 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004253 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004254 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004255 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004256 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004257
4258 assert(reopen_state != NULL);
4259 assert(reopen_state->bs->drv != NULL);
4260 drv = reopen_state->bs->drv;
4261
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004262 /* This function and each driver's bdrv_reopen_prepare() remove
4263 * entries from reopen_state->options as they are processed, so
4264 * we need to make a copy of the original QDict. */
4265 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4266
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004267 /* Process generic block layer options */
4268 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004269 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004270 ret = -EINVAL;
4271 goto error;
4272 }
4273
Alberto Garciae6d79c42018-11-12 16:00:47 +02004274 /* This was already called in bdrv_reopen_queue_child() so the flags
4275 * are up-to-date. This time we simply want to remove the options from
4276 * QemuOpts in order to indicate that they have been processed. */
4277 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004278 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004279 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004280
Alberto Garcia415bbca2018-10-03 13:23:13 +03004281 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004282 if (discard != NULL) {
4283 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4284 error_setg(errp, "Invalid discard option");
4285 ret = -EINVAL;
4286 goto error;
4287 }
4288 }
4289
Alberto Garcia543770b2018-09-06 12:37:09 +03004290 reopen_state->detect_zeroes =
4291 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4292 if (local_err) {
4293 error_propagate(errp, local_err);
4294 ret = -EINVAL;
4295 goto error;
4296 }
4297
Alberto Garcia57f9db92018-09-06 12:37:06 +03004298 /* All other options (including node-name and driver) must be unchanged.
4299 * Put them back into the QDict, so that they are checked at the end
4300 * of this function. */
4301 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004302
Jeff Cody3d8ce172017-04-07 16:55:30 -04004303 /* If we are to stay read-only, do not allow permission change
4304 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4305 * not set, or if the BDS still has copy_on_read enabled */
4306 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004307 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004308 if (local_err) {
4309 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004310 goto error;
4311 }
4312
Kevin Wolf30450252017-07-03 17:07:35 +02004313 /* Calculate required permissions after reopening */
4314 bdrv_reopen_perm(queue, reopen_state->bs,
4315 &reopen_state->perm, &reopen_state->shared_perm);
Jeff Codye971aa12012-09-20 15:13:19 -04004316
4317 ret = bdrv_flush(reopen_state->bs);
4318 if (ret) {
Eric Blake455b0fd2015-11-10 23:51:20 -07004319 error_setg_errno(errp, -ret, "Error flushing drive");
Jeff Codye971aa12012-09-20 15:13:19 -04004320 goto error;
4321 }
4322
4323 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004324 /*
4325 * If a driver-specific option is missing, it means that we
4326 * should reset it to its default value.
4327 * But not all options allow that, so we need to check it first.
4328 */
4329 ret = bdrv_reset_options_allowed(reopen_state->bs,
4330 reopen_state->options, errp);
4331 if (ret) {
4332 goto error;
4333 }
4334
Jeff Codye971aa12012-09-20 15:13:19 -04004335 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4336 if (ret) {
4337 if (local_err != NULL) {
4338 error_propagate(errp, local_err);
4339 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004340 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004341 error_setg(errp, "failed while preparing to reopen image '%s'",
4342 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004343 }
4344 goto error;
4345 }
4346 } else {
4347 /* It is currently mandatory to have a bdrv_reopen_prepare()
4348 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004349 error_setg(errp, "Block format '%s' used by node '%s' "
4350 "does not support reopening files", drv->format_name,
4351 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004352 ret = -1;
4353 goto error;
4354 }
4355
Max Reitz9ad08c42018-11-16 17:45:24 +01004356 drv_prepared = true;
4357
Alberto Garciabacd9b82019-03-12 18:48:46 +02004358 /*
4359 * We must provide the 'backing' option if the BDS has a backing
4360 * file or if the image file has a backing file name as part of
4361 * its metadata. Otherwise the 'backing' option can be omitted.
4362 */
4363 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004364 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004365 error_setg(errp, "backing is missing for '%s'",
4366 reopen_state->bs->node_name);
4367 ret = -EINVAL;
4368 goto error;
4369 }
4370
Alberto Garciacb828c32019-03-12 18:48:47 +02004371 /*
4372 * Allow changing the 'backing' option. The new value can be
4373 * either a reference to an existing node (using its node name)
4374 * or NULL to simply detach the current backing file.
4375 */
4376 ret = bdrv_reopen_parse_backing(reopen_state, errp);
4377 if (ret < 0) {
4378 goto error;
4379 }
4380 qdict_del(reopen_state->options, "backing");
4381
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004382 /* Options that are not handled are only okay if they are unchanged
4383 * compared to the old state. It is expected that some options are only
4384 * used for the initial open, but not reopen (e.g. filename) */
4385 if (qdict_size(reopen_state->options)) {
4386 const QDictEntry *entry = qdict_first(reopen_state->options);
4387
4388 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004389 QObject *new = entry->value;
4390 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004391
Alberto Garciadb905282018-09-06 12:37:05 +03004392 /* Allow child references (child_name=node_name) as long as they
4393 * point to the current child (i.e. everything stays the same). */
4394 if (qobject_type(new) == QTYPE_QSTRING) {
4395 BdrvChild *child;
4396 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4397 if (!strcmp(child->name, entry->key)) {
4398 break;
4399 }
4400 }
4401
4402 if (child) {
Markus Armbruster410f44f2020-12-11 18:11:42 +01004403 if (!strcmp(child->bs->node_name,
4404 qstring_get_str(qobject_to(QString, new)))) {
Alberto Garciadb905282018-09-06 12:37:05 +03004405 continue; /* Found child with this name, skip option */
4406 }
4407 }
4408 }
4409
Max Reitz54fd1b02017-11-14 19:01:26 +01004410 /*
4411 * TODO: When using -drive to specify blockdev options, all values
4412 * will be strings; however, when using -blockdev, blockdev-add or
4413 * filenames using the json:{} pseudo-protocol, they will be
4414 * correctly typed.
4415 * In contrast, reopening options are (currently) always strings
4416 * (because you can only specify them through qemu-io; all other
4417 * callers do not specify any options).
4418 * Therefore, when using anything other than -drive to create a BDS,
4419 * this cannot detect non-string options as unchanged, because
4420 * qobject_is_equal() always returns false for objects of different
4421 * type. In the future, this should be remedied by correctly typing
4422 * all options. For now, this is not too big of an issue because
4423 * the user can simply omit options which cannot be changed anyway,
4424 * so they will stay unchanged.
4425 */
4426 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004427 error_setg(errp, "Cannot change the option '%s'", entry->key);
4428 ret = -EINVAL;
4429 goto error;
4430 }
4431 } while ((entry = qdict_next(reopen_state->options, entry)));
4432 }
4433
Jeff Codye971aa12012-09-20 15:13:19 -04004434 ret = 0;
4435
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004436 /* Restore the original reopen_state->options QDict */
4437 qobject_unref(reopen_state->options);
4438 reopen_state->options = qobject_ref(orig_reopen_opts);
4439
Jeff Codye971aa12012-09-20 15:13:19 -04004440error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004441 if (ret < 0 && drv_prepared) {
4442 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4443 * call drv->bdrv_reopen_abort() before signaling an error
4444 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4445 * when the respective bdrv_reopen_prepare() has failed) */
4446 if (drv->bdrv_reopen_abort) {
4447 drv->bdrv_reopen_abort(reopen_state);
4448 }
4449 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004450 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004451 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004452 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004453 return ret;
4454}
4455
4456/*
4457 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4458 * makes them final by swapping the staging BlockDriverState contents into
4459 * the active BlockDriverState contents.
4460 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004461static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004462{
4463 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004464 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004465 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004466
4467 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004468 bs = reopen_state->bs;
4469 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004470 assert(drv != NULL);
4471
4472 /* If there are any driver level actions to take */
4473 if (drv->bdrv_reopen_commit) {
4474 drv->bdrv_reopen_commit(reopen_state);
4475 }
4476
4477 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004478 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004479 qobject_unref(bs->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004480
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004481 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004482 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004483 bs->open_flags = reopen_state->flags;
4484 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
Alberto Garcia543770b2018-09-06 12:37:09 +03004485 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004486
Alberto Garciacb828c32019-03-12 18:48:47 +02004487 if (reopen_state->replace_backing_bs) {
4488 qdict_del(bs->explicit_options, "backing");
4489 qdict_del(bs->options, "backing");
4490 }
4491
Alberto Garcia50196d72018-09-06 12:37:03 +03004492 /* Remove child references from bs->options and bs->explicit_options.
4493 * Child options were already removed in bdrv_reopen_queue_child() */
4494 QLIST_FOREACH(child, &bs->children, next) {
4495 qdict_del(bs->explicit_options, child->name);
4496 qdict_del(bs->options, child->name);
4497 }
4498
Alberto Garciacb828c32019-03-12 18:48:47 +02004499 /*
4500 * Change the backing file if a new one was specified. We do this
4501 * after updating bs->options, so bdrv_refresh_filename() (called
4502 * from bdrv_set_backing_hd()) has the new values.
4503 */
4504 if (reopen_state->replace_backing_bs) {
Max Reitz1d42f482019-06-12 17:24:39 +02004505 BlockDriverState *old_backing_bs = child_bs(bs->backing);
Alberto Garciacb828c32019-03-12 18:48:47 +02004506 assert(!old_backing_bs || !old_backing_bs->implicit);
4507 /* Abort the permission update on the backing bs we're detaching */
4508 if (old_backing_bs) {
4509 bdrv_abort_perm_update(old_backing_bs);
4510 }
4511 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4512 }
4513
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004514 bdrv_refresh_limits(bs, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004515}
4516
4517/*
4518 * Abort the reopen, and delete and free the staged changes in
4519 * reopen_state
4520 */
Vladimir Sementsov-Ogievskiy53e96d12021-04-28 18:17:35 +03004521static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
Jeff Codye971aa12012-09-20 15:13:19 -04004522{
4523 BlockDriver *drv;
4524
4525 assert(reopen_state != NULL);
4526 drv = reopen_state->bs->drv;
4527 assert(drv != NULL);
4528
4529 if (drv->bdrv_reopen_abort) {
4530 drv->bdrv_reopen_abort(reopen_state);
4531 }
4532}
4533
4534
Max Reitz64dff522016-01-29 16:36:10 +01004535static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004536{
Max Reitz33384422014-06-20 21:57:33 +02004537 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004538 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004539
Max Reitz30f55fb2016-05-17 16:41:32 +02004540 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004541
Paolo Bonzinifc272912015-12-23 11:48:24 +01004542 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004543 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004544 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004545
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004546 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004547 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004548 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004549 bs->drv->bdrv_close(bs);
4550 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004551 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004552 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004553
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004554 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004555 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004556 }
4557
Alberto Garciadd4118c2019-05-13 16:46:17 +03004558 bs->backing = NULL;
4559 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004560 g_free(bs->opaque);
4561 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004562 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004563 bs->backing_file[0] = '\0';
4564 bs->backing_format[0] = '\0';
4565 bs->total_sectors = 0;
4566 bs->encrypted = false;
4567 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004568 qobject_unref(bs->options);
4569 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004570 bs->options = NULL;
4571 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004572 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004573 bs->full_open_options = NULL;
4574
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004575 bdrv_release_named_dirty_bitmaps(bs);
4576 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4577
Max Reitz33384422014-06-20 21:57:33 +02004578 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4579 g_free(ban);
4580 }
4581 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004582 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004583
4584 /*
4585 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4586 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4587 * gets called.
4588 */
4589 if (bs->quiesce_counter) {
4590 bdrv_drain_all_end_quiesce(bs);
4591 }
bellardb3380822004-03-14 21:38:54 +00004592}
4593
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004594void bdrv_close_all(void)
4595{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004596 assert(job_next(NULL) == NULL);
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004597
Max Reitzca9bd242016-01-29 16:36:14 +01004598 /* Drop references from requests still in flight, such as canceled block
4599 * jobs whose AIO context has not been polled yet */
4600 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004601
Max Reitzca9bd242016-01-29 16:36:14 +01004602 blk_remove_all_bs();
4603 blockdev_close_all_bdrv_states();
4604
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004605 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004606}
4607
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004608static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004609{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004610 GQueue *queue;
4611 GHashTable *found;
4612 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004613
Max Reitzbd86fb92020-05-13 13:05:13 +02004614 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004615 return false;
4616 }
4617
Max Reitzec9f10f2018-06-13 20:18:15 +02004618 /* If the child @c belongs to the BDS @to, replacing the current
4619 * c->bs by @to would mean to create a loop.
4620 *
4621 * Such a case occurs when appending a BDS to a backing chain.
4622 * For instance, imagine the following chain:
4623 *
4624 * guest device -> node A -> further backing chain...
4625 *
4626 * Now we create a new BDS B which we want to put on top of this
4627 * chain, so we first attach A as its backing node:
4628 *
4629 * node B
4630 * |
4631 * v
4632 * guest device -> node A -> further backing chain...
4633 *
4634 * Finally we want to replace A by B. When doing that, we want to
4635 * replace all pointers to A by pointers to B -- except for the
4636 * pointer from B because (1) that would create a loop, and (2)
4637 * that pointer should simply stay intact:
4638 *
4639 * guest device -> node B
4640 * |
4641 * v
4642 * node A -> further backing chain...
4643 *
4644 * In general, when replacing a node A (c->bs) by a node B (@to),
4645 * if A is a child of B, that means we cannot replace A by B there
4646 * because that would create a loop. Silently detaching A from B
4647 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004648 * place there is the most sensible choice.
4649 *
4650 * We would also create a loop in any cases where @c is only
4651 * indirectly referenced by @to. Prevent this by returning false
4652 * if @c is found (by breadth-first search) anywhere in the whole
4653 * subtree of @to.
4654 */
4655
4656 ret = true;
4657 found = g_hash_table_new(NULL, NULL);
4658 g_hash_table_add(found, to);
4659 queue = g_queue_new();
4660 g_queue_push_tail(queue, to);
4661
4662 while (!g_queue_is_empty(queue)) {
4663 BlockDriverState *v = g_queue_pop_head(queue);
4664 BdrvChild *c2;
4665
4666 QLIST_FOREACH(c2, &v->children, next) {
4667 if (c2 == c) {
4668 ret = false;
4669 break;
4670 }
4671
4672 if (g_hash_table_contains(found, c2->bs)) {
4673 continue;
4674 }
4675
4676 g_queue_push_tail(queue, c2->bs);
4677 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004678 }
4679 }
4680
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004681 g_queue_free(queue);
4682 g_hash_table_destroy(found);
4683
4684 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004685}
4686
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004687/*
4688 * With auto_skip=true bdrv_replace_node_common skips updating from parents
4689 * if it creates a parent-child relation loop or if parent is block-job.
4690 *
4691 * With auto_skip=false the error is returned if from has a parent which should
4692 * not be updated.
4693 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004694static int bdrv_replace_node_common(BlockDriverState *from,
4695 BlockDriverState *to,
4696 bool auto_skip, Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004697{
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004698 BdrvChild *c, *next;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004699 GSList *list = NULL, *p;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004700 uint64_t perm = 0, shared = BLK_PERM_ALL;
4701 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004702
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004703 /* Make sure that @from doesn't go away until we have successfully attached
4704 * all of its parents to @to. */
4705 bdrv_ref(from);
4706
Kevin Wolff871abd2019-05-21 19:00:25 +02004707 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01004708 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02004709 bdrv_drained_begin(from);
4710
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004711 /* Put all parents into @list and calculate their cumulative permissions */
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004712 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
Max Reitzec9f10f2018-06-13 20:18:15 +02004713 assert(c->bs == from);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004714 if (!should_update_child(c, to)) {
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004715 if (auto_skip) {
4716 continue;
4717 }
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004718 ret = -EINVAL;
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004719 error_setg(errp, "Should not change '%s' link to '%s'",
4720 c->name, from->node_name);
4721 goto out;
Kevin Wolf26de9432017-01-17 13:39:34 +01004722 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004723 if (c->frozen) {
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004724 ret = -EPERM;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004725 error_setg(errp, "Cannot change '%s' link to '%s'",
4726 c->name, from->node_name);
4727 goto out;
4728 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004729 list = g_slist_prepend(list, c);
4730 perm |= c->perm;
4731 shared &= c->shared_perm;
4732 }
4733
4734 /* Check whether the required permissions can be granted on @to, ignoring
4735 * all BdrvChild in @list so that they can't block themselves. */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03004736 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004737 if (ret < 0) {
4738 bdrv_abort_perm_update(to);
4739 goto out;
4740 }
4741
4742 /* Now actually perform the change. We performed the permission check for
4743 * all elements of @list at once, so set the permissions all at once at the
4744 * very end. */
4745 for (p = list; p != NULL; p = p->next) {
4746 c = p->data;
Max Reitz9bd910e2016-06-10 20:57:46 +02004747
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004748 bdrv_ref(to);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004749 bdrv_replace_child_noperm(c, to);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004750 bdrv_unref(from);
4751 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004752
Vladimir Sementsov-Ogievskiy74ad9a32020-11-06 15:42:39 +03004753 bdrv_set_perm(to);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004754
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004755 ret = 0;
4756
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004757out:
4758 g_slist_free(list);
Kevin Wolff871abd2019-05-21 19:00:25 +02004759 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004760 bdrv_unref(from);
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004761
4762 return ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004763}
4764
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004765int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4766 Error **errp)
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004767{
4768 return bdrv_replace_node_common(from, to, true, errp);
4769}
4770
Jeff Cody8802d1f2012-02-28 15:54:06 -05004771/*
4772 * Add new bs contents at the top of an image chain while the chain is
4773 * live, while keeping required fields on the top layer.
4774 *
4775 * This will modify the BlockDriverState fields, and swap contents
4776 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4777 *
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02004778 * bs_new must not be attached to a BlockBackend.
Jeff Codyf6801b82012-03-27 16:30:19 -04004779 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05004780 * This function does not create any image files.
4781 */
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004782int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4783 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05004784{
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004785 int ret = bdrv_set_backing_hd(bs_new, bs_top, errp);
4786 if (ret < 0) {
Vladimir Sementsov-Ogievskiyae9d4412021-04-28 18:17:32 +03004787 return ret;
Kevin Wolfb2c28322017-02-20 12:46:42 +01004788 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004789
Vladimir Sementsov-Ogievskiya1e708f2021-02-02 15:49:43 +03004790 ret = bdrv_replace_node(bs_top, bs_new, errp);
4791 if (ret < 0) {
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004792 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
Vladimir Sementsov-Ogievskiyae9d4412021-04-28 18:17:32 +03004793 return ret;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004794 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004795
Vladimir Sementsov-Ogievskiyae9d4412021-04-28 18:17:32 +03004796 return 0;
Jeff Cody8802d1f2012-02-28 15:54:06 -05004797}
4798
Fam Zheng4f6fd342013-08-23 09:14:47 +08004799static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00004800{
Fam Zheng3718d8a2014-05-23 21:29:43 +08004801 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08004802 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02004803
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01004804 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01004805 if (bs->node_name[0] != '\0') {
4806 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4807 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01004808 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4809
Anton Kuchin30c321f2019-05-07 11:12:56 +03004810 bdrv_close(bs);
4811
Anthony Liguori7267c092011-08-20 22:09:37 -05004812 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00004813}
4814
Andrey Shinkevich8872ef72020-12-16 09:16:52 +03004815BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *node_options,
4816 int flags, Error **errp)
4817{
4818 BlockDriverState *new_node_bs;
4819 Error *local_err = NULL;
4820
4821 new_node_bs = bdrv_open(NULL, NULL, node_options, flags, errp);
4822 if (new_node_bs == NULL) {
4823 error_prepend(errp, "Could not create node: ");
4824 return NULL;
4825 }
4826
4827 bdrv_drained_begin(bs);
4828 bdrv_replace_node(bs, new_node_bs, &local_err);
4829 bdrv_drained_end(bs);
4830
4831 if (local_err) {
4832 bdrv_unref(new_node_bs);
4833 error_propagate(errp, local_err);
4834 return NULL;
4835 }
4836
4837 return new_node_bs;
4838}
4839
aliguorie97fc192009-04-21 23:11:50 +00004840/*
4841 * Run consistency checks on an image
4842 *
Kevin Wolfe076f332010-06-29 11:43:13 +02004843 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02004844 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02004845 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00004846 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03004847int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4848 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00004849{
Max Reitz908bcd52014-08-07 22:47:55 +02004850 if (bs->drv == NULL) {
4851 return -ENOMEDIUM;
4852 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01004853 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00004854 return -ENOTSUP;
4855 }
4856
Kevin Wolfe076f332010-06-29 11:43:13 +02004857 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01004858 return bs->drv->bdrv_co_check(bs, res, fix);
4859}
4860
Kevin Wolf756e6732010-01-12 12:55:17 +01004861/*
4862 * Return values:
4863 * 0 - success
4864 * -EINVAL - backing format specified, but no file
4865 * -ENOSPC - can't update the backing file because no space is left in the
4866 * image file header
4867 * -ENOTSUP - format driver doesn't support changing the backing file
4868 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05004869int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
4870 const char *backing_fmt, bool warn)
Kevin Wolf756e6732010-01-12 12:55:17 +01004871{
4872 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02004873 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01004874
Max Reitzd470ad42017-11-10 21:31:09 +01004875 if (!drv) {
4876 return -ENOMEDIUM;
4877 }
4878
Paolo Bonzini5f377792012-04-12 14:01:01 +02004879 /* Backing file format doesn't make sense without a backing file */
4880 if (backing_fmt && !backing_file) {
4881 return -EINVAL;
4882 }
4883
Eric Blakee54ee1b2020-07-06 15:39:53 -05004884 if (warn && backing_file && !backing_fmt) {
4885 warn_report("Deprecated use of backing file without explicit "
4886 "backing format, use of this image requires "
4887 "potentially unsafe format probing");
4888 }
4889
Kevin Wolf756e6732010-01-12 12:55:17 +01004890 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02004891 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01004892 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02004893 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01004894 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02004895
4896 if (ret == 0) {
4897 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4898 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01004899 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4900 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02004901 }
4902 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01004903}
4904
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004905/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02004906 * Finds the first non-filter node above bs in the chain between
4907 * active and bs. The returned node is either an immediate parent of
4908 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004909 *
4910 * Returns NULL if bs is not found in active's image chain,
4911 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04004912 *
4913 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004914 */
4915BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4916 BlockDriverState *bs)
4917{
Max Reitzdcf3f9b2019-06-12 17:34:45 +02004918 bs = bdrv_skip_filters(bs);
4919 active = bdrv_skip_filters(active);
4920
4921 while (active) {
4922 BlockDriverState *next = bdrv_backing_chain_next(active);
4923 if (bs == next) {
4924 return active;
4925 }
4926 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004927 }
4928
Max Reitzdcf3f9b2019-06-12 17:34:45 +02004929 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04004930}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004931
Jeff Cody4caf0fc2014-06-25 15:35:26 -04004932/* Given a BDS, searches for the base layer. */
4933BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4934{
4935 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004936}
4937
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004938/*
Max Reitz7b99a262019-06-12 16:07:11 +02004939 * Return true if at least one of the COW (backing) and filter links
4940 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004941 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004942 */
4943bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4944 Error **errp)
4945{
4946 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02004947 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004948
Max Reitz7b99a262019-06-12 16:07:11 +02004949 for (i = bs; i != base; i = child_bs(child)) {
4950 child = bdrv_filter_or_cow_child(i);
4951
4952 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004953 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02004954 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004955 return true;
4956 }
4957 }
4958
4959 return false;
4960}
4961
4962/*
Max Reitz7b99a262019-06-12 16:07:11 +02004963 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004964 * If any of the links is already frozen the operation is aborted and
4965 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004966 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004967 * Returns 0 on success. On failure returns < 0 and sets @errp.
4968 */
4969int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4970 Error **errp)
4971{
4972 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02004973 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004974
4975 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4976 return -EPERM;
4977 }
4978
Max Reitz7b99a262019-06-12 16:07:11 +02004979 for (i = bs; i != base; i = child_bs(child)) {
4980 child = bdrv_filter_or_cow_child(i);
4981 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02004982 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02004983 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02004984 return -EPERM;
4985 }
4986 }
4987
Max Reitz7b99a262019-06-12 16:07:11 +02004988 for (i = bs; i != base; i = child_bs(child)) {
4989 child = bdrv_filter_or_cow_child(i);
4990 if (child) {
4991 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004992 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004993 }
4994
4995 return 0;
4996}
4997
4998/*
Max Reitz7b99a262019-06-12 16:07:11 +02004999 * Unfreeze all COW (backing) and filter links between @bs and @base.
5000 * The caller must ensure that all links are frozen before using this
5001 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005002 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005003 */
5004void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5005{
5006 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02005007 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005008
Max Reitz7b99a262019-06-12 16:07:11 +02005009 for (i = bs; i != base; i = child_bs(child)) {
5010 child = bdrv_filter_or_cow_child(i);
5011 if (child) {
5012 assert(child->frozen);
5013 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02005014 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02005015 }
5016}
5017
5018/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005019 * Drops images above 'base' up to and including 'top', and sets the image
5020 * above 'top' to have base as its backing file.
5021 *
5022 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5023 * information in 'bs' can be properly updated.
5024 *
5025 * E.g., this will convert the following chain:
5026 * bottom <- base <- intermediate <- top <- active
5027 *
5028 * to
5029 *
5030 * bottom <- base <- active
5031 *
5032 * It is allowed for bottom==base, in which case it converts:
5033 *
5034 * base <- intermediate <- top <- active
5035 *
5036 * to
5037 *
5038 * base <- active
5039 *
Jeff Cody54e26902014-06-25 15:40:10 -04005040 * If backing_file_str is non-NULL, it will be used when modifying top's
5041 * overlay image metadata.
5042 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005043 * Error conditions:
5044 * if active == top, that is considered an error
5045 *
5046 */
Kevin Wolfbde70712017-06-27 20:36:18 +02005047int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5048 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005049{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005050 BlockDriverState *explicit_top = top;
5051 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005052 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005053 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005054 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005055 g_autoptr(GSList) updated_children = NULL;
5056 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005057
Kevin Wolf6858eba2017-06-29 19:32:21 +02005058 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02005059 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005060
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005061 if (!top->drv || !base->drv) {
5062 goto exit;
5063 }
5064
Kevin Wolf5db15a52015-09-14 15:33:33 +02005065 /* Make sure that base is in the backing chain of top */
5066 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005067 goto exit;
5068 }
5069
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005070 /* If 'base' recursively inherits from 'top' then we should set
5071 * base->inherits_from to top->inherits_from after 'top' and all
5072 * other intermediate nodes have been dropped.
5073 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5074 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005075 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005076 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5077
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005078 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolfbde70712017-06-27 20:36:18 +02005079 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
5080 * we've figured out how they should work. */
Max Reitzf30c66b2019-02-01 20:29:05 +01005081 if (!backing_file_str) {
5082 bdrv_refresh_filename(base);
5083 backing_file_str = base->filename;
5084 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005085
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005086 QLIST_FOREACH(c, &top->parents, next_parent) {
5087 updated_children = g_slist_prepend(updated_children, c);
5088 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005089
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005090 bdrv_replace_node_common(top, base, false, &local_err);
5091 if (local_err) {
5092 error_report_err(local_err);
5093 goto exit;
5094 }
5095
5096 for (p = updated_children; p; p = p->next) {
5097 c = p->data;
5098
Max Reitzbd86fb92020-05-13 13:05:13 +02005099 if (c->klass->update_filename) {
5100 ret = c->klass->update_filename(c, base, backing_file_str,
5101 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005102 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03005103 /*
5104 * TODO: Actually, we want to rollback all previous iterations
5105 * of this loop, and (which is almost impossible) previous
5106 * bdrv_replace_node()...
5107 *
5108 * Note, that c->klass->update_filename may lead to permission
5109 * update, so it's a bad idea to call it inside permission
5110 * update transaction of bdrv_replace_node.
5111 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02005112 error_report_err(local_err);
5113 goto exit;
5114 }
5115 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01005116 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005117
Alberto Garcia6bd858b2018-10-31 18:16:38 +02005118 if (update_inherits_from) {
5119 base->inherits_from = explicit_top->inherits_from;
5120 }
5121
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005122 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005123exit:
Max Reitz637d54a2019-07-22 15:33:43 +02005124 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02005125 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04005126 return ret;
5127}
5128
bellard83f64092006-08-01 16:21:11 +00005129/**
Max Reitz081e4652019-06-12 18:14:13 +02005130 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5131 * sums the size of all data-bearing children. (This excludes backing
5132 * children.)
5133 */
5134static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5135{
5136 BdrvChild *child;
5137 int64_t child_size, sum = 0;
5138
5139 QLIST_FOREACH(child, &bs->children, next) {
5140 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5141 BDRV_CHILD_FILTERED))
5142 {
5143 child_size = bdrv_get_allocated_file_size(child->bs);
5144 if (child_size < 0) {
5145 return child_size;
5146 }
5147 sum += child_size;
5148 }
5149 }
5150
5151 return sum;
5152}
5153
5154/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005155 * Length of a allocated file in bytes. Sparse files are counted by actual
5156 * allocated space. Return < 0 if error or unknown.
5157 */
5158int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5159{
5160 BlockDriver *drv = bs->drv;
5161 if (!drv) {
5162 return -ENOMEDIUM;
5163 }
5164 if (drv->bdrv_get_allocated_file_size) {
5165 return drv->bdrv_get_allocated_file_size(bs);
5166 }
Max Reitz081e4652019-06-12 18:14:13 +02005167
5168 if (drv->bdrv_file_open) {
5169 /*
5170 * Protocol drivers default to -ENOTSUP (most of their data is
5171 * not stored in any of their children (if they even have any),
5172 * so there is no generic way to figure it out).
5173 */
5174 return -ENOTSUP;
5175 } else if (drv->is_filter) {
5176 /* Filter drivers default to the size of their filtered child */
5177 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5178 } else {
5179 /* Other drivers default to summing their children's sizes */
5180 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005181 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005182}
5183
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005184/*
5185 * bdrv_measure:
5186 * @drv: Format driver
5187 * @opts: Creation options for new image
5188 * @in_bs: Existing image containing data for new image (may be NULL)
5189 * @errp: Error object
5190 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5191 * or NULL on error
5192 *
5193 * Calculate file size required to create a new image.
5194 *
5195 * If @in_bs is given then space for allocated clusters and zero clusters
5196 * from that image are included in the calculation. If @opts contains a
5197 * backing file that is shared by @in_bs then backing clusters may be omitted
5198 * from the calculation.
5199 *
5200 * If @in_bs is NULL then the calculation includes no allocated clusters
5201 * unless a preallocation option is given in @opts.
5202 *
5203 * Note that @in_bs may use a different BlockDriver from @drv.
5204 *
5205 * If an error occurs the @errp pointer is set.
5206 */
5207BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5208 BlockDriverState *in_bs, Error **errp)
5209{
5210 if (!drv->bdrv_measure) {
5211 error_setg(errp, "Block driver '%s' does not support size measurement",
5212 drv->format_name);
5213 return NULL;
5214 }
5215
5216 return drv->bdrv_measure(opts, in_bs, errp);
5217}
5218
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005219/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005220 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005221 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005222int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005223{
5224 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005225
bellard83f64092006-08-01 16:21:11 +00005226 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005227 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005228
Kevin Wolfb94a2612013-10-29 12:18:58 +01005229 if (drv->has_variable_length) {
5230 int ret = refresh_total_sectors(bs, bs->total_sectors);
5231 if (ret < 0) {
5232 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005233 }
bellard83f64092006-08-01 16:21:11 +00005234 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005235 return bs->total_sectors;
5236}
5237
5238/**
5239 * Return length in bytes on success, -errno on error.
5240 * The length is always a multiple of BDRV_SECTOR_SIZE.
5241 */
5242int64_t bdrv_getlength(BlockDriverState *bs)
5243{
5244 int64_t ret = bdrv_nb_sectors(bs);
5245
Eric Blake122860b2020-11-05 09:51:22 -06005246 if (ret < 0) {
5247 return ret;
5248 }
5249 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5250 return -EFBIG;
5251 }
5252 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005253}
5254
bellard19cb3732006-08-19 11:45:59 +00005255/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005256void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005257{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005258 int64_t nb_sectors = bdrv_nb_sectors(bs);
5259
5260 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005261}
bellardcf989512004-02-16 21:56:36 +00005262
Eric Blake54115412016-06-23 16:37:26 -06005263bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005264{
5265 return bs->sg;
5266}
5267
Max Reitzae23f782019-06-12 22:57:15 +02005268/**
5269 * Return whether the given node supports compressed writes.
5270 */
5271bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5272{
5273 BlockDriverState *filtered;
5274
5275 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5276 return false;
5277 }
5278
5279 filtered = bdrv_filter_bs(bs);
5280 if (filtered) {
5281 /*
5282 * Filters can only forward compressed writes, so we have to
5283 * check the child.
5284 */
5285 return bdrv_supports_compressed_writes(filtered);
5286 }
5287
5288 return true;
5289}
5290
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005291const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005292{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005293 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005294}
5295
Stefan Hajnocziada42402014-08-27 12:08:55 +01005296static int qsort_strcmp(const void *a, const void *b)
5297{
Max Reitzceff5bd2016-10-12 22:49:05 +02005298 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005299}
5300
ths5fafdf22007-09-16 21:08:06 +00005301void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005302 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005303{
5304 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005305 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005306 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005307 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005308
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005309 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005310 if (drv->format_name) {
5311 bool found = false;
5312 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005313
5314 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5315 continue;
5316 }
5317
Jeff Codye855e4f2014-04-28 18:29:54 -04005318 while (formats && i && !found) {
5319 found = !strcmp(formats[--i], drv->format_name);
5320 }
5321
5322 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005323 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005324 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005325 }
5326 }
bellardea2384d2004-08-01 21:59:26 +00005327 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005328
Max Reitzeb0df692016-10-12 22:49:06 +02005329 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5330 const char *format_name = block_driver_modules[i].format_name;
5331
5332 if (format_name) {
5333 bool found = false;
5334 int j = count;
5335
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005336 if (use_bdrv_whitelist &&
5337 !bdrv_format_is_whitelisted(format_name, read_only)) {
5338 continue;
5339 }
5340
Max Reitzeb0df692016-10-12 22:49:06 +02005341 while (formats && j && !found) {
5342 found = !strcmp(formats[--j], format_name);
5343 }
5344
5345 if (!found) {
5346 formats = g_renew(const char *, formats, count + 1);
5347 formats[count++] = format_name;
5348 }
5349 }
5350 }
5351
Stefan Hajnocziada42402014-08-27 12:08:55 +01005352 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5353
5354 for (i = 0; i < count; i++) {
5355 it(opaque, formats[i]);
5356 }
5357
Jeff Codye855e4f2014-04-28 18:29:54 -04005358 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005359}
5360
Benoît Canetdc364f42014-01-23 21:31:32 +01005361/* This function is to find a node in the bs graph */
5362BlockDriverState *bdrv_find_node(const char *node_name)
5363{
5364 BlockDriverState *bs;
5365
5366 assert(node_name);
5367
5368 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5369 if (!strcmp(node_name, bs->node_name)) {
5370 return bs;
5371 }
5372 }
5373 return NULL;
5374}
5375
Benoît Canetc13163f2014-01-23 21:31:34 +01005376/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005377BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5378 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005379{
Eric Blake9812e712020-10-27 00:05:47 -05005380 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005381 BlockDriverState *bs;
5382
5383 list = NULL;
5384 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005385 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005386 if (!info) {
5387 qapi_free_BlockDeviceInfoList(list);
5388 return NULL;
5389 }
Eric Blake9812e712020-10-27 00:05:47 -05005390 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005391 }
5392
5393 return list;
5394}
5395
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005396typedef struct XDbgBlockGraphConstructor {
5397 XDbgBlockGraph *graph;
5398 GHashTable *graph_nodes;
5399} XDbgBlockGraphConstructor;
5400
5401static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5402{
5403 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5404
5405 gr->graph = g_new0(XDbgBlockGraph, 1);
5406 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5407
5408 return gr;
5409}
5410
5411static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5412{
5413 XDbgBlockGraph *graph = gr->graph;
5414
5415 g_hash_table_destroy(gr->graph_nodes);
5416 g_free(gr);
5417
5418 return graph;
5419}
5420
5421static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5422{
5423 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5424
5425 if (ret != 0) {
5426 return ret;
5427 }
5428
5429 /*
5430 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5431 * answer of g_hash_table_lookup.
5432 */
5433 ret = g_hash_table_size(gr->graph_nodes) + 1;
5434 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5435
5436 return ret;
5437}
5438
5439static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5440 XDbgBlockGraphNodeType type, const char *name)
5441{
5442 XDbgBlockGraphNode *n;
5443
5444 n = g_new0(XDbgBlockGraphNode, 1);
5445
5446 n->id = xdbg_graph_node_num(gr, node);
5447 n->type = type;
5448 n->name = g_strdup(name);
5449
Eric Blake9812e712020-10-27 00:05:47 -05005450 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005451}
5452
5453static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5454 const BdrvChild *child)
5455{
Max Reitzcdb1cec2019-11-08 13:34:52 +01005456 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005457 XDbgBlockGraphEdge *edge;
5458
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005459 edge = g_new0(XDbgBlockGraphEdge, 1);
5460
5461 edge->parent = xdbg_graph_node_num(gr, parent);
5462 edge->child = xdbg_graph_node_num(gr, child->bs);
5463 edge->name = g_strdup(child->name);
5464
Max Reitzcdb1cec2019-11-08 13:34:52 +01005465 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5466 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5467
5468 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005469 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005470 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01005471 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005472 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005473 }
5474 }
5475
Eric Blake9812e712020-10-27 00:05:47 -05005476 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005477}
5478
5479
5480XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5481{
5482 BlockBackend *blk;
5483 BlockJob *job;
5484 BlockDriverState *bs;
5485 BdrvChild *child;
5486 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5487
5488 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5489 char *allocated_name = NULL;
5490 const char *name = blk_name(blk);
5491
5492 if (!*name) {
5493 name = allocated_name = blk_get_attached_dev_id(blk);
5494 }
5495 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5496 name);
5497 g_free(allocated_name);
5498 if (blk_root(blk)) {
5499 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5500 }
5501 }
5502
5503 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5504 GSList *el;
5505
5506 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5507 job->job.id);
5508 for (el = job->nodes; el; el = el->next) {
5509 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5510 }
5511 }
5512
5513 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5514 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5515 bs->node_name);
5516 QLIST_FOREACH(child, &bs->children, next) {
5517 xdbg_graph_add_edge(gr, bs, child);
5518 }
5519 }
5520
5521 return xdbg_graph_finalize(gr);
5522}
5523
Benoît Canet12d3ba82014-01-23 21:31:35 +01005524BlockDriverState *bdrv_lookup_bs(const char *device,
5525 const char *node_name,
5526 Error **errp)
5527{
Markus Armbruster7f06d472014-10-07 13:59:12 +02005528 BlockBackend *blk;
5529 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005530
Benoît Canet12d3ba82014-01-23 21:31:35 +01005531 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02005532 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005533
Markus Armbruster7f06d472014-10-07 13:59:12 +02005534 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005535 bs = blk_bs(blk);
5536 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02005537 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02005538 }
5539
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005540 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005541 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005542 }
5543
Benoît Canetdd67fa52014-02-12 17:15:06 +01005544 if (node_name) {
5545 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005546
Benoît Canetdd67fa52014-02-12 17:15:06 +01005547 if (bs) {
5548 return bs;
5549 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005550 }
5551
Connor Kuehl785ec4b2021-03-05 09:19:28 -06005552 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
Benoît Canetdd67fa52014-02-12 17:15:06 +01005553 device ? device : "",
5554 node_name ? node_name : "");
5555 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005556}
5557
Jeff Cody5a6684d2014-06-25 15:40:09 -04005558/* If 'base' is in the same chain as 'top', return true. Otherwise,
5559 * return false. If either argument is NULL, return false. */
5560bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5561{
5562 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005563 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04005564 }
5565
5566 return top != NULL;
5567}
5568
Fam Zheng04df7652014-10-31 11:32:54 +08005569BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5570{
5571 if (!bs) {
5572 return QTAILQ_FIRST(&graph_bdrv_states);
5573 }
5574 return QTAILQ_NEXT(bs, node_list);
5575}
5576
Kevin Wolf0f122642018-03-28 18:29:18 +02005577BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5578{
5579 if (!bs) {
5580 return QTAILQ_FIRST(&all_bdrv_states);
5581 }
5582 return QTAILQ_NEXT(bs, bs_list);
5583}
5584
Fam Zheng20a9e772014-10-31 11:32:55 +08005585const char *bdrv_get_node_name(const BlockDriverState *bs)
5586{
5587 return bs->node_name;
5588}
5589
Kevin Wolf1f0c4612016-03-22 18:38:44 +01005590const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005591{
5592 BdrvChild *c;
5593 const char *name;
5594
5595 /* If multiple parents have a name, just pick the first one. */
5596 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005597 if (c->klass->get_name) {
5598 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005599 if (name && *name) {
5600 return name;
5601 }
5602 }
5603 }
5604
5605 return NULL;
5606}
5607
Markus Armbruster7f06d472014-10-07 13:59:12 +02005608/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02005609const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005610{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005611 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00005612}
5613
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005614/* This can be used to identify nodes that might not have a device
5615 * name associated. Since node and device names live in the same
5616 * namespace, the result is unambiguous. The exception is if both are
5617 * absent, then this returns an empty (non-null) string. */
5618const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5619{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005620 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005621}
5622
Markus Armbrusterc8433282012-06-05 16:49:24 +02005623int bdrv_get_flags(BlockDriverState *bs)
5624{
5625 return bs->open_flags;
5626}
5627
Peter Lieven3ac21622013-06-28 12:47:42 +02005628int bdrv_has_zero_init_1(BlockDriverState *bs)
5629{
5630 return 1;
5631}
5632
Kevin Wolff2feebb2010-04-14 17:30:35 +02005633int bdrv_has_zero_init(BlockDriverState *bs)
5634{
Max Reitz93393e62019-06-12 17:03:38 +02005635 BlockDriverState *filtered;
5636
Max Reitzd470ad42017-11-10 21:31:09 +01005637 if (!bs->drv) {
5638 return 0;
5639 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005640
Paolo Bonzini11212d82013-09-04 19:00:27 +02005641 /* If BS is a copy on write image, it is initialized to
5642 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02005643 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02005644 return 0;
5645 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02005646 if (bs->drv->bdrv_has_zero_init) {
5647 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02005648 }
Max Reitz93393e62019-06-12 17:03:38 +02005649
5650 filtered = bdrv_filter_bs(bs);
5651 if (filtered) {
5652 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005653 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005654
Peter Lieven3ac21622013-06-28 12:47:42 +02005655 /* safe default */
5656 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02005657}
5658
Peter Lieven4ce78692013-10-24 12:06:54 +02005659bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5660{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03005661 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02005662 return false;
5663 }
5664
Eric Blakee24d8132018-01-26 13:34:39 -06005665 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02005666}
5667
ths5fafdf22007-09-16 21:08:06 +00005668void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00005669 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00005670{
Kevin Wolf3574c602011-10-26 11:02:11 +02005671 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00005672}
5673
bellardfaea38e2006-08-05 21:31:00 +00005674int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5675{
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005676 int ret;
bellardfaea38e2006-08-05 21:31:00 +00005677 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005678 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5679 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00005680 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005681 }
5682 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02005683 BlockDriverState *filtered = bdrv_filter_bs(bs);
5684 if (filtered) {
5685 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005686 }
bellardfaea38e2006-08-05 21:31:00 +00005687 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005688 }
bellardfaea38e2006-08-05 21:31:00 +00005689 memset(bdi, 0, sizeof(*bdi));
Vladimir Sementsov-Ogievskiy8b117002020-12-04 01:27:13 +03005690 ret = drv->bdrv_get_info(bs, bdi);
5691 if (ret < 0) {
5692 return ret;
5693 }
5694
5695 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
5696 return -EINVAL;
5697 }
5698
5699 return 0;
bellardfaea38e2006-08-05 21:31:00 +00005700}
5701
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005702ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5703 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02005704{
5705 BlockDriver *drv = bs->drv;
5706 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005707 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02005708 }
5709 return NULL;
5710}
5711
Anton Nefedovd9245592019-09-23 15:17:37 +03005712BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5713{
5714 BlockDriver *drv = bs->drv;
5715 if (!drv || !drv->bdrv_get_specific_stats) {
5716 return NULL;
5717 }
5718 return drv->bdrv_get_specific_stats(bs);
5719}
5720
Eric Blakea31939e2015-11-18 01:52:54 -07005721void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005722{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005723 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005724 return;
5725 }
5726
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005727 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005728}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005729
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005730static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01005731{
5732 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02005733 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005734 }
5735
5736 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005737 assert(bs->drv->bdrv_debug_remove_breakpoint);
5738 return bs;
5739 }
5740
5741 return NULL;
5742}
5743
5744int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5745 const char *tag)
5746{
5747 bs = bdrv_find_debug_node(bs);
5748 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01005749 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5750 }
5751
5752 return -ENOTSUP;
5753}
5754
Fam Zheng4cc70e92013-11-20 10:01:54 +08005755int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5756{
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005757 bs = bdrv_find_debug_node(bs);
5758 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08005759 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5760 }
5761
5762 return -ENOTSUP;
5763}
5764
Kevin Wolf41c695c2012-12-06 14:32:58 +01005765int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5766{
Max Reitz938789e2014-03-10 23:44:08 +01005767 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02005768 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005769 }
5770
5771 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5772 return bs->drv->bdrv_debug_resume(bs, tag);
5773 }
5774
5775 return -ENOTSUP;
5776}
5777
5778bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5779{
5780 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02005781 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005782 }
5783
5784 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5785 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5786 }
5787
5788 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005789}
5790
Jeff Codyb1b1d782012-10-16 15:49:09 -04005791/* backing_file can either be relative, or absolute, or a protocol. If it is
5792 * relative, it must be relative to the chain. So, passing in bs->filename
5793 * from a BDS as backing_file should not be done, as that may be relative to
5794 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005795BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5796 const char *backing_file)
5797{
Jeff Codyb1b1d782012-10-16 15:49:09 -04005798 char *filename_full = NULL;
5799 char *backing_file_full = NULL;
5800 char *filename_tmp = NULL;
5801 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02005802 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005803 BlockDriverState *curr_bs = NULL;
5804 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005805 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005806
5807 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005808 return NULL;
5809 }
5810
Jeff Codyb1b1d782012-10-16 15:49:09 -04005811 filename_full = g_malloc(PATH_MAX);
5812 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005813
5814 is_protocol = path_has_protocol(backing_file);
5815
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005816 /*
5817 * Being largely a legacy function, skip any filters here
5818 * (because filters do not have normal filenames, so they cannot
5819 * match anyway; and allowing json:{} filenames is a bit out of
5820 * scope).
5821 */
5822 for (curr_bs = bdrv_skip_filters(bs);
5823 bdrv_cow_child(curr_bs) != NULL;
5824 curr_bs = bs_below)
5825 {
5826 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005827
Max Reitz0b877d02018-08-01 20:34:11 +02005828 if (bdrv_backing_overridden(curr_bs)) {
5829 /*
5830 * If the backing file was overridden, we can only compare
5831 * directly against the backing node's filename.
5832 */
5833
5834 if (!filenames_refreshed) {
5835 /*
5836 * This will automatically refresh all of the
5837 * filenames in the rest of the backing chain, so we
5838 * only need to do this once.
5839 */
5840 bdrv_refresh_filename(bs_below);
5841 filenames_refreshed = true;
5842 }
5843
5844 if (strcmp(backing_file, bs_below->filename) == 0) {
5845 retval = bs_below;
5846 break;
5847 }
5848 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
5849 /*
5850 * If either of the filename paths is actually a protocol, then
5851 * compare unmodified paths; otherwise make paths relative.
5852 */
Max Reitz6b6833c2019-02-01 20:29:15 +01005853 char *backing_file_full_ret;
5854
Jeff Codyb1b1d782012-10-16 15:49:09 -04005855 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005856 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005857 break;
5858 }
Jeff Cody418661e2017-01-25 20:08:20 -05005859 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01005860 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5861 NULL);
5862 if (backing_file_full_ret) {
5863 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5864 g_free(backing_file_full_ret);
5865 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005866 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05005867 break;
5868 }
Jeff Cody418661e2017-01-25 20:08:20 -05005869 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005870 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04005871 /* If not an absolute filename path, make it relative to the current
5872 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01005873 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5874 NULL);
5875 /* We are going to compare canonicalized absolute pathnames */
5876 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5877 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005878 continue;
5879 }
Max Reitz2d9158c2019-02-01 20:29:17 +01005880 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005881
5882 /* We need to make sure the backing filename we are comparing against
5883 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01005884 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5885 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5886 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005887 continue;
5888 }
Max Reitz2d9158c2019-02-01 20:29:17 +01005889 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005890
5891 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005892 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005893 break;
5894 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005895 }
5896 }
5897
Jeff Codyb1b1d782012-10-16 15:49:09 -04005898 g_free(filename_full);
5899 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005900 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005901}
5902
bellardea2384d2004-08-01 21:59:26 +00005903void bdrv_init(void)
5904{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05005905 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00005906}
pbrookce1a14d2006-08-07 02:38:06 +00005907
Markus Armbrustereb852012009-10-27 18:41:44 +01005908void bdrv_init_with_whitelist(void)
5909{
5910 use_bdrv_whitelist = 1;
5911 bdrv_init();
5912}
5913
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005914int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06005915{
Kevin Wolf4417ab72017-05-04 18:52:37 +02005916 BdrvChild *child, *parent;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005917 Error *local_err = NULL;
5918 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04005919 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005920
Kevin Wolf3456a8d2014-03-11 10:58:39 +01005921 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005922 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06005923 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01005924
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03005925 QLIST_FOREACH(child, &bs->children, next) {
Paolo Bonzini2b148f32018-03-01 17:36:18 +01005926 bdrv_co_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005927 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005928 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005929 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005930 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005931 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005932
Kevin Wolfdafe0962017-11-16 13:00:01 +01005933 /*
5934 * Update permissions, they may differ for inactive nodes.
5935 *
5936 * Note that the required permissions of inactive images are always a
5937 * subset of the permissions required after activating the image. This
5938 * allows us to just get the permissions upfront without restricting
5939 * drv->bdrv_invalidate_cache().
5940 *
5941 * It also means that in error cases, we don't have to try and revert to
5942 * the old permissions (which is an operation that could fail, too). We can
5943 * just keep the extended permissions for the next time that an activation
5944 * of the image is tried.
5945 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01005946 if (bs->open_flags & BDRV_O_INACTIVE) {
5947 bs->open_flags &= ~BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03005948 ret = bdrv_refresh_perms(bs, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01005949 if (ret < 0) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005950 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005951 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005952 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01005953
Kevin Wolf7bb49412019-12-17 15:06:38 +01005954 if (bs->drv->bdrv_co_invalidate_cache) {
5955 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5956 if (local_err) {
5957 bs->open_flags |= BDRV_O_INACTIVE;
5958 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005959 return -EINVAL;
Kevin Wolf7bb49412019-12-17 15:06:38 +01005960 }
5961 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04005962
Kevin Wolf7bb49412019-12-17 15:06:38 +01005963 FOR_EACH_DIRTY_BITMAP(bs, bm) {
5964 bdrv_dirty_bitmap_skip_store(bm, false);
5965 }
5966
5967 ret = refresh_total_sectors(bs, bs->total_sectors);
5968 if (ret < 0) {
5969 bs->open_flags |= BDRV_O_INACTIVE;
5970 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005971 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01005972 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005973 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02005974
5975 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005976 if (parent->klass->activate) {
5977 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02005978 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01005979 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02005980 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005981 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02005982 }
5983 }
5984 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005985
5986 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06005987}
5988
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005989void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06005990{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01005991 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02005992 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06005993
Kevin Wolf88be7b42016-05-20 18:49:07 +02005994 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02005995 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005996 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02005997
5998 aio_context_acquire(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005999 ret = bdrv_invalidate_cache(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02006000 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03006001 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01006002 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01006003 return;
6004 }
Anthony Liguori0f154232011-11-14 15:09:45 -06006005 }
6006}
6007
Kevin Wolf9e372712018-11-23 15:11:14 +01006008static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6009{
6010 BdrvChild *parent;
6011
6012 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006013 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006014 BlockDriverState *parent_bs = parent->opaque;
6015 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6016 return true;
6017 }
6018 }
6019 }
6020
6021 return false;
6022}
6023
6024static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006025{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006026 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006027 int ret;
6028
Max Reitzd470ad42017-11-10 21:31:09 +01006029 if (!bs->drv) {
6030 return -ENOMEDIUM;
6031 }
6032
Kevin Wolf9e372712018-11-23 15:11:14 +01006033 /* Make sure that we don't inactivate a child before its parent.
6034 * It will be covered by recursion from the yet active parent. */
6035 if (bdrv_has_bds_parent(bs, true)) {
6036 return 0;
6037 }
6038
6039 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6040
6041 /* Inactivate this node */
6042 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006043 ret = bs->drv->bdrv_inactivate(bs);
6044 if (ret < 0) {
6045 return ret;
6046 }
6047 }
6048
Kevin Wolf9e372712018-11-23 15:11:14 +01006049 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02006050 if (parent->klass->inactivate) {
6051 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01006052 if (ret < 0) {
6053 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02006054 }
6055 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006056 }
Kevin Wolf38701b62017-05-04 18:52:39 +02006057
Kevin Wolf9e372712018-11-23 15:11:14 +01006058 bs->open_flags |= BDRV_O_INACTIVE;
6059
Vladimir Sementsov-Ogievskiybb87e4d2020-11-06 15:42:38 +03006060 /*
6061 * Update permissions, they may differ for inactive nodes.
6062 * We only tried to loosen restrictions, so errors are not fatal, ignore
6063 * them.
6064 */
Vladimir Sementsov-Ogievskiy071b4742020-11-06 15:42:41 +03006065 bdrv_refresh_perms(bs, NULL);
Kevin Wolf9e372712018-11-23 15:11:14 +01006066
6067 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02006068 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01006069 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02006070 if (ret < 0) {
6071 return ret;
6072 }
6073 }
6074
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006075 return 0;
6076}
6077
6078int bdrv_inactivate_all(void)
6079{
Max Reitz79720af2016-03-16 19:54:44 +01006080 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02006081 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006082 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006083 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006084
Kevin Wolf88be7b42016-05-20 18:49:07 +02006085 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006086 AioContext *aio_context = bdrv_get_aio_context(bs);
6087
6088 if (!g_slist_find(aio_ctxs, aio_context)) {
6089 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6090 aio_context_acquire(aio_context);
6091 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006092 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006093
Kevin Wolf9e372712018-11-23 15:11:14 +01006094 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6095 /* Nodes with BDS parents are covered by recursion from the last
6096 * parent that gets inactivated. Don't inactivate them a second
6097 * time if that has already happened. */
6098 if (bdrv_has_bds_parent(bs, false)) {
6099 continue;
6100 }
6101 ret = bdrv_inactivate_recurse(bs);
6102 if (ret < 0) {
6103 bdrv_next_cleanup(&it);
6104 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006105 }
6106 }
6107
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006108out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006109 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6110 AioContext *aio_context = ctx->data;
6111 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006112 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00006113 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08006114
6115 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01006116}
6117
Kevin Wolff9f05dc2011-07-15 13:50:26 +02006118/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00006119/* removable device support */
6120
6121/**
6122 * Return TRUE if the media is present
6123 */
Max Reitze031f752015-10-19 17:53:11 +02006124bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00006125{
6126 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02006127 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02006128
Max Reitze031f752015-10-19 17:53:11 +02006129 if (!drv) {
6130 return false;
6131 }
Max Reitz28d7a782015-10-19 17:53:13 +02006132 if (drv->bdrv_is_inserted) {
6133 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02006134 }
Max Reitz28d7a782015-10-19 17:53:13 +02006135 QLIST_FOREACH(child, &bs->children, next) {
6136 if (!bdrv_is_inserted(child->bs)) {
6137 return false;
6138 }
6139 }
6140 return true;
bellard19cb3732006-08-19 11:45:59 +00006141}
6142
6143/**
bellard19cb3732006-08-19 11:45:59 +00006144 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6145 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006146void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006147{
6148 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006149
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006150 if (drv && drv->bdrv_eject) {
6151 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006152 }
bellard19cb3732006-08-19 11:45:59 +00006153}
6154
bellard19cb3732006-08-19 11:45:59 +00006155/**
6156 * Lock or unlock the media (if it is locked, the user won't be able
6157 * to eject it manually).
6158 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006159void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006160{
6161 BlockDriver *drv = bs->drv;
6162
Markus Armbruster025e8492011-09-06 18:58:47 +02006163 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006164
Markus Armbruster025e8492011-09-06 18:58:47 +02006165 if (drv && drv->bdrv_lock_medium) {
6166 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006167 }
6168}
ths985a03b2007-12-24 16:10:43 +00006169
Fam Zheng9fcb0252013-08-23 09:14:46 +08006170/* Get a reference to bs */
6171void bdrv_ref(BlockDriverState *bs)
6172{
6173 bs->refcnt++;
6174}
6175
6176/* Release a previously grabbed reference to bs.
6177 * If after releasing, reference count is zero, the BlockDriverState is
6178 * deleted. */
6179void bdrv_unref(BlockDriverState *bs)
6180{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006181 if (!bs) {
6182 return;
6183 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006184 assert(bs->refcnt > 0);
6185 if (--bs->refcnt == 0) {
6186 bdrv_delete(bs);
6187 }
6188}
6189
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006190struct BdrvOpBlocker {
6191 Error *reason;
6192 QLIST_ENTRY(BdrvOpBlocker) list;
6193};
6194
6195bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6196{
6197 BdrvOpBlocker *blocker;
6198 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6199 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6200 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006201 error_propagate_prepend(errp, error_copy(blocker->reason),
6202 "Node '%s' is busy: ",
6203 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006204 return true;
6205 }
6206 return false;
6207}
6208
6209void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6210{
6211 BdrvOpBlocker *blocker;
6212 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6213
Markus Armbruster5839e532014-08-19 10:31:08 +02006214 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006215 blocker->reason = reason;
6216 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6217}
6218
6219void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6220{
6221 BdrvOpBlocker *blocker, *next;
6222 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6223 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6224 if (blocker->reason == reason) {
6225 QLIST_REMOVE(blocker, list);
6226 g_free(blocker);
6227 }
6228 }
6229}
6230
6231void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6232{
6233 int i;
6234 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6235 bdrv_op_block(bs, i, reason);
6236 }
6237}
6238
6239void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6240{
6241 int i;
6242 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6243 bdrv_op_unblock(bs, i, reason);
6244 }
6245}
6246
6247bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6248{
6249 int i;
6250
6251 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6252 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6253 return false;
6254 }
6255 }
6256 return true;
6257}
6258
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006259void bdrv_img_create(const char *filename, const char *fmt,
6260 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006261 char *options, uint64_t img_size, int flags, bool quiet,
6262 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006263{
Chunyan Liu83d05212014-06-05 17:20:51 +08006264 QemuOptsList *create_opts = NULL;
6265 QemuOpts *opts = NULL;
6266 const char *backing_fmt, *backing_file;
6267 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006268 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006269 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006270 int ret = 0;
6271
6272 /* Find driver and parse its options */
6273 drv = bdrv_find_format(fmt);
6274 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006275 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006276 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006277 }
6278
Max Reitzb65a5e12015-02-05 13:58:12 -05006279 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006280 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006281 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006282 }
6283
Max Reitzc6149722014-12-02 18:32:45 +01006284 if (!drv->create_opts) {
6285 error_setg(errp, "Format driver '%s' does not support image creation",
6286 drv->format_name);
6287 return;
6288 }
6289
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006290 if (!proto_drv->create_opts) {
6291 error_setg(errp, "Protocol driver '%s' does not support image creation",
6292 proto_drv->format_name);
6293 return;
6294 }
6295
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006296 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006297 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006298 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006299
Chunyan Liu83d05212014-06-05 17:20:51 +08006300 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006301
6302 /* Parse -o options */
6303 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006304 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006305 goto out;
6306 }
6307 }
6308
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006309 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6310 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6311 } else if (img_size != UINT64_C(-1)) {
6312 error_setg(errp, "The image size must be specified only once");
6313 goto out;
6314 }
6315
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006316 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006317 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006318 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006319 error_setg(errp, "Backing file not supported for file format '%s'",
6320 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006321 goto out;
6322 }
6323 }
6324
6325 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006326 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006327 error_setg(errp, "Backing file format not supported for file "
6328 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006329 goto out;
6330 }
6331 }
6332
Chunyan Liu83d05212014-06-05 17:20:51 +08006333 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6334 if (backing_file) {
6335 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006336 error_setg(errp, "Error: Trying to create an image with the "
6337 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006338 goto out;
6339 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006340 if (backing_file[0] == '\0') {
6341 error_setg(errp, "Expected backing file name, got empty string");
6342 goto out;
6343 }
Jes Sorensen792da932010-12-16 13:52:17 +01006344 }
6345
Chunyan Liu83d05212014-06-05 17:20:51 +08006346 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006347
John Snow6e6e55f2017-07-17 20:34:22 -04006348 /* The size for the image must always be specified, unless we have a backing
6349 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006350 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006351 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6352 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006353 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006354 int back_flags;
6355 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006356
Max Reitz645ae7d2019-02-01 20:29:14 +01006357 full_backing =
6358 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6359 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006360 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006361 goto out;
6362 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006363 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006364
6365 /* backing files always opened read-only */
6366 back_flags = flags;
6367 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6368
Fam Zhengcc954f02017-12-15 16:04:45 +08006369 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006370 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006371 qdict_put_str(backing_options, "driver", backing_fmt);
6372 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006373 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006374
6375 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6376 &local_err);
6377 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006378 if (!bs) {
6379 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006380 goto out;
6381 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006382 if (!backing_fmt) {
6383 warn_report("Deprecated use of backing file without explicit "
6384 "backing format (detected format of %s)",
6385 bs->drv->format_name);
6386 if (bs->drv != &bdrv_raw) {
6387 /*
6388 * A probe of raw deserves the most attention:
6389 * leaving the backing format out of the image
6390 * will ensure bs->probed is set (ensuring we
6391 * don't accidentally commit into the backing
6392 * file), and allow more spots to warn the users
6393 * to fix their toolchain when opening this image
6394 * later. For other images, we can safely record
6395 * the format that we probed.
6396 */
6397 backing_fmt = bs->drv->format_name;
6398 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
6399 NULL);
6400 }
6401 }
John Snow6e6e55f2017-07-17 20:34:22 -04006402 if (size == -1) {
6403 /* Opened BS, have no size */
6404 size = bdrv_getlength(bs);
6405 if (size < 0) {
6406 error_setg_errno(errp, -size, "Could not get size of '%s'",
6407 backing_file);
6408 bdrv_unref(bs);
6409 goto out;
6410 }
6411 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6412 }
6413 bdrv_unref(bs);
6414 }
Eric Blaked9f059a2020-07-06 15:39:54 -05006415 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6416 } else if (backing_file && !backing_fmt) {
6417 warn_report("Deprecated use of unopened backing file without "
6418 "explicit backing format, use of this image requires "
6419 "potentially unsafe format probing");
6420 }
John Snow6e6e55f2017-07-17 20:34:22 -04006421
6422 if (size == -1) {
6423 error_setg(errp, "Image creation needs a size parameter");
6424 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006425 }
6426
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006427 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02006428 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08006429 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006430 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05006431 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006432 }
Chunyan Liu83d05212014-06-05 17:20:51 +08006433
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006434 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08006435
Max Reitzcc84d902013-09-06 17:14:26 +02006436 if (ret == -EFBIG) {
6437 /* This is generally a better message than whatever the driver would
6438 * deliver (especially because of the cluster_size_hint), since that
6439 * is most probably not much different from "image too large". */
6440 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08006441 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02006442 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006443 }
Max Reitzcc84d902013-09-06 17:14:26 +02006444 error_setg(errp, "The image size is too large for file format '%s'"
6445 "%s", fmt, cluster_size_hint);
6446 error_free(local_err);
6447 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006448 }
6449
6450out:
Chunyan Liu83d05212014-06-05 17:20:51 +08006451 qemu_opts_del(opts);
6452 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03006453 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006454}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006455
6456AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6457{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00006458 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006459}
6460
Kevin Wolfe336fd42020-10-05 17:58:53 +02006461AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6462{
6463 Coroutine *self = qemu_coroutine_self();
6464 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6465 AioContext *new_ctx;
6466
6467 /*
6468 * Increase bs->in_flight to ensure that this operation is completed before
6469 * moving the node to a different AioContext. Read new_ctx only afterwards.
6470 */
6471 bdrv_inc_in_flight(bs);
6472
6473 new_ctx = bdrv_get_aio_context(bs);
6474 aio_co_reschedule_self(new_ctx);
6475 return old_ctx;
6476}
6477
6478void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6479{
6480 aio_co_reschedule_self(old_ctx);
6481 bdrv_dec_in_flight(bs);
6482}
6483
Kevin Wolf18c6ac12020-10-05 17:58:54 +02006484void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6485{
6486 AioContext *ctx = bdrv_get_aio_context(bs);
6487
6488 /* In the main thread, bs->aio_context won't change concurrently */
6489 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6490
6491 /*
6492 * We're in coroutine context, so we already hold the lock of the main
6493 * loop AioContext. Don't lock it twice to avoid deadlocks.
6494 */
6495 assert(qemu_in_coroutine());
6496 if (ctx != qemu_get_aio_context()) {
6497 aio_context_acquire(ctx);
6498 }
6499}
6500
6501void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6502{
6503 AioContext *ctx = bdrv_get_aio_context(bs);
6504
6505 assert(qemu_in_coroutine());
6506 if (ctx != qemu_get_aio_context()) {
6507 aio_context_release(ctx);
6508 }
6509}
6510
Fam Zheng052a7572017-04-10 20:09:25 +08006511void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6512{
6513 aio_co_enter(bdrv_get_aio_context(bs), co);
6514}
6515
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006516static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6517{
6518 QLIST_REMOVE(ban, list);
6519 g_free(ban);
6520}
6521
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006522static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006523{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006524 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006525
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006526 assert(!bs->walking_aio_notifiers);
6527 bs->walking_aio_notifiers = true;
6528 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6529 if (baf->deleted) {
6530 bdrv_do_remove_aio_context_notifier(baf);
6531 } else {
6532 baf->detach_aio_context(baf->opaque);
6533 }
Max Reitz33384422014-06-20 21:57:33 +02006534 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006535 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6536 * remove remaining aio notifiers if we aren't called again.
6537 */
6538 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02006539
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006540 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006541 bs->drv->bdrv_detach_aio_context(bs);
6542 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006543
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006544 if (bs->quiesce_counter) {
6545 aio_enable_external(bs->aio_context);
6546 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006547 bs->aio_context = NULL;
6548}
6549
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006550static void bdrv_attach_aio_context(BlockDriverState *bs,
6551 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006552{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006553 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006554
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006555 if (bs->quiesce_counter) {
6556 aio_disable_external(new_context);
6557 }
6558
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006559 bs->aio_context = new_context;
6560
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006561 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006562 bs->drv->bdrv_attach_aio_context(bs, new_context);
6563 }
Max Reitz33384422014-06-20 21:57:33 +02006564
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006565 assert(!bs->walking_aio_notifiers);
6566 bs->walking_aio_notifiers = true;
6567 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6568 if (ban->deleted) {
6569 bdrv_do_remove_aio_context_notifier(ban);
6570 } else {
6571 ban->attached_aio_context(new_context, ban->opaque);
6572 }
Max Reitz33384422014-06-20 21:57:33 +02006573 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006574 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006575}
6576
Kevin Wolf42a65f02019-05-07 18:31:38 +02006577/*
6578 * Changes the AioContext used for fd handlers, timers, and BHs by this
6579 * BlockDriverState and all its children and parents.
6580 *
Max Reitz43eaaae2019-07-22 15:30:54 +02006581 * Must be called from the main AioContext.
6582 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02006583 * The caller must own the AioContext lock for the old AioContext of bs, but it
6584 * must not own the AioContext lock for new_context (unless new_context is the
6585 * same as the current context of bs).
6586 *
6587 * @ignore will accumulate all visited BdrvChild object. The caller is
6588 * responsible for freeing the list afterwards.
6589 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02006590void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6591 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006592{
Max Reitze037c092019-07-19 11:26:14 +02006593 AioContext *old_context = bdrv_get_aio_context(bs);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006594 GSList *children_to_process = NULL;
6595 GSList *parents_to_process = NULL;
6596 GSList *entry;
6597 BdrvChild *child, *parent;
Kevin Wolf0d837082019-05-06 19:17:58 +02006598
Max Reitz43eaaae2019-07-22 15:30:54 +02006599 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6600
Max Reitze037c092019-07-19 11:26:14 +02006601 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03006602 return;
6603 }
6604
Kevin Wolfd70d5952019-02-08 16:53:37 +01006605 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02006606
6607 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006608 if (g_slist_find(*ignore, child)) {
6609 continue;
6610 }
6611 *ignore = g_slist_prepend(*ignore, child);
Sergio Lopez722d8e72021-02-01 13:50:31 +01006612 children_to_process = g_slist_prepend(children_to_process, child);
Kevin Wolf53a7d042019-05-06 19:17:59 +02006613 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006614
6615 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6616 if (g_slist_find(*ignore, parent)) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006617 continue;
6618 }
Sergio Lopez722d8e72021-02-01 13:50:31 +01006619 *ignore = g_slist_prepend(*ignore, parent);
6620 parents_to_process = g_slist_prepend(parents_to_process, parent);
Kevin Wolf0d837082019-05-06 19:17:58 +02006621 }
6622
Sergio Lopez722d8e72021-02-01 13:50:31 +01006623 for (entry = children_to_process;
6624 entry != NULL;
6625 entry = g_slist_next(entry)) {
6626 child = entry->data;
6627 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6628 }
6629 g_slist_free(children_to_process);
6630
6631 for (entry = parents_to_process;
6632 entry != NULL;
6633 entry = g_slist_next(entry)) {
6634 parent = entry->data;
6635 assert(parent->klass->set_aio_ctx);
6636 parent->klass->set_aio_ctx(parent, new_context, ignore);
6637 }
6638 g_slist_free(parents_to_process);
6639
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006640 bdrv_detach_aio_context(bs);
6641
Max Reitze037c092019-07-19 11:26:14 +02006642 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02006643 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006644 aio_context_acquire(new_context);
6645 }
6646
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006647 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02006648
6649 /*
6650 * If this function was recursively called from
6651 * bdrv_set_aio_context_ignore(), there may be nodes in the
6652 * subtree that have not yet been moved to the new AioContext.
6653 * Release the old one so bdrv_drained_end() can poll them.
6654 */
Max Reitz43eaaae2019-07-22 15:30:54 +02006655 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006656 aio_context_release(old_context);
6657 }
6658
Kevin Wolfd70d5952019-02-08 16:53:37 +01006659 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02006660
Max Reitz43eaaae2019-07-22 15:30:54 +02006661 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006662 aio_context_acquire(old_context);
6663 }
Max Reitz43eaaae2019-07-22 15:30:54 +02006664 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006665 aio_context_release(new_context);
6666 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006667}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02006668
Kevin Wolf5d231842019-05-06 19:17:56 +02006669static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6670 GSList **ignore, Error **errp)
6671{
6672 if (g_slist_find(*ignore, c)) {
6673 return true;
6674 }
6675 *ignore = g_slist_prepend(*ignore, c);
6676
Max Reitzbd86fb92020-05-13 13:05:13 +02006677 /*
6678 * A BdrvChildClass that doesn't handle AioContext changes cannot
6679 * tolerate any AioContext changes
6680 */
6681 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006682 char *user = bdrv_child_user_desc(c);
6683 error_setg(errp, "Changing iothreads is not supported by %s", user);
6684 g_free(user);
6685 return false;
6686 }
Max Reitzbd86fb92020-05-13 13:05:13 +02006687 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006688 assert(!errp || *errp);
6689 return false;
6690 }
6691 return true;
6692}
6693
6694bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6695 GSList **ignore, Error **errp)
6696{
6697 if (g_slist_find(*ignore, c)) {
6698 return true;
6699 }
6700 *ignore = g_slist_prepend(*ignore, c);
6701 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6702}
6703
6704/* @ignore will accumulate all visited BdrvChild object. The caller is
6705 * responsible for freeing the list afterwards. */
6706bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6707 GSList **ignore, Error **errp)
6708{
6709 BdrvChild *c;
6710
6711 if (bdrv_get_aio_context(bs) == ctx) {
6712 return true;
6713 }
6714
6715 QLIST_FOREACH(c, &bs->parents, next_parent) {
6716 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6717 return false;
6718 }
6719 }
6720 QLIST_FOREACH(c, &bs->children, next) {
6721 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6722 return false;
6723 }
6724 }
6725
6726 return true;
6727}
6728
6729int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6730 BdrvChild *ignore_child, Error **errp)
6731{
6732 GSList *ignore;
6733 bool ret;
6734
6735 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6736 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6737 g_slist_free(ignore);
6738
6739 if (!ret) {
6740 return -EPERM;
6741 }
6742
Kevin Wolf53a7d042019-05-06 19:17:59 +02006743 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6744 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6745 g_slist_free(ignore);
6746
Kevin Wolf5d231842019-05-06 19:17:56 +02006747 return 0;
6748}
6749
6750int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6751 Error **errp)
6752{
6753 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6754}
6755
Max Reitz33384422014-06-20 21:57:33 +02006756void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6757 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6758 void (*detach_aio_context)(void *opaque), void *opaque)
6759{
6760 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6761 *ban = (BdrvAioNotifier){
6762 .attached_aio_context = attached_aio_context,
6763 .detach_aio_context = detach_aio_context,
6764 .opaque = opaque
6765 };
6766
6767 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6768}
6769
6770void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6771 void (*attached_aio_context)(AioContext *,
6772 void *),
6773 void (*detach_aio_context)(void *),
6774 void *opaque)
6775{
6776 BdrvAioNotifier *ban, *ban_next;
6777
6778 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6779 if (ban->attached_aio_context == attached_aio_context &&
6780 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006781 ban->opaque == opaque &&
6782 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02006783 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006784 if (bs->walking_aio_notifiers) {
6785 ban->deleted = true;
6786 } else {
6787 bdrv_do_remove_aio_context_notifier(ban);
6788 }
Max Reitz33384422014-06-20 21:57:33 +02006789 return;
6790 }
6791 }
6792
6793 abort();
6794}
6795
Max Reitz77485432014-10-27 11:12:50 +01006796int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02006797 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02006798 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02006799 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02006800{
Max Reitzd470ad42017-11-10 21:31:09 +01006801 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02006802 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01006803 return -ENOMEDIUM;
6804 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006805 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02006806 error_setg(errp, "Block driver '%s' does not support option amendment",
6807 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02006808 return -ENOTSUP;
6809 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02006810 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
6811 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02006812}
Benoît Canetf6186f42013-10-02 14:33:48 +02006813
Max Reitz5d69b5a2020-02-18 11:34:41 +01006814/*
6815 * This function checks whether the given @to_replace is allowed to be
6816 * replaced by a node that always shows the same data as @bs. This is
6817 * used for example to verify whether the mirror job can replace
6818 * @to_replace by the target mirrored from @bs.
6819 * To be replaceable, @bs and @to_replace may either be guaranteed to
6820 * always show the same data (because they are only connected through
6821 * filters), or some driver may allow replacing one of its children
6822 * because it can guarantee that this child's data is not visible at
6823 * all (for example, for dissenting quorum children that have no other
6824 * parents).
6825 */
6826bool bdrv_recurse_can_replace(BlockDriverState *bs,
6827 BlockDriverState *to_replace)
6828{
Max Reitz93393e62019-06-12 17:03:38 +02006829 BlockDriverState *filtered;
6830
Max Reitz5d69b5a2020-02-18 11:34:41 +01006831 if (!bs || !bs->drv) {
6832 return false;
6833 }
6834
6835 if (bs == to_replace) {
6836 return true;
6837 }
6838
6839 /* See what the driver can do */
6840 if (bs->drv->bdrv_recurse_can_replace) {
6841 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
6842 }
6843
6844 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02006845 filtered = bdrv_filter_bs(bs);
6846 if (filtered) {
6847 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01006848 }
6849
6850 /* Safe default */
6851 return false;
6852}
6853
Max Reitz810803a2020-02-18 11:34:44 +01006854/*
6855 * Check whether the given @node_name can be replaced by a node that
6856 * has the same data as @parent_bs. If so, return @node_name's BDS;
6857 * NULL otherwise.
6858 *
6859 * @node_name must be a (recursive) *child of @parent_bs (or this
6860 * function will return NULL).
6861 *
6862 * The result (whether the node can be replaced or not) is only valid
6863 * for as long as no graph or permission changes occur.
6864 */
Wen Congyange12f3782015-07-17 10:12:22 +08006865BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6866 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02006867{
6868 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006869 AioContext *aio_context;
6870
Benoît Canet09158f02014-06-27 18:25:25 +02006871 if (!to_replace_bs) {
Connor Kuehl785ec4b2021-03-05 09:19:28 -06006872 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Benoît Canet09158f02014-06-27 18:25:25 +02006873 return NULL;
6874 }
6875
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006876 aio_context = bdrv_get_aio_context(to_replace_bs);
6877 aio_context_acquire(aio_context);
6878
Benoît Canet09158f02014-06-27 18:25:25 +02006879 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006880 to_replace_bs = NULL;
6881 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02006882 }
6883
6884 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6885 * most non filter in order to prevent data corruption.
6886 * Another benefit is that this tests exclude backing files which are
6887 * blocked by the backing blockers.
6888 */
Max Reitz810803a2020-02-18 11:34:44 +01006889 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
6890 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
6891 "because it cannot be guaranteed that doing so would not "
6892 "lead to an abrupt change of visible data",
6893 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006894 to_replace_bs = NULL;
6895 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02006896 }
6897
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006898out:
6899 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02006900 return to_replace_bs;
6901}
Ming Lei448ad912014-07-04 18:04:33 +08006902
Max Reitz97e2f022019-02-01 20:29:27 +01006903/**
6904 * Iterates through the list of runtime option keys that are said to
6905 * be "strong" for a BDS. An option is called "strong" if it changes
6906 * a BDS's data. For example, the null block driver's "size" and
6907 * "read-zeroes" options are strong, but its "latency-ns" option is
6908 * not.
6909 *
6910 * If a key returned by this function ends with a dot, all options
6911 * starting with that prefix are strong.
6912 */
6913static const char *const *strong_options(BlockDriverState *bs,
6914 const char *const *curopt)
6915{
6916 static const char *const global_options[] = {
6917 "driver", "filename", NULL
6918 };
6919
6920 if (!curopt) {
6921 return &global_options[0];
6922 }
6923
6924 curopt++;
6925 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6926 curopt = bs->drv->strong_runtime_opts;
6927 }
6928
6929 return (curopt && *curopt) ? curopt : NULL;
6930}
6931
6932/**
6933 * Copies all strong runtime options from bs->options to the given
6934 * QDict. The set of strong option keys is determined by invoking
6935 * strong_options().
6936 *
6937 * Returns true iff any strong option was present in bs->options (and
6938 * thus copied to the target QDict) with the exception of "filename"
6939 * and "driver". The caller is expected to use this value to decide
6940 * whether the existence of strong options prevents the generation of
6941 * a plain filename.
6942 */
6943static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6944{
6945 bool found_any = false;
6946 const char *const *option_name = NULL;
6947
6948 if (!bs->drv) {
6949 return false;
6950 }
6951
6952 while ((option_name = strong_options(bs, option_name))) {
6953 bool option_given = false;
6954
6955 assert(strlen(*option_name) > 0);
6956 if ((*option_name)[strlen(*option_name) - 1] != '.') {
6957 QObject *entry = qdict_get(bs->options, *option_name);
6958 if (!entry) {
6959 continue;
6960 }
6961
6962 qdict_put_obj(d, *option_name, qobject_ref(entry));
6963 option_given = true;
6964 } else {
6965 const QDictEntry *entry;
6966 for (entry = qdict_first(bs->options); entry;
6967 entry = qdict_next(bs->options, entry))
6968 {
6969 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6970 qdict_put_obj(d, qdict_entry_key(entry),
6971 qobject_ref(qdict_entry_value(entry)));
6972 option_given = true;
6973 }
6974 }
6975 }
6976
6977 /* While "driver" and "filename" need to be included in a JSON filename,
6978 * their existence does not prohibit generation of a plain filename. */
6979 if (!found_any && option_given &&
6980 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6981 {
6982 found_any = true;
6983 }
6984 }
6985
Max Reitz62a01a272019-02-01 20:29:34 +01006986 if (!qdict_haskey(d, "driver")) {
6987 /* Drivers created with bdrv_new_open_driver() may not have a
6988 * @driver option. Add it here. */
6989 qdict_put_str(d, "driver", bs->drv->format_name);
6990 }
6991
Max Reitz97e2f022019-02-01 20:29:27 +01006992 return found_any;
6993}
6994
Max Reitz90993622019-02-01 20:29:09 +01006995/* Note: This function may return false positives; it may return true
6996 * even if opening the backing file specified by bs's image header
6997 * would result in exactly bs->backing. */
Max Reitz0b877d02018-08-01 20:34:11 +02006998bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01006999{
7000 if (bs->backing) {
7001 return strcmp(bs->auto_backing_file,
7002 bs->backing->bs->filename);
7003 } else {
7004 /* No backing BDS, so if the image header reports any backing
7005 * file, it must have been suppressed */
7006 return bs->auto_backing_file[0] != '\0';
7007 }
7008}
7009
Max Reitz91af7012014-07-18 20:24:56 +02007010/* Updates the following BDS fields:
7011 * - exact_filename: A filename which may be used for opening a block device
7012 * which (mostly) equals the given BDS (even without any
7013 * other options; so reading and writing must return the same
7014 * results, but caching etc. may be different)
7015 * - full_open_options: Options which, when given when opening a block device
7016 * (without a filename), result in a BDS (mostly)
7017 * equalling the given one
7018 * - filename: If exact_filename is set, it is copied here. Otherwise,
7019 * full_open_options is converted to a JSON object, prefixed with
7020 * "json:" (for use through the JSON pseudo protocol) and put here.
7021 */
7022void bdrv_refresh_filename(BlockDriverState *bs)
7023{
7024 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01007025 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02007026 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02007027 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01007028 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01007029 bool generate_json_filename; /* Whether our default implementation should
7030 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02007031
7032 if (!drv) {
7033 return;
7034 }
7035
Max Reitze24518e2019-02-01 20:29:06 +01007036 /* This BDS's file name may depend on any of its children's file names, so
7037 * refresh those first */
7038 QLIST_FOREACH(child, &bs->children, next) {
7039 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02007040 }
7041
Max Reitzbb808d52019-02-01 20:29:07 +01007042 if (bs->implicit) {
7043 /* For implicit nodes, just copy everything from the single child */
7044 child = QLIST_FIRST(&bs->children);
7045 assert(QLIST_NEXT(child, next) == NULL);
7046
7047 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7048 child->bs->exact_filename);
7049 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7050
Pan Nengyuancb895612020-01-16 16:56:00 +08007051 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01007052 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7053
7054 return;
7055 }
7056
Max Reitz90993622019-02-01 20:29:09 +01007057 backing_overridden = bdrv_backing_overridden(bs);
7058
7059 if (bs->open_flags & BDRV_O_NO_IO) {
7060 /* Without I/O, the backing file does not change anything.
7061 * Therefore, in such a case (primarily qemu-img), we can
7062 * pretend the backing file has not been overridden even if
7063 * it technically has been. */
7064 backing_overridden = false;
7065 }
7066
Max Reitz97e2f022019-02-01 20:29:27 +01007067 /* Gather the options QDict */
7068 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01007069 generate_json_filename = append_strong_runtime_options(opts, bs);
7070 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01007071
7072 if (drv->bdrv_gather_child_options) {
7073 /* Some block drivers may not want to present all of their children's
7074 * options, or name them differently from BdrvChild.name */
7075 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7076 } else {
7077 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02007078 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01007079 /* We can skip the backing BDS if it has not been overridden */
7080 continue;
7081 }
7082
7083 qdict_put(opts, child->name,
7084 qobject_ref(child->bs->full_open_options));
7085 }
7086
7087 if (backing_overridden && !bs->backing) {
7088 /* Force no backing file */
7089 qdict_put_null(opts, "backing");
7090 }
7091 }
7092
7093 qobject_unref(bs->full_open_options);
7094 bs->full_open_options = opts;
7095
Max Reitz52f72d62019-06-12 17:43:03 +02007096 primary_child_bs = bdrv_primary_bs(bs);
7097
Max Reitz998b3a12019-02-01 20:29:28 +01007098 if (drv->bdrv_refresh_filename) {
7099 /* Obsolete information is of no use here, so drop the old file name
7100 * information before refreshing it */
7101 bs->exact_filename[0] = '\0';
7102
7103 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02007104 } else if (primary_child_bs) {
7105 /*
7106 * Try to reconstruct valid information from the underlying
7107 * file -- this only works for format nodes (filter nodes
7108 * cannot be probed and as such must be selected by the user
7109 * either through an options dict, or through a special
7110 * filename which the filter driver must construct in its
7111 * .bdrv_refresh_filename() implementation).
7112 */
Max Reitz998b3a12019-02-01 20:29:28 +01007113
7114 bs->exact_filename[0] = '\0';
7115
Max Reitzfb695c72019-02-01 20:29:29 +01007116 /*
7117 * We can use the underlying file's filename if:
7118 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02007119 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01007120 * - the file is a protocol BDS, and
7121 * - opening that file (as this BDS's format) will automatically create
7122 * the BDS tree we have right now, that is:
7123 * - the user did not significantly change this BDS's behavior with
7124 * some explicit (strong) options
7125 * - no non-file child of this BDS has been overridden by the user
7126 * Both of these conditions are represented by generate_json_filename.
7127 */
Max Reitz52f72d62019-06-12 17:43:03 +02007128 if (primary_child_bs->exact_filename[0] &&
7129 primary_child_bs->drv->bdrv_file_open &&
7130 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01007131 {
Max Reitz52f72d62019-06-12 17:43:03 +02007132 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01007133 }
7134 }
7135
Max Reitz91af7012014-07-18 20:24:56 +02007136 if (bs->exact_filename[0]) {
7137 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01007138 } else {
Markus Armbrustereab3a462020-12-11 18:11:37 +01007139 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05007140 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
Markus Armbrustereab3a462020-12-11 18:11:37 +01007141 json->str) >= sizeof(bs->filename)) {
Eric Blake5c86bdf2020-06-08 13:26:38 -05007142 /* Give user a hint if we truncated things. */
7143 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7144 }
Markus Armbrustereab3a462020-12-11 18:11:37 +01007145 g_string_free(json, true);
Max Reitz91af7012014-07-18 20:24:56 +02007146 }
7147}
Wen Congyange06018a2016-05-10 15:36:37 +08007148
Max Reitz1e89d0f2019-02-01 20:29:18 +01007149char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7150{
7151 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02007152 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01007153
7154 if (!drv) {
7155 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7156 return NULL;
7157 }
7158
7159 if (drv->bdrv_dirname) {
7160 return drv->bdrv_dirname(bs, errp);
7161 }
7162
Max Reitz52f72d62019-06-12 17:43:03 +02007163 child_bs = bdrv_primary_bs(bs);
7164 if (child_bs) {
7165 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007166 }
7167
7168 bdrv_refresh_filename(bs);
7169 if (bs->exact_filename[0] != '\0') {
7170 return path_combine(bs->exact_filename, "");
7171 }
7172
7173 error_setg(errp, "Cannot generate a base directory for %s nodes",
7174 drv->format_name);
7175 return NULL;
7176}
7177
Wen Congyange06018a2016-05-10 15:36:37 +08007178/*
7179 * Hot add/remove a BDS's child. So the user can take a child offline when
7180 * it is broken and take a new child online
7181 */
7182void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7183 Error **errp)
7184{
7185
7186 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7187 error_setg(errp, "The node %s does not support adding a child",
7188 bdrv_get_device_or_node_name(parent_bs));
7189 return;
7190 }
7191
7192 if (!QLIST_EMPTY(&child_bs->parents)) {
7193 error_setg(errp, "The node %s already has a parent",
7194 child_bs->node_name);
7195 return;
7196 }
7197
7198 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7199}
7200
7201void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7202{
7203 BdrvChild *tmp;
7204
7205 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7206 error_setg(errp, "The node %s does not support removing a child",
7207 bdrv_get_device_or_node_name(parent_bs));
7208 return;
7209 }
7210
7211 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7212 if (tmp == child) {
7213 break;
7214 }
7215 }
7216
7217 if (!tmp) {
7218 error_setg(errp, "The node %s does not have a child named %s",
7219 bdrv_get_device_or_node_name(parent_bs),
7220 bdrv_get_device_or_node_name(child->bs));
7221 return;
7222 }
7223
7224 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7225}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007226
7227int bdrv_make_empty(BdrvChild *c, Error **errp)
7228{
7229 BlockDriver *drv = c->bs->drv;
7230 int ret;
7231
7232 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7233
7234 if (!drv->bdrv_make_empty) {
7235 error_setg(errp, "%s does not support emptying nodes",
7236 drv->format_name);
7237 return -ENOTSUP;
7238 }
7239
7240 ret = drv->bdrv_make_empty(c->bs);
7241 if (ret < 0) {
7242 error_setg_errno(errp, -ret, "Failed to empty %s",
7243 c->bs->filename);
7244 return ret;
7245 }
7246
7247 return 0;
7248}
Max Reitz9a6fc882019-05-31 15:23:11 +02007249
7250/*
7251 * Return the child that @bs acts as an overlay for, and from which data may be
7252 * copied in COW or COR operations. Usually this is the backing file.
7253 */
7254BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7255{
7256 if (!bs || !bs->drv) {
7257 return NULL;
7258 }
7259
7260 if (bs->drv->is_filter) {
7261 return NULL;
7262 }
7263
7264 if (!bs->backing) {
7265 return NULL;
7266 }
7267
7268 assert(bs->backing->role & BDRV_CHILD_COW);
7269 return bs->backing;
7270}
7271
7272/*
7273 * If @bs acts as a filter for exactly one of its children, return
7274 * that child.
7275 */
7276BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7277{
7278 BdrvChild *c;
7279
7280 if (!bs || !bs->drv) {
7281 return NULL;
7282 }
7283
7284 if (!bs->drv->is_filter) {
7285 return NULL;
7286 }
7287
7288 /* Only one of @backing or @file may be used */
7289 assert(!(bs->backing && bs->file));
7290
7291 c = bs->backing ?: bs->file;
7292 if (!c) {
7293 return NULL;
7294 }
7295
7296 assert(c->role & BDRV_CHILD_FILTERED);
7297 return c;
7298}
7299
7300/*
7301 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7302 * whichever is non-NULL.
7303 *
7304 * Return NULL if both are NULL.
7305 */
7306BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7307{
7308 BdrvChild *cow_child = bdrv_cow_child(bs);
7309 BdrvChild *filter_child = bdrv_filter_child(bs);
7310
7311 /* Filter nodes cannot have COW backing files */
7312 assert(!(cow_child && filter_child));
7313
7314 return cow_child ?: filter_child;
7315}
7316
7317/*
7318 * Return the primary child of this node: For filters, that is the
7319 * filtered child. For other nodes, that is usually the child storing
7320 * metadata.
7321 * (A generally more helpful description is that this is (usually) the
7322 * child that has the same filename as @bs.)
7323 *
7324 * Drivers do not necessarily have a primary child; for example quorum
7325 * does not.
7326 */
7327BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7328{
7329 BdrvChild *c, *found = NULL;
7330
7331 QLIST_FOREACH(c, &bs->children, next) {
7332 if (c->role & BDRV_CHILD_PRIMARY) {
7333 assert(!found);
7334 found = c;
7335 }
7336 }
7337
7338 return found;
7339}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007340
7341static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7342 bool stop_on_explicit_filter)
7343{
7344 BdrvChild *c;
7345
7346 if (!bs) {
7347 return NULL;
7348 }
7349
7350 while (!(stop_on_explicit_filter && !bs->implicit)) {
7351 c = bdrv_filter_child(bs);
7352 if (!c) {
7353 /*
7354 * A filter that is embedded in a working block graph must
7355 * have a child. Assert this here so this function does
7356 * not return a filter node that is not expected by the
7357 * caller.
7358 */
7359 assert(!bs->drv || !bs->drv->is_filter);
7360 break;
7361 }
7362 bs = c->bs;
7363 }
7364 /*
7365 * Note that this treats nodes with bs->drv == NULL as not being
7366 * filters (bs->drv == NULL should be replaced by something else
7367 * anyway).
7368 * The advantage of this behavior is that this function will thus
7369 * always return a non-NULL value (given a non-NULL @bs).
7370 */
7371
7372 return bs;
7373}
7374
7375/*
7376 * Return the first BDS that has not been added implicitly or that
7377 * does not have a filtered child down the chain starting from @bs
7378 * (including @bs itself).
7379 */
7380BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7381{
7382 return bdrv_do_skip_filters(bs, true);
7383}
7384
7385/*
7386 * Return the first BDS that does not have a filtered child down the
7387 * chain starting from @bs (including @bs itself).
7388 */
7389BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7390{
7391 return bdrv_do_skip_filters(bs, false);
7392}
7393
7394/*
7395 * For a backing chain, return the first non-filter backing image of
7396 * the first non-filter image.
7397 */
7398BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7399{
7400 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7401}