blob: f1cedac362577c2796b69e3972e9c74a89d55dc9 [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"
Kevin Wolfcd7fca92016-07-06 11:22:39 +020029#include "block/nbd.h"
Max Reitz609f45e2018-06-14 21:14:28 +020030#include "block/qdict.h"
Markus Armbrusterd49b6832015-03-17 18:29:20 +010031#include "qemu/error-report.h"
Marc-André Lureau5e5733e2019-08-29 22:34:43 +040032#include "block/module_block.h"
Markus Armbrusterdb725812019-08-12 07:23:50 +020033#include "qemu/main-loop.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010034#include "qemu/module.h"
Markus Armbrustere688df62018-02-01 12:18:31 +010035#include "qapi/error.h"
Markus Armbruster452fcdb2018-02-01 12:18:39 +010036#include "qapi/qmp/qdict.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010037#include "qapi/qmp/qjson.h"
Max Reitze59a0cf2018-02-24 16:40:32 +010038#include "qapi/qmp/qnull.h"
Markus Armbrusterfc81fa12018-02-01 12:18:40 +010039#include "qapi/qmp/qstring.h"
Kevin Wolfe1d74bc2018-01-10 15:52:33 +010040#include "qapi/qobject-output-visitor.h"
41#include "qapi/qapi-visit-block-core.h"
Markus Armbrusterbfb197e2014-10-07 13:59:11 +020042#include "sysemu/block-backend.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010043#include "sysemu/sysemu.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010044#include "qemu/notify.h"
Markus Armbruster922a01a2018-02-01 12:18:46 +010045#include "qemu/option.h"
Daniel P. Berrange10817bf2015-09-01 14:48:02 +010046#include "qemu/coroutine.h"
Benoît Canetc13163f2014-01-23 21:31:34 +010047#include "block/qapi.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010048#include "qemu/timer.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020049#include "qemu/cutils.h"
50#include "qemu/id.h"
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +030051#include "block/coroutines.h"
bellardfc01f7e2003-06-30 10:03:06 +000052
Juan Quintela71e72a12009-07-27 16:12:56 +020053#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000054#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000055#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000056#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000057#include <sys/disk.h>
58#endif
blueswir1c5e97232009-03-07 20:06:23 +000059#endif
bellard7674e7b2005-04-26 21:59:26 +000060
aliguori49dc7682009-03-08 16:26:59 +000061#ifdef _WIN32
62#include <windows.h>
63#endif
64
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010065#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
66
Benoît Canetdc364f42014-01-23 21:31:32 +010067static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
68 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
69
Max Reitz2c1d04e2016-01-29 16:36:11 +010070static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
71 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
72
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010073static QLIST_HEAD(, BlockDriver) bdrv_drivers =
74 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000075
Max Reitz5b363932016-05-17 16:41:31 +020076static BlockDriverState *bdrv_open_inherit(const char *filename,
77 const char *reference,
78 QDict *options, int flags,
79 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +020080 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +020081 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +020082 Error **errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +020083
Markus Armbrustereb852012009-10-27 18:41:44 +010084/* If non-zero, use only whitelisted block drivers */
85static int use_bdrv_whitelist;
86
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000087#ifdef _WIN32
88static int is_windows_drive_prefix(const char *filename)
89{
90 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
91 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
92 filename[1] == ':');
93}
94
95int is_windows_drive(const char *filename)
96{
97 if (is_windows_drive_prefix(filename) &&
98 filename[2] == '\0')
99 return 1;
100 if (strstart(filename, "\\\\.\\", NULL) ||
101 strstart(filename, "//./", NULL))
102 return 1;
103 return 0;
104}
105#endif
106
Kevin Wolf339064d2013-11-28 10:23:32 +0100107size_t bdrv_opt_mem_align(BlockDriverState *bs)
108{
109 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300110 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800111 return MAX(4096, qemu_real_host_page_size);
Kevin Wolf339064d2013-11-28 10:23:32 +0100112 }
113
114 return bs->bl.opt_mem_alignment;
115}
116
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300117size_t bdrv_min_mem_align(BlockDriverState *bs)
118{
119 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300120 /* page size or 4k (hdd sector size) should be on the safe side */
Wei Yang038adc22019-10-13 10:11:45 +0800121 return MAX(4096, qemu_real_host_page_size);
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300122 }
123
124 return bs->bl.min_mem_alignment;
125}
126
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000127/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100128int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000129{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200130 const char *p;
131
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000132#ifdef _WIN32
133 if (is_windows_drive(path) ||
134 is_windows_drive_prefix(path)) {
135 return 0;
136 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200137 p = path + strcspn(path, ":/\\");
138#else
139 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000140#endif
141
Paolo Bonzini947995c2012-05-08 16:51:48 +0200142 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000143}
144
bellard83f64092006-08-01 16:21:11 +0000145int path_is_absolute(const char *path)
146{
bellard21664422007-01-07 18:22:37 +0000147#ifdef _WIN32
148 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200149 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000150 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200151 }
152 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000153#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200154 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000155#endif
bellard83f64092006-08-01 16:21:11 +0000156}
157
Max Reitz009b03a2019-02-01 20:29:13 +0100158/* if filename is absolute, just return its duplicate. Otherwise, build a
bellard83f64092006-08-01 16:21:11 +0000159 path to it by considering it is relative to base_path. URL are
160 supported. */
Max Reitz009b03a2019-02-01 20:29:13 +0100161char *path_combine(const char *base_path, const char *filename)
bellard83f64092006-08-01 16:21:11 +0000162{
Max Reitz009b03a2019-02-01 20:29:13 +0100163 const char *protocol_stripped = NULL;
bellard83f64092006-08-01 16:21:11 +0000164 const char *p, *p1;
Max Reitz009b03a2019-02-01 20:29:13 +0100165 char *result;
bellard83f64092006-08-01 16:21:11 +0000166 int len;
167
bellard83f64092006-08-01 16:21:11 +0000168 if (path_is_absolute(filename)) {
Max Reitz009b03a2019-02-01 20:29:13 +0100169 return g_strdup(filename);
bellard83f64092006-08-01 16:21:11 +0000170 }
Max Reitz009b03a2019-02-01 20:29:13 +0100171
172 if (path_has_protocol(base_path)) {
173 protocol_stripped = strchr(base_path, ':');
174 if (protocol_stripped) {
175 protocol_stripped++;
176 }
177 }
178 p = protocol_stripped ?: base_path;
179
180 p1 = strrchr(base_path, '/');
181#ifdef _WIN32
182 {
183 const char *p2;
184 p2 = strrchr(base_path, '\\');
185 if (!p1 || p2 > p1) {
186 p1 = p2;
187 }
188 }
189#endif
190 if (p1) {
191 p1++;
192 } else {
193 p1 = base_path;
194 }
195 if (p1 > p) {
196 p = p1;
197 }
198 len = p - base_path;
199
200 result = g_malloc(len + strlen(filename) + 1);
201 memcpy(result, base_path, len);
202 strcpy(result + len, filename);
203
204 return result;
205}
206
Max Reitz03c320d2017-05-22 21:52:16 +0200207/*
208 * Helper function for bdrv_parse_filename() implementations to remove optional
209 * protocol prefixes (especially "file:") from a filename and for putting the
210 * stripped filename into the options QDict if there is such a prefix.
211 */
212void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
213 QDict *options)
214{
215 if (strstart(filename, prefix, &filename)) {
216 /* Stripping the explicit protocol prefix may result in a protocol
217 * prefix being (wrongly) detected (if the filename contains a colon) */
218 if (path_has_protocol(filename)) {
219 QString *fat_filename;
220
221 /* This means there is some colon before the first slash; therefore,
222 * this cannot be an absolute path */
223 assert(!path_is_absolute(filename));
224
225 /* And we can thus fix the protocol detection issue by prefixing it
226 * by "./" */
227 fat_filename = qstring_from_str("./");
228 qstring_append(fat_filename, filename);
229
230 assert(!path_has_protocol(qstring_get_str(fat_filename)));
231
232 qdict_put(options, "filename", fat_filename);
233 } else {
234 /* If no protocol prefix was detected, we can use the shortened
235 * filename as-is */
236 qdict_put_str(options, "filename", filename);
237 }
238 }
239}
240
241
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200242/* Returns whether the image file is opened as read-only. Note that this can
243 * return false and writing to the image file is still not possible because the
244 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400245bool bdrv_is_read_only(BlockDriverState *bs)
246{
247 return bs->read_only;
248}
249
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200250int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
251 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400252{
Jeff Codye2b82472017-04-07 16:55:26 -0400253 /* Do not set read_only if copy_on_read is enabled */
254 if (bs->copy_on_read && read_only) {
255 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
256 bdrv_get_device_or_node_name(bs));
257 return -EINVAL;
258 }
259
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400260 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200261 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
262 !ignore_allow_rdw)
263 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400264 error_setg(errp, "Node '%s' is read only",
265 bdrv_get_device_or_node_name(bs));
266 return -EPERM;
267 }
268
Jeff Cody45803a02017-04-07 16:55:29 -0400269 return 0;
270}
271
Kevin Wolfeaa24102018-10-12 11:27:41 +0200272/*
273 * Called by a driver that can only provide a read-only image.
274 *
275 * Returns 0 if the node is already read-only or it could switch the node to
276 * read-only because BDRV_O_AUTO_RDONLY is set.
277 *
278 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
279 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
280 * is not NULL, it is used as the error message for the Error object.
281 */
282int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
283 Error **errp)
Jeff Cody45803a02017-04-07 16:55:29 -0400284{
285 int ret = 0;
286
Kevin Wolfeaa24102018-10-12 11:27:41 +0200287 if (!(bs->open_flags & BDRV_O_RDWR)) {
288 return 0;
289 }
290 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
291 goto fail;
292 }
293
294 ret = bdrv_can_set_read_only(bs, true, false, NULL);
Jeff Cody45803a02017-04-07 16:55:29 -0400295 if (ret < 0) {
Kevin Wolfeaa24102018-10-12 11:27:41 +0200296 goto fail;
Jeff Cody45803a02017-04-07 16:55:29 -0400297 }
298
Kevin Wolfeaa24102018-10-12 11:27:41 +0200299 bs->read_only = true;
300 bs->open_flags &= ~BDRV_O_RDWR;
Kevin Wolfeeae6a52018-10-09 16:57:12 +0200301
Jeff Codye2b82472017-04-07 16:55:26 -0400302 return 0;
Kevin Wolfeaa24102018-10-12 11:27:41 +0200303
304fail:
305 error_setg(errp, "%s", errmsg ?: "Image is read-only");
306 return -EACCES;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400307}
308
Max Reitz645ae7d2019-02-01 20:29:14 +0100309/*
310 * If @backing is empty, this function returns NULL without setting
311 * @errp. In all other cases, NULL will only be returned with @errp
312 * set.
313 *
314 * Therefore, a return value of NULL without @errp set means that
315 * there is no backing file; if @errp is set, there is one but its
316 * absolute filename cannot be generated.
317 */
318char *bdrv_get_full_backing_filename_from_filename(const char *backed,
319 const char *backing,
320 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100321{
Max Reitz645ae7d2019-02-01 20:29:14 +0100322 if (backing[0] == '\0') {
323 return NULL;
324 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
325 return g_strdup(backing);
Max Reitz9f074292014-11-26 17:20:26 +0100326 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
327 error_setg(errp, "Cannot use relative backing file names for '%s'",
328 backed);
Max Reitz645ae7d2019-02-01 20:29:14 +0100329 return NULL;
Max Reitz0a828552014-11-26 17:20:25 +0100330 } else {
Max Reitz645ae7d2019-02-01 20:29:14 +0100331 return path_combine(backed, backing);
Max Reitz0a828552014-11-26 17:20:25 +0100332 }
333}
334
Max Reitz9f4793d2019-02-01 20:29:16 +0100335/*
336 * If @filename is empty or NULL, this function returns NULL without
337 * setting @errp. In all other cases, NULL will only be returned with
338 * @errp set.
339 */
340static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
341 const char *filename, Error **errp)
342{
Max Reitz8df68612019-02-01 20:29:23 +0100343 char *dir, *full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100344
Max Reitz8df68612019-02-01 20:29:23 +0100345 if (!filename || filename[0] == '\0') {
346 return NULL;
347 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
348 return g_strdup(filename);
349 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100350
Max Reitz8df68612019-02-01 20:29:23 +0100351 dir = bdrv_dirname(relative_to, errp);
352 if (!dir) {
353 return NULL;
354 }
Max Reitz9f4793d2019-02-01 20:29:16 +0100355
Max Reitz8df68612019-02-01 20:29:23 +0100356 full_name = g_strconcat(dir, filename, NULL);
357 g_free(dir);
358 return full_name;
Max Reitz9f4793d2019-02-01 20:29:16 +0100359}
360
Max Reitz6b6833c2019-02-01 20:29:15 +0100361char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200362{
Max Reitz9f4793d2019-02-01 20:29:16 +0100363 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200364}
365
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100366void bdrv_register(BlockDriver *bdrv)
367{
Philippe Mathieu-Daudéa15f08d2020-03-18 23:22:35 +0100368 assert(bdrv->format_name);
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100369 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000370}
bellardb3380822004-03-14 21:38:54 +0000371
Markus Armbrustere4e99862014-10-07 13:59:03 +0200372BlockDriverState *bdrv_new(void)
373{
374 BlockDriverState *bs;
375 int i;
376
Markus Armbruster5839e532014-08-19 10:31:08 +0200377 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800378 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800379 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
380 QLIST_INIT(&bs->op_blockers[i]);
381 }
Stefan Hajnoczid616b222013-06-24 17:13:10 +0200382 notifier_with_return_list_init(&bs->before_write_notifiers);
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200383 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200384 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800385 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200386 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200387
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300388 qemu_co_queue_init(&bs->flush_queue);
389
Kevin Wolf0f122642018-03-28 18:29:18 +0200390 for (i = 0; i < bdrv_drain_all_count; i++) {
391 bdrv_drained_begin(bs);
392 }
393
Max Reitz2c1d04e2016-01-29 16:36:11 +0100394 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
395
bellardb3380822004-03-14 21:38:54 +0000396 return bs;
397}
398
Marc Mari88d88792016-08-12 09:27:03 -0400399static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000400{
401 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400402
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100403 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
404 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000405 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100406 }
bellardea2384d2004-08-01 21:59:26 +0000407 }
Marc Mari88d88792016-08-12 09:27:03 -0400408
bellardea2384d2004-08-01 21:59:26 +0000409 return NULL;
410}
411
Marc Mari88d88792016-08-12 09:27:03 -0400412BlockDriver *bdrv_find_format(const char *format_name)
413{
414 BlockDriver *drv1;
415 int i;
416
417 drv1 = bdrv_do_find_format(format_name);
418 if (drv1) {
419 return drv1;
420 }
421
422 /* The driver isn't registered, maybe we need to load a module */
423 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
424 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
425 block_module_load_one(block_driver_modules[i].library_name);
426 break;
427 }
428 }
429
430 return bdrv_do_find_format(format_name);
431}
432
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300433static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100434{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800435 static const char *whitelist_rw[] = {
436 CONFIG_BDRV_RW_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200437 NULL
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800438 };
439 static const char *whitelist_ro[] = {
440 CONFIG_BDRV_RO_WHITELIST
Paolo Bonzini859aef02020-08-04 18:14:26 +0200441 NULL
Markus Armbrustereb852012009-10-27 18:41:44 +0100442 };
443 const char **p;
444
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800445 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100446 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800447 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100448
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800449 for (p = whitelist_rw; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300450 if (!strcmp(format_name, *p)) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100451 return 1;
452 }
453 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800454 if (read_only) {
455 for (p = whitelist_ro; *p; p++) {
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300456 if (!strcmp(format_name, *p)) {
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800457 return 1;
458 }
459 }
460 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100461 return 0;
462}
463
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +0300464int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
465{
466 return bdrv_format_is_whitelisted(drv->format_name, read_only);
467}
468
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000469bool bdrv_uses_whitelist(void)
470{
471 return use_bdrv_whitelist;
472}
473
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800474typedef struct CreateCo {
475 BlockDriver *drv;
476 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800477 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800478 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200479 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800480} CreateCo;
481
482static void coroutine_fn bdrv_create_co_entry(void *opaque)
483{
Max Reitzcc84d902013-09-06 17:14:26 +0200484 Error *local_err = NULL;
485 int ret;
486
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800487 CreateCo *cco = opaque;
488 assert(cco->drv);
489
Maxim Levitskyb92902d2020-03-26 03:12:17 +0200490 ret = cco->drv->bdrv_co_create_opts(cco->drv,
491 cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300492 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200493 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800494}
495
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200496int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800497 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000498{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800499 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200500
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800501 Coroutine *co;
502 CreateCo cco = {
503 .drv = drv,
504 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800505 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800506 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200507 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800508 };
509
Stefan Hajnocziefc75e22018-01-18 13:43:45 +0100510 if (!drv->bdrv_co_create_opts) {
Max Reitzcc84d902013-09-06 17:14:26 +0200511 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300512 ret = -ENOTSUP;
513 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800514 }
515
516 if (qemu_in_coroutine()) {
517 /* Fast-path if already in coroutine context */
518 bdrv_create_co_entry(&cco);
519 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200520 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
521 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800522 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200523 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800524 }
525 }
526
527 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200528 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100529 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200530 error_propagate(errp, cco.err);
531 } else {
532 error_setg_errno(errp, -ret, "Could not create image");
533 }
534 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800535
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300536out:
537 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800538 return ret;
bellardea2384d2004-08-01 21:59:26 +0000539}
540
Max Reitzfd171462020-01-22 17:45:29 +0100541/**
542 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
543 * least the given @minimum_size.
544 *
545 * On success, return @blk's actual length.
546 * Otherwise, return -errno.
547 */
548static int64_t create_file_fallback_truncate(BlockBackend *blk,
549 int64_t minimum_size, Error **errp)
550{
551 Error *local_err = NULL;
552 int64_t size;
553 int ret;
554
Kevin Wolf8c6242b2020-04-24 14:54:41 +0200555 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
556 &local_err);
Max Reitzfd171462020-01-22 17:45:29 +0100557 if (ret < 0 && ret != -ENOTSUP) {
558 error_propagate(errp, local_err);
559 return ret;
560 }
561
562 size = blk_getlength(blk);
563 if (size < 0) {
564 error_free(local_err);
565 error_setg_errno(errp, -size,
566 "Failed to inquire the new image file's length");
567 return size;
568 }
569
570 if (size < minimum_size) {
571 /* Need to grow the image, but we failed to do that */
572 error_propagate(errp, local_err);
573 return -ENOTSUP;
574 }
575
576 error_free(local_err);
577 local_err = NULL;
578
579 return size;
580}
581
582/**
583 * Helper function for bdrv_create_file_fallback(): Zero the first
584 * sector to remove any potentially pre-existing image header.
585 */
586static int create_file_fallback_zero_first_sector(BlockBackend *blk,
587 int64_t current_size,
588 Error **errp)
589{
590 int64_t bytes_to_clear;
591 int ret;
592
593 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
594 if (bytes_to_clear) {
595 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
596 if (ret < 0) {
597 error_setg_errno(errp, -ret,
598 "Failed to clear the new image's first sector");
599 return ret;
600 }
601 }
602
603 return 0;
604}
605
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200606/**
607 * Simple implementation of bdrv_co_create_opts for protocol drivers
608 * which only support creation via opening a file
609 * (usually existing raw storage device)
610 */
611int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
612 const char *filename,
613 QemuOpts *opts,
614 Error **errp)
Max Reitzfd171462020-01-22 17:45:29 +0100615{
616 BlockBackend *blk;
Max Reitzeeea1fa2020-02-25 16:56:18 +0100617 QDict *options;
Max Reitzfd171462020-01-22 17:45:29 +0100618 int64_t size = 0;
619 char *buf = NULL;
620 PreallocMode prealloc;
621 Error *local_err = NULL;
622 int ret;
623
624 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
625 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
626 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
627 PREALLOC_MODE_OFF, &local_err);
628 g_free(buf);
629 if (local_err) {
630 error_propagate(errp, local_err);
631 return -EINVAL;
632 }
633
634 if (prealloc != PREALLOC_MODE_OFF) {
635 error_setg(errp, "Unsupported preallocation mode '%s'",
636 PreallocMode_str(prealloc));
637 return -ENOTSUP;
638 }
639
Max Reitzeeea1fa2020-02-25 16:56:18 +0100640 options = qdict_new();
Max Reitzfd171462020-01-22 17:45:29 +0100641 qdict_put_str(options, "driver", drv->format_name);
642
643 blk = blk_new_open(filename, NULL, options,
644 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
645 if (!blk) {
646 error_prepend(errp, "Protocol driver '%s' does not support image "
647 "creation, and opening the image failed: ",
648 drv->format_name);
649 return -EINVAL;
650 }
651
652 size = create_file_fallback_truncate(blk, size, errp);
653 if (size < 0) {
654 ret = size;
655 goto out;
656 }
657
658 ret = create_file_fallback_zero_first_sector(blk, size, errp);
659 if (ret < 0) {
660 goto out;
661 }
662
663 ret = 0;
664out:
665 blk_unref(blk);
666 return ret;
667}
668
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800669int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200670{
671 BlockDriver *drv;
672
Max Reitzb65a5e12015-02-05 13:58:12 -0500673 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200674 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000675 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200676 }
677
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +0200678 return bdrv_create(drv, filename, opts, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200679}
680
Daniel Henrique Barbozae1d7f8b2020-01-30 18:39:05 -0300681int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
682{
683 Error *local_err = NULL;
684 int ret;
685
686 assert(bs != NULL);
687
688 if (!bs->drv) {
689 error_setg(errp, "Block node '%s' is not opened", bs->filename);
690 return -ENOMEDIUM;
691 }
692
693 if (!bs->drv->bdrv_co_delete_file) {
694 error_setg(errp, "Driver '%s' does not support image deletion",
695 bs->drv->format_name);
696 return -ENOTSUP;
697 }
698
699 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
700 if (ret < 0) {
701 error_propagate(errp, local_err);
702 }
703
704 return ret;
705}
706
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100707/**
708 * Try to get @bs's logical and physical block size.
709 * On success, store them in @bsz struct and return 0.
710 * On failure return -errno.
711 * @bs must not be empty.
712 */
713int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
714{
715 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200716 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100717
718 if (drv && drv->bdrv_probe_blocksizes) {
719 return drv->bdrv_probe_blocksizes(bs, bsz);
Max Reitz93393e62019-06-12 17:03:38 +0200720 } else if (filtered) {
721 return bdrv_probe_blocksizes(filtered, bsz);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100722 }
723
724 return -ENOTSUP;
725}
726
727/**
728 * Try to get @bs's geometry (cyls, heads, sectors).
729 * On success, store them in @geo struct and return 0.
730 * On failure return -errno.
731 * @bs must not be empty.
732 */
733int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
734{
735 BlockDriver *drv = bs->drv;
Max Reitz93393e62019-06-12 17:03:38 +0200736 BlockDriverState *filtered = bdrv_filter_bs(bs);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100737
738 if (drv && drv->bdrv_probe_geometry) {
739 return drv->bdrv_probe_geometry(bs, geo);
Max Reitz93393e62019-06-12 17:03:38 +0200740 } else if (filtered) {
741 return bdrv_probe_geometry(filtered, geo);
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100742 }
743
744 return -ENOTSUP;
745}
746
Jim Meyeringeba25052012-05-28 09:27:54 +0200747/*
748 * Create a uniquely-named empty temporary file.
749 * Return 0 upon success, otherwise a negative errno value.
750 */
751int get_tmp_filename(char *filename, int size)
752{
bellardd5249392004-08-03 21:14:23 +0000753#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000754 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200755 /* GetTempFileName requires that its output buffer (4th param)
756 have length MAX_PATH or greater. */
757 assert(size >= MAX_PATH);
758 return (GetTempPath(MAX_PATH, temp_dir)
759 && GetTempFileName(temp_dir, "qem", 0, filename)
760 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000761#else
bellardea2384d2004-08-01 21:59:26 +0000762 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000763 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000764 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530765 if (!tmpdir) {
766 tmpdir = "/var/tmp";
767 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200768 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
769 return -EOVERFLOW;
770 }
bellardea2384d2004-08-01 21:59:26 +0000771 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800772 if (fd < 0) {
773 return -errno;
774 }
775 if (close(fd) != 0) {
776 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200777 return -errno;
778 }
779 return 0;
bellardd5249392004-08-03 21:14:23 +0000780#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200781}
bellardea2384d2004-08-01 21:59:26 +0000782
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200783/*
784 * Detect host devices. By convention, /dev/cdrom[N] is always
785 * recognized as a host CDROM.
786 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200787static BlockDriver *find_hdev_driver(const char *filename)
788{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200789 int score_max = 0, score;
790 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200791
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100792 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200793 if (d->bdrv_probe_device) {
794 score = d->bdrv_probe_device(filename);
795 if (score > score_max) {
796 score_max = score;
797 drv = d;
798 }
799 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200800 }
801
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200802 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200803}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200804
Marc Mari88d88792016-08-12 09:27:03 -0400805static BlockDriver *bdrv_do_find_protocol(const char *protocol)
806{
807 BlockDriver *drv1;
808
809 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
810 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
811 return drv1;
812 }
813 }
814
815 return NULL;
816}
817
Kevin Wolf98289622013-07-10 15:47:39 +0200818BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500819 bool allow_protocol_prefix,
820 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200821{
822 BlockDriver *drv1;
823 char protocol[128];
824 int len;
825 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400826 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200827
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200828 /* TODO Drivers without bdrv_file_open must be specified explicitly */
829
Christoph Hellwig39508e72010-06-23 12:25:17 +0200830 /*
831 * XXX(hch): we really should not let host device detection
832 * override an explicit protocol specification, but moving this
833 * later breaks access to device names with colons in them.
834 * Thanks to the brain-dead persistent naming schemes on udev-
835 * based Linux systems those actually are quite common.
836 */
837 drv1 = find_hdev_driver(filename);
838 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200839 return drv1;
840 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200841
Kevin Wolf98289622013-07-10 15:47:39 +0200842 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100843 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200844 }
Kevin Wolf98289622013-07-10 15:47:39 +0200845
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000846 p = strchr(filename, ':');
847 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200848 len = p - filename;
849 if (len > sizeof(protocol) - 1)
850 len = sizeof(protocol) - 1;
851 memcpy(protocol, filename, len);
852 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400853
854 drv1 = bdrv_do_find_protocol(protocol);
855 if (drv1) {
856 return drv1;
857 }
858
859 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
860 if (block_driver_modules[i].protocol_name &&
861 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
862 block_module_load_one(block_driver_modules[i].library_name);
863 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200864 }
865 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500866
Marc Mari88d88792016-08-12 09:27:03 -0400867 drv1 = bdrv_do_find_protocol(protocol);
868 if (!drv1) {
869 error_setg(errp, "Unknown protocol '%s'", protocol);
870 }
871 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200872}
873
Markus Armbrusterc6684242014-11-20 16:27:10 +0100874/*
875 * Guess image format by probing its contents.
876 * This is not a good idea when your image is raw (CVE-2008-2004), but
877 * we do it anyway for backward compatibility.
878 *
879 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100880 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
881 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100882 * @filename is its filename.
883 *
884 * For all block drivers, call the bdrv_probe() method to get its
885 * probing score.
886 * Return the first block driver with the highest probing score.
887 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100888BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
889 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100890{
891 int score_max = 0, score;
892 BlockDriver *drv = NULL, *d;
893
894 QLIST_FOREACH(d, &bdrv_drivers, list) {
895 if (d->bdrv_probe) {
896 score = d->bdrv_probe(buf, buf_size, filename);
897 if (score > score_max) {
898 score_max = score;
899 drv = d;
900 }
901 }
902 }
903
904 return drv;
905}
906
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100907static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200908 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000909{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100910 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100911 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100912 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700913
Kevin Wolf08a00552010-06-01 18:37:31 +0200914 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100915 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100916 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200917 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700918 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700919
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100920 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +0000921 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200922 error_setg_errno(errp, -ret, "Could not read image for determining its "
923 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +0200924 *pdrv = NULL;
925 return ret;
bellard83f64092006-08-01 16:21:11 +0000926 }
927
Markus Armbrusterc6684242014-11-20 16:27:10 +0100928 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +0200929 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200930 error_setg(errp, "Could not determine image format: No compatible "
931 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +0200932 ret = -ENOENT;
933 }
934 *pdrv = drv;
935 return ret;
bellardea2384d2004-08-01 21:59:26 +0000936}
937
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100938/**
939 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +0200940 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100941 */
Kevin Wolf3d9f2d22018-06-26 13:55:20 +0200942int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100943{
944 BlockDriver *drv = bs->drv;
945
Max Reitzd470ad42017-11-10 21:31:09 +0100946 if (!drv) {
947 return -ENOMEDIUM;
948 }
949
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700950 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +0300951 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700952 return 0;
953
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100954 /* query actual device if possible, otherwise just trust the hint */
955 if (drv->bdrv_getlength) {
956 int64_t length = drv->bdrv_getlength(bs);
957 if (length < 0) {
958 return length;
959 }
Fam Zheng7e382002013-11-06 19:48:06 +0800960 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100961 }
962
963 bs->total_sectors = hint;
964 return 0;
965}
966
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100967/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +0100968 * Combines a QDict of new block driver @options with any missing options taken
969 * from @old_options, so that leaving out an option defaults to its old value.
970 */
971static void bdrv_join_options(BlockDriverState *bs, QDict *options,
972 QDict *old_options)
973{
974 if (bs->drv && bs->drv->bdrv_join_options) {
975 bs->drv->bdrv_join_options(options, old_options);
976 } else {
977 qdict_join(options, old_options, false);
978 }
979}
980
Alberto Garcia543770b2018-09-06 12:37:09 +0300981static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
982 int open_flags,
983 Error **errp)
984{
985 Error *local_err = NULL;
986 char *value = qemu_opt_get_del(opts, "detect-zeroes");
987 BlockdevDetectZeroesOptions detect_zeroes =
988 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
989 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
990 g_free(value);
991 if (local_err) {
992 error_propagate(errp, local_err);
993 return detect_zeroes;
994 }
995
996 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
997 !(open_flags & BDRV_O_UNMAP))
998 {
999 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1000 "without setting discard operation to unmap");
1001 }
1002
1003 return detect_zeroes;
1004}
1005
Kevin Wolfcddff5b2015-11-16 16:43:27 +01001006/**
Aarushi Mehtaf80f2672020-01-20 14:18:50 +00001007 * Set open flags for aio engine
1008 *
1009 * Return 0 on success, -1 if the engine specified is invalid
1010 */
1011int bdrv_parse_aio(const char *mode, int *flags)
1012{
1013 if (!strcmp(mode, "threads")) {
1014 /* do nothing, default */
1015 } else if (!strcmp(mode, "native")) {
1016 *flags |= BDRV_O_NATIVE_AIO;
1017#ifdef CONFIG_LINUX_IO_URING
1018 } else if (!strcmp(mode, "io_uring")) {
1019 *flags |= BDRV_O_IO_URING;
1020#endif
1021 } else {
1022 return -1;
1023 }
1024
1025 return 0;
1026}
1027
1028/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +01001029 * Set open flags for a given discard mode
1030 *
1031 * Return 0 on success, -1 if the discard mode was invalid.
1032 */
1033int bdrv_parse_discard_flags(const char *mode, int *flags)
1034{
1035 *flags &= ~BDRV_O_UNMAP;
1036
1037 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1038 /* do nothing */
1039 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1040 *flags |= BDRV_O_UNMAP;
1041 } else {
1042 return -1;
1043 }
1044
1045 return 0;
1046}
1047
1048/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001049 * Set open flags for a given cache mode
1050 *
1051 * Return 0 on success, -1 if the cache mode was invalid.
1052 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001053int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001054{
1055 *flags &= ~BDRV_O_CACHE_MASK;
1056
1057 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001058 *writethrough = false;
1059 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001060 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001061 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +01001062 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001063 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001064 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001065 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001066 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001067 *flags |= BDRV_O_NO_FLUSH;
1068 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +01001069 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +01001070 } else {
1071 return -1;
1072 }
1073
1074 return 0;
1075}
1076
Kevin Wolfb5411552017-01-17 15:56:16 +01001077static char *bdrv_child_get_parent_desc(BdrvChild *c)
1078{
1079 BlockDriverState *parent = c->opaque;
1080 return g_strdup(bdrv_get_device_or_node_name(parent));
1081}
1082
Kevin Wolf20018e12016-05-23 18:46:59 +02001083static void bdrv_child_cb_drained_begin(BdrvChild *child)
1084{
1085 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001086 bdrv_do_drained_begin_quiesce(bs, NULL, false);
Kevin Wolf20018e12016-05-23 18:46:59 +02001087}
1088
Kevin Wolf89bd0302018-03-22 14:11:20 +01001089static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1090{
1091 BlockDriverState *bs = child->opaque;
Kevin Wolf6cd5c9d2018-05-29 17:17:45 +02001092 return bdrv_drain_poll(bs, false, NULL, false);
Kevin Wolf89bd0302018-03-22 14:11:20 +01001093}
1094
Max Reitze037c092019-07-19 11:26:14 +02001095static void bdrv_child_cb_drained_end(BdrvChild *child,
1096 int *drained_end_counter)
Kevin Wolf20018e12016-05-23 18:46:59 +02001097{
1098 BlockDriverState *bs = child->opaque;
Max Reitze037c092019-07-19 11:26:14 +02001099 bdrv_drained_end_no_poll(bs, drained_end_counter);
Kevin Wolf20018e12016-05-23 18:46:59 +02001100}
1101
Kevin Wolf38701b62017-05-04 18:52:39 +02001102static int bdrv_child_cb_inactivate(BdrvChild *child)
1103{
1104 BlockDriverState *bs = child->opaque;
1105 assert(bs->open_flags & BDRV_O_INACTIVE);
1106 return 0;
1107}
1108
Kevin Wolf5d231842019-05-06 19:17:56 +02001109static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1110 GSList **ignore, Error **errp)
1111{
1112 BlockDriverState *bs = child->opaque;
1113 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1114}
1115
Kevin Wolf53a7d042019-05-06 19:17:59 +02001116static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1117 GSList **ignore)
1118{
1119 BlockDriverState *bs = child->opaque;
1120 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1121}
1122
Kevin Wolf0b50cc82014-04-11 21:29:52 +02001123/*
Kevin Wolf73176be2016-03-07 13:02:15 +01001124 * Returns the options and flags that a temporary snapshot should get, based on
1125 * the originally requested flags (the originally requested image will have
1126 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001127 */
Kevin Wolf73176be2016-03-07 13:02:15 +01001128static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1129 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001130{
Kevin Wolf73176be2016-03-07 13:02:15 +01001131 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1132
1133 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +01001134 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1135 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +02001136
Kevin Wolf3f486862019-04-04 17:04:43 +02001137 /* Copy the read-only and discard options from the parent */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001138 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
Kevin Wolf3f486862019-04-04 17:04:43 +02001139 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001140
Kevin Wolf41869042016-06-16 12:59:30 +02001141 /* aio=native doesn't work for cache.direct=off, so disable it for the
1142 * temporary snapshot */
1143 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02001144}
1145
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001146static void bdrv_backing_attach(BdrvChild *c)
1147{
1148 BlockDriverState *parent = c->opaque;
1149 BlockDriverState *backing_hd = c->bs;
1150
1151 assert(!parent->backing_blocker);
1152 error_setg(&parent->backing_blocker,
1153 "node is used as backing hd of '%s'",
1154 bdrv_get_device_or_node_name(parent));
1155
Max Reitzf30c66b2019-02-01 20:29:05 +01001156 bdrv_refresh_filename(backing_hd);
1157
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001158 parent->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001159
1160 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1161 /* Otherwise we won't be able to commit or stream */
1162 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1163 parent->backing_blocker);
1164 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1165 parent->backing_blocker);
1166 /*
1167 * We do backup in 3 ways:
1168 * 1. drive backup
1169 * The target bs is new opened, and the source is top BDS
1170 * 2. blockdev backup
1171 * Both the source and the target are top BDSes.
1172 * 3. internal backup(used for block replication)
1173 * Both the source and the target are backing file
1174 *
1175 * In case 1 and 2, neither the source nor the target is the backing file.
1176 * In case 3, we will block the top BDS, so there is only one block job
1177 * for the top BDS and its backing chain.
1178 */
1179 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1180 parent->backing_blocker);
1181 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1182 parent->backing_blocker);
Max Reitzca2f1232020-05-13 13:05:22 +02001183}
Kevin Wolfd736f112017-12-18 16:05:48 +01001184
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001185static void bdrv_backing_detach(BdrvChild *c)
1186{
1187 BlockDriverState *parent = c->opaque;
1188
1189 assert(parent->backing_blocker);
1190 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1191 error_free(parent->backing_blocker);
1192 parent->backing_blocker = NULL;
Max Reitz48e08282020-05-13 13:05:23 +02001193}
Kevin Wolfd736f112017-12-18 16:05:48 +01001194
Kevin Wolf6858eba2017-06-29 19:32:21 +02001195static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1196 const char *filename, Error **errp)
1197{
1198 BlockDriverState *parent = c->opaque;
Alberto Garciae94d3db2018-11-12 16:00:34 +02001199 bool read_only = bdrv_is_read_only(parent);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001200 int ret;
1201
Alberto Garciae94d3db2018-11-12 16:00:34 +02001202 if (read_only) {
1203 ret = bdrv_reopen_set_read_only(parent, false, errp);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001204 if (ret < 0) {
1205 return ret;
1206 }
1207 }
1208
Kevin Wolf6858eba2017-06-29 19:32:21 +02001209 ret = bdrv_change_backing_file(parent, filename,
Eric Blakee54ee1b2020-07-06 15:39:53 -05001210 base->drv ? base->drv->format_name : "",
1211 false);
Kevin Wolf6858eba2017-06-29 19:32:21 +02001212 if (ret < 0) {
Kevin Wolf64730692017-11-06 17:52:58 +01001213 error_setg_errno(errp, -ret, "Could not update backing file link");
Kevin Wolf6858eba2017-06-29 19:32:21 +02001214 }
1215
Alberto Garciae94d3db2018-11-12 16:00:34 +02001216 if (read_only) {
1217 bdrv_reopen_set_read_only(parent, true, NULL);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02001218 }
1219
Kevin Wolf6858eba2017-06-29 19:32:21 +02001220 return ret;
1221}
1222
Max Reitzfae8bd32020-05-13 13:05:20 +02001223/*
1224 * Returns the options and flags that a generic child of a BDS should
1225 * get, based on the given options and flags for the parent BDS.
1226 */
Max Reitz00ff7ff2020-05-13 13:05:21 +02001227static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1228 int *child_flags, QDict *child_options,
1229 int parent_flags, QDict *parent_options)
Max Reitzfae8bd32020-05-13 13:05:20 +02001230{
1231 int flags = parent_flags;
1232
1233 /*
1234 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1235 * Generally, the question to answer is: Should this child be
1236 * format-probed by default?
1237 */
1238
1239 /*
1240 * Pure and non-filtered data children of non-format nodes should
1241 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1242 * set). This only affects a very limited set of drivers (namely
1243 * quorum and blkverify when this comment was written).
1244 * Force-clear BDRV_O_PROTOCOL then.
1245 */
1246 if (!parent_is_format &&
1247 (role & BDRV_CHILD_DATA) &&
1248 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1249 {
1250 flags &= ~BDRV_O_PROTOCOL;
1251 }
1252
1253 /*
1254 * All children of format nodes (except for COW children) and all
1255 * metadata children in general should never be format-probed.
1256 * Force-set BDRV_O_PROTOCOL then.
1257 */
1258 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1259 (role & BDRV_CHILD_METADATA))
1260 {
1261 flags |= BDRV_O_PROTOCOL;
1262 }
1263
1264 /*
1265 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1266 * the parent.
1267 */
1268 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1269 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1270 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1271
1272 if (role & BDRV_CHILD_COW) {
1273 /* backing files are opened read-only by default */
1274 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1275 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1276 } else {
1277 /* Inherit the read-only option from the parent if it's not set */
1278 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1279 qdict_copy_default(child_options, parent_options,
1280 BDRV_OPT_AUTO_READ_ONLY);
1281 }
1282
1283 /*
1284 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1285 * can default to enable it on lower layers regardless of the
1286 * parent option.
1287 */
1288 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1289
1290 /* Clear flags that only apply to the top layer */
1291 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1292
1293 if (role & BDRV_CHILD_METADATA) {
1294 flags &= ~BDRV_O_NO_IO;
1295 }
1296 if (role & BDRV_CHILD_COW) {
1297 flags &= ~BDRV_O_TEMPORARY;
1298 }
1299
1300 *child_flags = flags;
1301}
1302
Max Reitzca2f1232020-05-13 13:05:22 +02001303static void bdrv_child_cb_attach(BdrvChild *child)
1304{
1305 BlockDriverState *bs = child->opaque;
1306
1307 if (child->role & BDRV_CHILD_COW) {
1308 bdrv_backing_attach(child);
1309 }
1310
1311 bdrv_apply_subtree_drain(child, bs);
1312}
1313
Max Reitz48e08282020-05-13 13:05:23 +02001314static void bdrv_child_cb_detach(BdrvChild *child)
1315{
1316 BlockDriverState *bs = child->opaque;
1317
1318 if (child->role & BDRV_CHILD_COW) {
1319 bdrv_backing_detach(child);
1320 }
1321
1322 bdrv_unapply_subtree_drain(child, bs);
1323}
1324
Max Reitz43483552020-05-13 13:05:24 +02001325static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1326 const char *filename, Error **errp)
1327{
1328 if (c->role & BDRV_CHILD_COW) {
1329 return bdrv_backing_update_filename(c, base, filename, errp);
1330 }
1331 return 0;
1332}
1333
1334const BdrvChildClass child_of_bds = {
1335 .parent_is_bds = true,
1336 .get_parent_desc = bdrv_child_get_parent_desc,
1337 .inherit_options = bdrv_inherited_options,
1338 .drained_begin = bdrv_child_cb_drained_begin,
1339 .drained_poll = bdrv_child_cb_drained_poll,
1340 .drained_end = bdrv_child_cb_drained_end,
1341 .attach = bdrv_child_cb_attach,
1342 .detach = bdrv_child_cb_detach,
1343 .inactivate = bdrv_child_cb_inactivate,
1344 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1345 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1346 .update_filename = bdrv_child_cb_update_filename,
1347};
1348
Kevin Wolf7b272452012-11-12 17:05:39 +01001349static int bdrv_open_flags(BlockDriverState *bs, int flags)
1350{
Kevin Wolf61de4c62016-03-18 17:46:45 +01001351 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001352
1353 /*
1354 * Clear flags that are internal to the block layer before opening the
1355 * image.
1356 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001357 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001358
Kevin Wolf7b272452012-11-12 17:05:39 +01001359 return open_flags;
1360}
1361
Kevin Wolf91a097e2015-05-08 17:49:53 +02001362static void update_flags_from_options(int *flags, QemuOpts *opts)
1363{
Alberto Garcia2a3d4332018-11-12 16:00:48 +02001364 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001365
Alberto Garcia57f9db92018-09-06 12:37:06 +03001366 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001367 *flags |= BDRV_O_NO_FLUSH;
1368 }
1369
Alberto Garcia57f9db92018-09-06 12:37:06 +03001370 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001371 *flags |= BDRV_O_NOCACHE;
1372 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001373
Alberto Garcia57f9db92018-09-06 12:37:06 +03001374 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001375 *flags |= BDRV_O_RDWR;
1376 }
1377
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001378 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1379 *flags |= BDRV_O_AUTO_RDONLY;
1380 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001381}
1382
1383static void update_options_from_flags(QDict *options, int flags)
1384{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001385 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001386 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001387 }
1388 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001389 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1390 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001391 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001392 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001393 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001394 }
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001395 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1396 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1397 flags & BDRV_O_AUTO_RDONLY);
1398 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001399}
1400
Kevin Wolf636ea372014-01-24 14:11:52 +01001401static void bdrv_assign_node_name(BlockDriverState *bs,
1402 const char *node_name,
1403 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001404{
Jeff Cody15489c72015-10-12 19:36:50 -04001405 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001406
Jeff Cody15489c72015-10-12 19:36:50 -04001407 if (!node_name) {
1408 node_name = gen_node_name = id_generate(ID_BLOCK);
1409 } else if (!id_wellformed(node_name)) {
1410 /*
1411 * Check for empty string or invalid characters, but not if it is
1412 * generated (generated names use characters not available to the user)
1413 */
Kevin Wolf9aebf3b2014-09-25 09:54:02 +02001414 error_setg(errp, "Invalid node name");
Kevin Wolf636ea372014-01-24 14:11:52 +01001415 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001416 }
1417
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001418 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001419 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001420 error_setg(errp, "node-name=%s is conflicting with a device id",
1421 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001422 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001423 }
1424
Benoît Canet6913c0c2014-01-23 21:31:33 +01001425 /* takes care of avoiding duplicates node names */
1426 if (bdrv_find_node(node_name)) {
1427 error_setg(errp, "Duplicate node name");
Jeff Cody15489c72015-10-12 19:36:50 -04001428 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001429 }
1430
Kevin Wolf824808d2018-07-04 13:28:29 +02001431 /* Make sure that the node name isn't truncated */
1432 if (strlen(node_name) >= sizeof(bs->node_name)) {
1433 error_setg(errp, "Node name too long");
1434 goto out;
1435 }
1436
Benoît Canet6913c0c2014-01-23 21:31:33 +01001437 /* copy node name into the bs and insert it into the graph list */
1438 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1439 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001440out:
1441 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001442}
1443
Kevin Wolf01a56502017-01-18 15:51:56 +01001444static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1445 const char *node_name, QDict *options,
1446 int open_flags, Error **errp)
1447{
1448 Error *local_err = NULL;
Kevin Wolf0f122642018-03-28 18:29:18 +02001449 int i, ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001450
1451 bdrv_assign_node_name(bs, node_name, &local_err);
1452 if (local_err) {
1453 error_propagate(errp, local_err);
1454 return -EINVAL;
1455 }
1456
1457 bs->drv = drv;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001458 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Kevin Wolf01a56502017-01-18 15:51:56 +01001459 bs->opaque = g_malloc0(drv->instance_size);
1460
1461 if (drv->bdrv_file_open) {
1462 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1463 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001464 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001465 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001466 } else {
1467 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001468 }
1469
1470 if (ret < 0) {
1471 if (local_err) {
1472 error_propagate(errp, local_err);
1473 } else if (bs->filename[0]) {
1474 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1475 } else {
1476 error_setg_errno(errp, -ret, "Could not open image");
1477 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001478 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001479 }
1480
1481 ret = refresh_total_sectors(bs, bs->total_sectors);
1482 if (ret < 0) {
1483 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001484 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001485 }
1486
1487 bdrv_refresh_limits(bs, &local_err);
1488 if (local_err) {
1489 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001490 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001491 }
1492
1493 assert(bdrv_opt_mem_align(bs) != 0);
1494 assert(bdrv_min_mem_align(bs) != 0);
1495 assert(is_power_of_2(bs->bl.request_alignment));
1496
Kevin Wolf0f122642018-03-28 18:29:18 +02001497 for (i = 0; i < bs->quiesce_counter; i++) {
1498 if (drv->bdrv_co_drain_begin) {
1499 drv->bdrv_co_drain_begin(bs);
1500 }
1501 }
1502
Kevin Wolf01a56502017-01-18 15:51:56 +01001503 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001504open_failed:
1505 bs->drv = NULL;
1506 if (bs->file != NULL) {
1507 bdrv_unref_child(bs, bs->file);
1508 bs->file = NULL;
1509 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001510 g_free(bs->opaque);
1511 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001512 return ret;
1513}
1514
Kevin Wolf680c7f92017-01-18 17:16:41 +01001515BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1516 int flags, Error **errp)
1517{
1518 BlockDriverState *bs;
1519 int ret;
1520
1521 bs = bdrv_new();
1522 bs->open_flags = flags;
1523 bs->explicit_options = qdict_new();
1524 bs->options = qdict_new();
1525 bs->opaque = NULL;
1526
1527 update_options_from_flags(bs->options, flags);
1528
1529 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1530 if (ret < 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001531 qobject_unref(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001532 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001533 qobject_unref(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001534 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001535 bdrv_unref(bs);
1536 return NULL;
1537 }
1538
1539 return bs;
1540}
1541
Kevin Wolfc5f30142016-10-06 11:33:17 +02001542QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001543 .name = "bdrv_common",
1544 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1545 .desc = {
1546 {
1547 .name = "node-name",
1548 .type = QEMU_OPT_STRING,
1549 .help = "Node name of the block device node",
1550 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001551 {
1552 .name = "driver",
1553 .type = QEMU_OPT_STRING,
1554 .help = "Block driver to use for the node",
1555 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001556 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001557 .name = BDRV_OPT_CACHE_DIRECT,
1558 .type = QEMU_OPT_BOOL,
1559 .help = "Bypass software writeback cache on the host",
1560 },
1561 {
1562 .name = BDRV_OPT_CACHE_NO_FLUSH,
1563 .type = QEMU_OPT_BOOL,
1564 .help = "Ignore flush requests",
1565 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001566 {
1567 .name = BDRV_OPT_READ_ONLY,
1568 .type = QEMU_OPT_BOOL,
1569 .help = "Node is opened in read-only mode",
1570 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001571 {
Kevin Wolfe35bdc12018-10-05 18:57:40 +02001572 .name = BDRV_OPT_AUTO_READ_ONLY,
1573 .type = QEMU_OPT_BOOL,
1574 .help = "Node can become read-only if opening read-write fails",
1575 },
1576 {
Kevin Wolf692e01a2016-09-12 21:00:41 +02001577 .name = "detect-zeroes",
1578 .type = QEMU_OPT_STRING,
1579 .help = "try to optimize zero writes (off, on, unmap)",
1580 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001581 {
Alberto Garcia415bbca2018-10-03 13:23:13 +03001582 .name = BDRV_OPT_DISCARD,
Kevin Wolf818584a2016-09-12 18:03:18 +02001583 .type = QEMU_OPT_STRING,
1584 .help = "discard operation (ignore/off, unmap/on)",
1585 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001586 {
1587 .name = BDRV_OPT_FORCE_SHARE,
1588 .type = QEMU_OPT_BOOL,
1589 .help = "always accept other writers (default: off)",
1590 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001591 { /* end of list */ }
1592 },
1593};
1594
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02001595QemuOptsList bdrv_create_opts_simple = {
1596 .name = "simple-create-opts",
1597 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
Max Reitzfd171462020-01-22 17:45:29 +01001598 .desc = {
1599 {
1600 .name = BLOCK_OPT_SIZE,
1601 .type = QEMU_OPT_SIZE,
1602 .help = "Virtual disk size"
1603 },
1604 {
1605 .name = BLOCK_OPT_PREALLOC,
1606 .type = QEMU_OPT_STRING,
1607 .help = "Preallocation mode (allowed values: off)"
1608 },
1609 { /* end of list */ }
1610 }
1611};
1612
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001613/*
Kevin Wolf57915332010-04-14 15:24:50 +02001614 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001615 *
1616 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001617 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001618static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001619 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001620{
1621 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001622 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001623 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001624 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001625 const char *discard;
Kevin Wolf18edf282015-04-07 17:12:56 +02001626 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001627 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001628 Error *local_err = NULL;
Kevin Wolf57915332010-04-14 15:24:50 +02001629
Paolo Bonzini64058752012-05-08 16:51:49 +02001630 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001631 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001632
Kevin Wolf62392eb2015-04-24 16:38:02 +02001633 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02001634 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
Kevin Wolf62392eb2015-04-24 16:38:02 +02001635 ret = -EINVAL;
1636 goto fail_opts;
1637 }
1638
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001639 update_flags_from_options(&bs->open_flags, opts);
1640
Kevin Wolf62392eb2015-04-24 16:38:02 +02001641 driver_name = qemu_opt_get(opts, "driver");
1642 drv = bdrv_find_format(driver_name);
1643 assert(drv != NULL);
1644
Fam Zheng5a9347c2017-05-03 00:35:37 +08001645 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1646
1647 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1648 error_setg(errp,
1649 BDRV_OPT_FORCE_SHARE
1650 "=on can only be used with read-only images");
1651 ret = -EINVAL;
1652 goto fail_opts;
1653 }
1654
Kevin Wolf45673672013-04-22 17:48:40 +02001655 if (file != NULL) {
Max Reitzf30c66b2019-02-01 20:29:05 +01001656 bdrv_refresh_filename(blk_bs(file));
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001657 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001658 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001659 /*
1660 * Caution: while qdict_get_try_str() is fine, getting
1661 * non-string types would require more care. When @options
1662 * come from -blockdev or blockdev_add, its members are typed
1663 * according to the QAPI schema, but when they come from
1664 * -drive, they're all QString.
1665 */
Kevin Wolf45673672013-04-22 17:48:40 +02001666 filename = qdict_get_try_str(options, "filename");
1667 }
1668
Max Reitz4a008242017-04-13 18:06:24 +02001669 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001670 error_setg(errp, "The '%s' block driver requires a file name",
1671 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001672 ret = -EINVAL;
1673 goto fail_opts;
1674 }
1675
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001676 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1677 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001678
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001679 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001680
1681 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
Kevin Wolf8be25de2019-01-22 13:15:31 +01001682 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1683 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1684 } else {
1685 ret = -ENOTSUP;
1686 }
1687 if (ret < 0) {
1688 error_setg(errp,
1689 !bs->read_only && bdrv_is_whitelisted(drv, true)
1690 ? "Driver '%s' can only be used for read-only devices"
1691 : "Driver '%s' is not whitelisted",
1692 drv->format_name);
1693 goto fail_opts;
1694 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001695 }
Kevin Wolf57915332010-04-14 15:24:50 +02001696
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001697 /* bdrv_new() and bdrv_close() make it so */
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01001698 assert(qatomic_read(&bs->copy_on_read) == 0);
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001699
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001700 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001701 if (!bs->read_only) {
1702 bdrv_enable_copy_on_read(bs);
1703 } else {
1704 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001705 ret = -EINVAL;
1706 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001707 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001708 }
1709
Alberto Garcia415bbca2018-10-03 13:23:13 +03001710 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
Kevin Wolf818584a2016-09-12 18:03:18 +02001711 if (discard != NULL) {
1712 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1713 error_setg(errp, "Invalid discard option");
1714 ret = -EINVAL;
1715 goto fail_opts;
1716 }
1717 }
1718
Alberto Garcia543770b2018-09-06 12:37:09 +03001719 bs->detect_zeroes =
1720 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1721 if (local_err) {
1722 error_propagate(errp, local_err);
1723 ret = -EINVAL;
1724 goto fail_opts;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001725 }
1726
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001727 if (filename != NULL) {
1728 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1729 } else {
1730 bs->filename[0] = '\0';
1731 }
Max Reitz91af7012014-07-18 20:24:56 +02001732 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001733
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001734 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001735 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001736 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001737
Kevin Wolf01a56502017-01-18 15:51:56 +01001738 assert(!drv->bdrv_file_open || file == NULL);
1739 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001740 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001741 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001742 }
1743
Kevin Wolf18edf282015-04-07 17:12:56 +02001744 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001745 return 0;
1746
Kevin Wolf18edf282015-04-07 17:12:56 +02001747fail_opts:
1748 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001749 return ret;
1750}
1751
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001752static QDict *parse_json_filename(const char *filename, Error **errp)
1753{
1754 QObject *options_obj;
1755 QDict *options;
1756 int ret;
1757
1758 ret = strstart(filename, "json:", &filename);
1759 assert(ret);
1760
Markus Armbruster5577fff2017-02-28 22:26:59 +01001761 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001762 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001763 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001764 return NULL;
1765 }
1766
Max Reitz7dc847e2018-02-24 16:40:29 +01001767 options = qobject_to(QDict, options_obj);
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001768 if (!options) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001769 qobject_unref(options_obj);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001770 error_setg(errp, "Invalid JSON object given");
1771 return NULL;
1772 }
1773
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001774 qdict_flatten(options);
1775
1776 return options;
1777}
1778
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001779static void parse_json_protocol(QDict *options, const char **pfilename,
1780 Error **errp)
1781{
1782 QDict *json_options;
1783 Error *local_err = NULL;
1784
1785 /* Parse json: pseudo-protocol */
1786 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1787 return;
1788 }
1789
1790 json_options = parse_json_filename(*pfilename, &local_err);
1791 if (local_err) {
1792 error_propagate(errp, local_err);
1793 return;
1794 }
1795
1796 /* Options given in the filename have lower priority than options
1797 * specified directly */
1798 qdict_join(options, json_options, false);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02001799 qobject_unref(json_options);
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001800 *pfilename = NULL;
1801}
1802
Kevin Wolf57915332010-04-14 15:24:50 +02001803/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001804 * Fills in default options for opening images and converts the legacy
1805 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001806 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1807 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001808 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001809static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001810 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001811{
1812 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001813 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001814 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001815 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001816 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001817
Markus Armbruster129c7d12017-03-30 19:43:12 +02001818 /*
1819 * Caution: while qdict_get_try_str() is fine, getting non-string
1820 * types would require more care. When @options come from
1821 * -blockdev or blockdev_add, its members are typed according to
1822 * the QAPI schema, but when they come from -drive, they're all
1823 * QString.
1824 */
Max Reitz53a29512015-03-19 14:53:16 -04001825 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001826 if (drvname) {
1827 drv = bdrv_find_format(drvname);
1828 if (!drv) {
1829 error_setg(errp, "Unknown driver '%s'", drvname);
1830 return -ENOENT;
1831 }
1832 /* If the user has explicitly specified the driver, this choice should
1833 * override the BDRV_O_PROTOCOL flag */
1834 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001835 }
1836
1837 if (protocol) {
1838 *flags |= BDRV_O_PROTOCOL;
1839 } else {
1840 *flags &= ~BDRV_O_PROTOCOL;
1841 }
1842
Kevin Wolf91a097e2015-05-08 17:49:53 +02001843 /* Translate cache options from flags into options */
1844 update_options_from_flags(*options, *flags);
1845
Kevin Wolff54120f2014-05-26 11:09:59 +02001846 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001847 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001848 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001849 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001850 parse_filename = true;
1851 } else {
1852 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1853 "the same time");
1854 return -EINVAL;
1855 }
1856 }
1857
1858 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001859 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001860 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001861
Max Reitz053e1572015-08-26 19:47:51 +02001862 if (!drvname && protocol) {
1863 if (filename) {
1864 drv = bdrv_find_protocol(filename, parse_filename, errp);
1865 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001866 return -EINVAL;
1867 }
Max Reitz053e1572015-08-26 19:47:51 +02001868
1869 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05001870 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02001871 } else {
1872 error_setg(errp, "Must specify either driver or file");
1873 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001874 }
1875 }
1876
Kevin Wolf17b005f2014-05-27 10:50:29 +02001877 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001878
1879 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001880 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001881 drv->bdrv_parse_filename(filename, *options, &local_err);
1882 if (local_err) {
1883 error_propagate(errp, local_err);
1884 return -EINVAL;
1885 }
1886
1887 if (!drv->bdrv_needs_filename) {
1888 qdict_del(*options, "filename");
1889 }
1890 }
1891
1892 return 0;
1893}
1894
Kevin Wolf3121fb42017-09-14 14:42:12 +02001895static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1896 uint64_t perm, uint64_t shared,
Max Reitz9eab1542019-05-22 19:03:50 +02001897 GSList *ignore_children,
1898 bool *tighten_restrictions, Error **errp);
Fam Zhengc1cef672017-03-14 10:30:50 +08001899static void bdrv_child_abort_perm_update(BdrvChild *c);
1900static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1901
Kevin Wolf148eb132017-09-14 14:32:04 +02001902typedef struct BlockReopenQueueEntry {
1903 bool prepared;
Kevin Wolf69b736e2019-03-05 17:18:22 +01001904 bool perms_checked;
Kevin Wolf148eb132017-09-14 14:32:04 +02001905 BDRVReopenState state;
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03001906 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
Kevin Wolf148eb132017-09-14 14:32:04 +02001907} BlockReopenQueueEntry;
1908
1909/*
1910 * Return the flags that @bs will have after the reopens in @q have
1911 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1912 * return the current flags.
1913 */
1914static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1915{
1916 BlockReopenQueueEntry *entry;
1917
1918 if (q != NULL) {
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03001919 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf148eb132017-09-14 14:32:04 +02001920 if (entry->state.bs == bs) {
1921 return entry->state.flags;
1922 }
1923 }
1924 }
1925
1926 return bs->open_flags;
1927}
1928
1929/* Returns whether the image file can be written to after the reopen queue @q
1930 * has been successfully applied, or right now if @q is NULL. */
Max Reitzcc022142018-06-06 21:37:00 +02001931static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
1932 BlockReopenQueue *q)
Kevin Wolf148eb132017-09-14 14:32:04 +02001933{
1934 int flags = bdrv_reopen_get_flags(q, bs);
1935
1936 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
1937}
1938
Max Reitzcc022142018-06-06 21:37:00 +02001939/*
1940 * Return whether the BDS can be written to. This is not necessarily
1941 * the same as !bdrv_is_read_only(bs), as inactivated images may not
1942 * be written to but do not count as read-only images.
1943 */
1944bool bdrv_is_writable(BlockDriverState *bs)
1945{
1946 return bdrv_is_writable_after_reopen(bs, NULL);
1947}
1948
Fam Zhengffd1a5a2017-05-03 00:35:38 +08001949static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02001950 BdrvChild *c, BdrvChildRole role,
1951 BlockReopenQueue *reopen_queue,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08001952 uint64_t parent_perm, uint64_t parent_shared,
1953 uint64_t *nperm, uint64_t *nshared)
1954{
Alberto Garcia0b3ca762019-04-04 14:29:53 +03001955 assert(bs->drv && bs->drv->bdrv_child_perm);
Max Reitze5d8a402020-05-13 13:05:44 +02001956 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
Alberto Garcia0b3ca762019-04-04 14:29:53 +03001957 parent_perm, parent_shared,
1958 nperm, nshared);
Kevin Wolfe0995dc2017-09-14 12:47:11 +02001959 /* TODO Take force_share from reopen_queue */
Fam Zhengffd1a5a2017-05-03 00:35:38 +08001960 if (child_bs && child_bs->force_share) {
1961 *nshared = BLK_PERM_ALL;
1962 }
1963}
1964
Kevin Wolf33a610c2016-12-15 13:04:20 +01001965/*
1966 * Check whether permissions on this node can be changed in a way that
1967 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1968 * permissions of all its parents. This involves checking whether all necessary
1969 * permission changes to child nodes can be performed.
1970 *
Max Reitz9eab1542019-05-22 19:03:50 +02001971 * Will set *tighten_restrictions to true if and only if new permissions have to
1972 * be taken or currently shared permissions are to be unshared. Otherwise,
1973 * errors are not fatal as long as the caller accepts that the restrictions
1974 * remain tighter than they need to be. The caller still has to abort the
1975 * transaction.
1976 * @tighten_restrictions cannot be used together with @q: When reopening, we may
1977 * encounter fatal errors even though no restrictions are to be tightened. For
1978 * example, changing a node from RW to RO will fail if the WRITE permission is
1979 * to be kept.
1980 *
Kevin Wolf33a610c2016-12-15 13:04:20 +01001981 * A call to this function must always be followed by a call to bdrv_set_perm()
1982 * or bdrv_abort_perm_update().
1983 */
Kevin Wolf3121fb42017-09-14 14:42:12 +02001984static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
1985 uint64_t cumulative_perms,
Kevin Wolf46181122017-03-06 15:00:13 +01001986 uint64_t cumulative_shared_perms,
Max Reitz9eab1542019-05-22 19:03:50 +02001987 GSList *ignore_children,
1988 bool *tighten_restrictions, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001989{
1990 BlockDriver *drv = bs->drv;
1991 BdrvChild *c;
1992 int ret;
1993
Max Reitz9eab1542019-05-22 19:03:50 +02001994 assert(!q || !tighten_restrictions);
1995
1996 if (tighten_restrictions) {
1997 uint64_t current_perms, current_shared;
1998 uint64_t added_perms, removed_shared_perms;
1999
2000 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2001
2002 added_perms = cumulative_perms & ~current_perms;
2003 removed_shared_perms = current_shared & ~cumulative_shared_perms;
2004
2005 *tighten_restrictions = added_perms || removed_shared_perms;
2006 }
2007
Kevin Wolf33a610c2016-12-15 13:04:20 +01002008 /* Write permissions never work with read-only images */
2009 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Max Reitzcc022142018-06-06 21:37:00 +02002010 !bdrv_is_writable_after_reopen(bs, q))
Kevin Wolf33a610c2016-12-15 13:04:20 +01002011 {
Max Reitz481e0ee2019-05-15 22:15:00 +02002012 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2013 error_setg(errp, "Block node is read-only");
2014 } else {
2015 uint64_t current_perms, current_shared;
2016 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2017 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2018 error_setg(errp, "Cannot make block node read-only, there is "
2019 "a writer on it");
2020 } else {
2021 error_setg(errp, "Cannot make block node read-only and create "
2022 "a writer on it");
2023 }
2024 }
2025
Kevin Wolf33a610c2016-12-15 13:04:20 +01002026 return -EPERM;
2027 }
2028
Kevin Wolf9c60a5d2020-07-16 16:26:00 +02002029 /*
2030 * Unaligned requests will automatically be aligned to bl.request_alignment
2031 * and without RESIZE we can't extend requests to write to space beyond the
2032 * end of the image, so it's required that the image size is aligned.
2033 */
2034 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2035 !(cumulative_perms & BLK_PERM_RESIZE))
2036 {
2037 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2038 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2039 "Image size is not a multiple of request "
2040 "alignment");
2041 return -EPERM;
2042 }
2043 }
2044
Kevin Wolf33a610c2016-12-15 13:04:20 +01002045 /* Check this node */
2046 if (!drv) {
2047 return 0;
2048 }
2049
2050 if (drv->bdrv_check_perm) {
2051 return drv->bdrv_check_perm(bs, cumulative_perms,
2052 cumulative_shared_perms, errp);
2053 }
2054
Kevin Wolf78e421c2016-12-20 23:25:12 +01002055 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002056 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002057 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002058 return 0;
2059 }
2060
2061 /* Check all children */
2062 QLIST_FOREACH(c, &bs->children, next) {
2063 uint64_t cur_perm, cur_shared;
Max Reitz9eab1542019-05-22 19:03:50 +02002064 bool child_tighten_restr;
2065
Max Reitze5d8a402020-05-13 13:05:44 +02002066 bdrv_child_perm(bs, c->bs, c, c->role, q,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002067 cumulative_perms, cumulative_shared_perms,
2068 &cur_perm, &cur_shared);
Max Reitz9eab1542019-05-22 19:03:50 +02002069 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
2070 tighten_restrictions ? &child_tighten_restr
2071 : NULL,
2072 errp);
2073 if (tighten_restrictions) {
2074 *tighten_restrictions |= child_tighten_restr;
2075 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002076 if (ret < 0) {
2077 return ret;
2078 }
2079 }
2080
2081 return 0;
2082}
2083
2084/*
2085 * Notifies drivers that after a previous bdrv_check_perm() call, the
2086 * permission update is not performed and any preparations made for it (e.g.
2087 * taken file locks) need to be undone.
2088 *
2089 * This function recursively notifies all child nodes.
2090 */
2091static void bdrv_abort_perm_update(BlockDriverState *bs)
2092{
2093 BlockDriver *drv = bs->drv;
2094 BdrvChild *c;
2095
2096 if (!drv) {
2097 return;
2098 }
2099
2100 if (drv->bdrv_abort_perm_update) {
2101 drv->bdrv_abort_perm_update(bs);
2102 }
2103
2104 QLIST_FOREACH(c, &bs->children, next) {
2105 bdrv_child_abort_perm_update(c);
2106 }
2107}
2108
2109static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
2110 uint64_t cumulative_shared_perms)
2111{
2112 BlockDriver *drv = bs->drv;
2113 BdrvChild *c;
2114
2115 if (!drv) {
2116 return;
2117 }
2118
2119 /* Update this node */
2120 if (drv->bdrv_set_perm) {
2121 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2122 }
2123
Kevin Wolf78e421c2016-12-20 23:25:12 +01002124 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01002125 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01002126 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01002127 return;
2128 }
2129
2130 /* Update all children */
2131 QLIST_FOREACH(c, &bs->children, next) {
2132 uint64_t cur_perm, cur_shared;
Max Reitze5d8a402020-05-13 13:05:44 +02002133 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002134 cumulative_perms, cumulative_shared_perms,
2135 &cur_perm, &cur_shared);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002136 bdrv_child_set_perm(c, cur_perm, cur_shared);
2137 }
2138}
2139
Kevin Wolfc7a0f2b2020-03-10 12:38:25 +01002140void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2141 uint64_t *shared_perm)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002142{
2143 BdrvChild *c;
2144 uint64_t cumulative_perms = 0;
2145 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2146
2147 QLIST_FOREACH(c, &bs->parents, next_parent) {
2148 cumulative_perms |= c->perm;
2149 cumulative_shared_perms &= c->shared_perm;
2150 }
2151
2152 *perm = cumulative_perms;
2153 *shared_perm = cumulative_shared_perms;
2154}
2155
Kevin Wolfd0833192017-01-16 18:26:20 +01002156static char *bdrv_child_user_desc(BdrvChild *c)
2157{
Max Reitzbd86fb92020-05-13 13:05:13 +02002158 if (c->klass->get_parent_desc) {
2159 return c->klass->get_parent_desc(c);
Kevin Wolfd0833192017-01-16 18:26:20 +01002160 }
2161
2162 return g_strdup("another user");
2163}
2164
Fam Zheng51761962017-05-03 00:35:36 +08002165char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01002166{
2167 struct perm_name {
2168 uint64_t perm;
2169 const char *name;
2170 } permissions[] = {
2171 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2172 { BLK_PERM_WRITE, "write" },
2173 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2174 { BLK_PERM_RESIZE, "resize" },
2175 { BLK_PERM_GRAPH_MOD, "change children" },
2176 { 0, NULL }
2177 };
2178
Alberto Garciae2a74232020-01-10 18:15:18 +01002179 GString *result = g_string_sized_new(30);
Kevin Wolfd0833192017-01-16 18:26:20 +01002180 struct perm_name *p;
2181
2182 for (p = permissions; p->name; p++) {
2183 if (perm & p->perm) {
Alberto Garciae2a74232020-01-10 18:15:18 +01002184 if (result->len > 0) {
2185 g_string_append(result, ", ");
2186 }
2187 g_string_append(result, p->name);
Kevin Wolfd0833192017-01-16 18:26:20 +01002188 }
2189 }
2190
Alberto Garciae2a74232020-01-10 18:15:18 +01002191 return g_string_free(result, FALSE);
Kevin Wolfd0833192017-01-16 18:26:20 +01002192}
2193
Kevin Wolf33a610c2016-12-15 13:04:20 +01002194/*
2195 * Checks whether a new reference to @bs can be added if the new user requires
Kevin Wolf46181122017-03-06 15:00:13 +01002196 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2197 * set, the BdrvChild objects in this list are ignored in the calculations;
2198 * this allows checking permission updates for an existing reference.
Kevin Wolf33a610c2016-12-15 13:04:20 +01002199 *
Max Reitz9eab1542019-05-22 19:03:50 +02002200 * See bdrv_check_perm() for the semantics of @tighten_restrictions.
2201 *
Kevin Wolf33a610c2016-12-15 13:04:20 +01002202 * Needs to be followed by a call to either bdrv_set_perm() or
2203 * bdrv_abort_perm_update(). */
Kevin Wolf3121fb42017-09-14 14:42:12 +02002204static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2205 uint64_t new_used_perm,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002206 uint64_t new_shared_perm,
Max Reitz9eab1542019-05-22 19:03:50 +02002207 GSList *ignore_children,
2208 bool *tighten_restrictions,
2209 Error **errp)
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002210{
2211 BdrvChild *c;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002212 uint64_t cumulative_perms = new_used_perm;
2213 uint64_t cumulative_shared_perms = new_shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002214
Max Reitz9eab1542019-05-22 19:03:50 +02002215 assert(!q || !tighten_restrictions);
2216
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002217 /* There is no reason why anyone couldn't tolerate write_unchanged */
2218 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2219
2220 QLIST_FOREACH(c, &bs->parents, next_parent) {
Kevin Wolf46181122017-03-06 15:00:13 +01002221 if (g_slist_find(ignore_children, c)) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002222 continue;
2223 }
2224
Kevin Wolfd0833192017-01-16 18:26:20 +01002225 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2226 char *user = bdrv_child_user_desc(c);
2227 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
Max Reitz9eab1542019-05-22 19:03:50 +02002228
2229 if (tighten_restrictions) {
2230 *tighten_restrictions = true;
2231 }
2232
Kevin Wolfd0833192017-01-16 18:26:20 +01002233 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2234 "allow '%s' on %s",
2235 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2236 g_free(user);
2237 g_free(perm_names);
2238 return -EPERM;
2239 }
2240
2241 if ((c->perm & new_shared_perm) != c->perm) {
2242 char *user = bdrv_child_user_desc(c);
2243 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
Max Reitz9eab1542019-05-22 19:03:50 +02002244
2245 if (tighten_restrictions) {
2246 *tighten_restrictions = true;
2247 }
2248
Kevin Wolfd0833192017-01-16 18:26:20 +01002249 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2250 "'%s' on %s",
2251 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2252 g_free(user);
2253 g_free(perm_names);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002254 return -EPERM;
2255 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002256
2257 cumulative_perms |= c->perm;
2258 cumulative_shared_perms &= c->shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002259 }
2260
Kevin Wolf3121fb42017-09-14 14:42:12 +02002261 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
Max Reitz9eab1542019-05-22 19:03:50 +02002262 ignore_children, tighten_restrictions, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002263}
2264
2265/* Needs to be followed by a call to either bdrv_child_set_perm() or
2266 * bdrv_child_abort_perm_update(). */
Kevin Wolf3121fb42017-09-14 14:42:12 +02002267static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2268 uint64_t perm, uint64_t shared,
Max Reitz9eab1542019-05-22 19:03:50 +02002269 GSList *ignore_children,
2270 bool *tighten_restrictions, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002271{
Kevin Wolf46181122017-03-06 15:00:13 +01002272 int ret;
2273
2274 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
Max Reitz9eab1542019-05-22 19:03:50 +02002275 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children,
2276 tighten_restrictions, errp);
Kevin Wolf46181122017-03-06 15:00:13 +01002277 g_slist_free(ignore_children);
2278
Vladimir Sementsov-Ogievskiyf962e962019-02-23 22:20:40 +03002279 if (ret < 0) {
2280 return ret;
2281 }
2282
2283 if (!c->has_backup_perm) {
2284 c->has_backup_perm = true;
2285 c->backup_perm = c->perm;
2286 c->backup_shared_perm = c->shared_perm;
2287 }
2288 /*
2289 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2290 * same child twice during check_perm procedure
2291 */
2292
2293 c->perm = perm;
2294 c->shared_perm = shared;
2295
2296 return 0;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002297}
2298
Fam Zhengc1cef672017-03-14 10:30:50 +08002299static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002300{
2301 uint64_t cumulative_perms, cumulative_shared_perms;
2302
Vladimir Sementsov-Ogievskiyf962e962019-02-23 22:20:40 +03002303 c->has_backup_perm = false;
2304
Kevin Wolf33a610c2016-12-15 13:04:20 +01002305 c->perm = perm;
2306 c->shared_perm = shared;
2307
2308 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
2309 &cumulative_shared_perms);
2310 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
2311}
2312
Fam Zhengc1cef672017-03-14 10:30:50 +08002313static void bdrv_child_abort_perm_update(BdrvChild *c)
Kevin Wolf33a610c2016-12-15 13:04:20 +01002314{
Vladimir Sementsov-Ogievskiyf962e962019-02-23 22:20:40 +03002315 if (c->has_backup_perm) {
2316 c->perm = c->backup_perm;
2317 c->shared_perm = c->backup_shared_perm;
2318 c->has_backup_perm = false;
2319 }
2320
Kevin Wolf33a610c2016-12-15 13:04:20 +01002321 bdrv_abort_perm_update(c->bs);
2322}
2323
2324int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2325 Error **errp)
2326{
Max Reitz10467792019-05-22 19:03:51 +02002327 Error *local_err = NULL;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002328 int ret;
Max Reitz10467792019-05-22 19:03:51 +02002329 bool tighten_restrictions;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002330
Max Reitz10467792019-05-22 19:03:51 +02002331 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL,
2332 &tighten_restrictions, &local_err);
Kevin Wolf33a610c2016-12-15 13:04:20 +01002333 if (ret < 0) {
2334 bdrv_child_abort_perm_update(c);
Max Reitz10467792019-05-22 19:03:51 +02002335 if (tighten_restrictions) {
2336 error_propagate(errp, local_err);
2337 } else {
2338 /*
2339 * Our caller may intend to only loosen restrictions and
2340 * does not expect this function to fail. Errors are not
2341 * fatal in such a case, so we can just hide them from our
2342 * caller.
2343 */
2344 error_free(local_err);
2345 ret = 0;
2346 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01002347 return ret;
2348 }
2349
2350 bdrv_child_set_perm(c, perm, shared);
2351
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002352 return 0;
2353}
2354
Max Reitzc1087f12019-05-22 19:03:46 +02002355int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2356{
2357 uint64_t parent_perms, parent_shared;
2358 uint64_t perms, shared;
2359
2360 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
Max Reitze5d8a402020-05-13 13:05:44 +02002361 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
Max Reitzbf8e9252020-05-13 13:05:16 +02002362 parent_perms, parent_shared, &perms, &shared);
Max Reitzc1087f12019-05-22 19:03:46 +02002363
2364 return bdrv_child_try_set_perm(c, perms, shared, errp);
2365}
2366
Max Reitz87278af2020-05-13 13:05:40 +02002367/*
2368 * Default implementation for .bdrv_child_perm() for block filters:
2369 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2370 * filtered child.
2371 */
2372static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitz87278af2020-05-13 13:05:40 +02002373 BdrvChildRole role,
2374 BlockReopenQueue *reopen_queue,
2375 uint64_t perm, uint64_t shared,
2376 uint64_t *nperm, uint64_t *nshared)
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002377{
Kevin Wolfe444fa82019-08-02 15:59:41 +02002378 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2379 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01002380}
2381
Max Reitz70082db2020-05-13 13:05:26 +02002382static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
Max Reitz70082db2020-05-13 13:05:26 +02002383 BdrvChildRole role,
2384 BlockReopenQueue *reopen_queue,
2385 uint64_t perm, uint64_t shared,
2386 uint64_t *nperm, uint64_t *nshared)
2387{
Max Reitze5d8a402020-05-13 13:05:44 +02002388 assert(role & BDRV_CHILD_COW);
Max Reitz70082db2020-05-13 13:05:26 +02002389
2390 /*
2391 * We want consistent read from backing files if the parent needs it.
2392 * No other operations are performed on backing files.
2393 */
2394 perm &= BLK_PERM_CONSISTENT_READ;
2395
2396 /*
2397 * If the parent can deal with changing data, we're okay with a
2398 * writable and resizable backing file.
2399 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2400 */
2401 if (shared & BLK_PERM_WRITE) {
2402 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2403 } else {
2404 shared = 0;
2405 }
2406
2407 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2408 BLK_PERM_WRITE_UNCHANGED;
2409
2410 if (bs->open_flags & BDRV_O_INACTIVE) {
2411 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2412 }
2413
2414 *nperm = perm;
2415 *nshared = shared;
2416}
2417
Max Reitz6f838a42020-05-13 13:05:27 +02002418static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
Max Reitz6f838a42020-05-13 13:05:27 +02002419 BdrvChildRole role,
2420 BlockReopenQueue *reopen_queue,
2421 uint64_t perm, uint64_t shared,
2422 uint64_t *nperm, uint64_t *nshared)
2423{
2424 int flags;
2425
Max Reitze5d8a402020-05-13 13:05:44 +02002426 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
Max Reitz6f838a42020-05-13 13:05:27 +02002427
2428 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2429
2430 /*
2431 * Apart from the modifications below, the same permissions are
2432 * forwarded and left alone as for filters
2433 */
Max Reitze5d8a402020-05-13 13:05:44 +02002434 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz6f838a42020-05-13 13:05:27 +02002435 perm, shared, &perm, &shared);
2436
Max Reitzf8890542020-05-13 13:05:28 +02002437 if (role & BDRV_CHILD_METADATA) {
2438 /* Format drivers may touch metadata even if the guest doesn't write */
2439 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2440 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2441 }
2442
2443 /*
2444 * bs->file always needs to be consistent because of the
2445 * metadata. We can never allow other users to resize or write
2446 * to it.
2447 */
2448 if (!(flags & BDRV_O_NO_IO)) {
2449 perm |= BLK_PERM_CONSISTENT_READ;
2450 }
2451 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
Max Reitz6f838a42020-05-13 13:05:27 +02002452 }
2453
Max Reitzf8890542020-05-13 13:05:28 +02002454 if (role & BDRV_CHILD_DATA) {
2455 /*
2456 * Technically, everything in this block is a subset of the
2457 * BDRV_CHILD_METADATA path taken above, and so this could
2458 * be an "else if" branch. However, that is not obvious, and
2459 * this function is not performance critical, therefore we let
2460 * this be an independent "if".
2461 */
2462
2463 /*
2464 * We cannot allow other users to resize the file because the
2465 * format driver might have some assumptions about the size
2466 * (e.g. because it is stored in metadata, or because the file
2467 * is split into fixed-size data files).
2468 */
2469 shared &= ~BLK_PERM_RESIZE;
2470
2471 /*
2472 * WRITE_UNCHANGED often cannot be performed as such on the
2473 * data file. For example, the qcow2 driver may still need to
2474 * write copied clusters on copy-on-read.
2475 */
2476 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2477 perm |= BLK_PERM_WRITE;
2478 }
2479
2480 /*
2481 * If the data file is written to, the format driver may
2482 * expect to be able to resize it by writing beyond the EOF.
2483 */
2484 if (perm & BLK_PERM_WRITE) {
2485 perm |= BLK_PERM_RESIZE;
2486 }
Max Reitz6f838a42020-05-13 13:05:27 +02002487 }
Max Reitz6f838a42020-05-13 13:05:27 +02002488
2489 if (bs->open_flags & BDRV_O_INACTIVE) {
2490 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2491 }
2492
2493 *nperm = perm;
2494 *nshared = shared;
2495}
2496
Max Reitz2519f542020-05-13 13:05:29 +02002497void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
Max Reitze5d8a402020-05-13 13:05:44 +02002498 BdrvChildRole role, BlockReopenQueue *reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002499 uint64_t perm, uint64_t shared,
2500 uint64_t *nperm, uint64_t *nshared)
2501{
Max Reitz2519f542020-05-13 13:05:29 +02002502 if (role & BDRV_CHILD_FILTERED) {
2503 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2504 BDRV_CHILD_COW)));
Max Reitze5d8a402020-05-13 13:05:44 +02002505 bdrv_filter_default_perms(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002506 perm, shared, nperm, nshared);
2507 } else if (role & BDRV_CHILD_COW) {
2508 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
Max Reitze5d8a402020-05-13 13:05:44 +02002509 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002510 perm, shared, nperm, nshared);
2511 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
Max Reitze5d8a402020-05-13 13:05:44 +02002512 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
Max Reitz2519f542020-05-13 13:05:29 +02002513 perm, shared, nperm, nshared);
2514 } else {
2515 g_assert_not_reached();
2516 }
2517}
2518
Max Reitz7b1d9c42019-11-08 13:34:51 +01002519uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2520{
2521 static const uint64_t permissions[] = {
2522 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2523 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2524 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2525 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2526 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2527 };
2528
2529 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2530 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2531
2532 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2533
2534 return permissions[qapi_perm];
2535}
2536
Kevin Wolf8ee03992017-03-06 13:45:28 +01002537static void bdrv_replace_child_noperm(BdrvChild *child,
2538 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002539{
2540 BlockDriverState *old_bs = child->bs;
Max Reitzdebc2922019-07-22 15:33:44 +02002541 int new_bs_quiesce_counter;
2542 int drain_saldo;
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002543
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002544 assert(!child->frozen);
2545
Fam Zhengbb2614e2017-04-07 14:54:10 +08002546 if (old_bs && new_bs) {
2547 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2548 }
Max Reitzdebc2922019-07-22 15:33:44 +02002549
2550 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2551 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2552
2553 /*
2554 * If the new child node is drained but the old one was not, flush
2555 * all outstanding requests to the old child node.
2556 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002557 while (drain_saldo > 0 && child->klass->drained_begin) {
Max Reitzdebc2922019-07-22 15:33:44 +02002558 bdrv_parent_drained_begin_single(child, true);
2559 drain_saldo--;
2560 }
2561
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002562 if (old_bs) {
Kevin Wolfd736f112017-12-18 16:05:48 +01002563 /* Detach first so that the recursive drain sections coming from @child
2564 * are already gone and we only end the drain sections that came from
2565 * elsewhere. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002566 if (child->klass->detach) {
2567 child->klass->detach(child);
Kevin Wolfd736f112017-12-18 16:05:48 +01002568 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002569 QLIST_REMOVE(child, next_parent);
2570 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002571
2572 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02002573
2574 if (new_bs) {
2575 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
Max Reitzdebc2922019-07-22 15:33:44 +02002576
2577 /*
2578 * Detaching the old node may have led to the new node's
2579 * quiesce_counter having been decreased. Not a problem, we
2580 * just need to recognize this here and then invoke
2581 * drained_end appropriately more often.
2582 */
2583 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2584 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
Kevin Wolf33a610c2016-12-15 13:04:20 +01002585
Kevin Wolfd736f112017-12-18 16:05:48 +01002586 /* Attach only after starting new drained sections, so that recursive
2587 * drain sections coming from @child don't get an extra .drained_begin
2588 * callback. */
Max Reitzbd86fb92020-05-13 13:05:13 +02002589 if (child->klass->attach) {
2590 child->klass->attach(child);
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01002591 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02002592 }
Max Reitzdebc2922019-07-22 15:33:44 +02002593
2594 /*
2595 * If the old child node was drained but the new one is not, allow
2596 * requests to come in only after the new node has been attached.
2597 */
Max Reitzbd86fb92020-05-13 13:05:13 +02002598 while (drain_saldo < 0 && child->klass->drained_end) {
Max Reitzdebc2922019-07-22 15:33:44 +02002599 bdrv_parent_drained_end_single(child);
2600 drain_saldo++;
2601 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002602}
2603
Kevin Wolf466787f2017-03-08 14:44:07 +01002604/*
2605 * Updates @child to change its reference to point to @new_bs, including
zhaolichange3a6e0d2020-09-17 15:50:20 +08002606 * checking and applying the necessary permission updates both to the old node
Kevin Wolf466787f2017-03-08 14:44:07 +01002607 * and to @new_bs.
2608 *
2609 * NULL is passed as @new_bs for removing the reference before freeing @child.
2610 *
2611 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2612 * function uses bdrv_set_perm() to update the permissions according to the new
2613 * reference that @new_bs gets.
Max Reitz7b99a262019-06-12 16:07:11 +02002614 *
2615 * Callers must ensure that child->frozen is false.
Kevin Wolf466787f2017-03-08 14:44:07 +01002616 */
2617static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
Kevin Wolf8ee03992017-03-06 13:45:28 +01002618{
2619 BlockDriverState *old_bs = child->bs;
2620 uint64_t perm, shared_perm;
2621
Max Reitz7b99a262019-06-12 16:07:11 +02002622 /* Asserts that child->frozen == false */
Kevin Wolf8aecf1d2017-08-03 17:02:57 +02002623 bdrv_replace_child_noperm(child, new_bs);
2624
Max Reitz87ace5f2019-05-22 19:03:49 +02002625 /*
2626 * Start with the new node's permissions. If @new_bs is a (direct
2627 * or indirect) child of @old_bs, we must complete the permission
2628 * update on @new_bs before we loosen the restrictions on @old_bs.
2629 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2630 * updating the permissions of @new_bs, and thus not purely loosen
2631 * restrictions.
2632 */
2633 if (new_bs) {
2634 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
2635 bdrv_set_perm(new_bs, perm, shared_perm);
2636 }
2637
Kevin Wolf8ee03992017-03-06 13:45:28 +01002638 if (old_bs) {
2639 /* Update permissions for old node. This is guaranteed to succeed
2640 * because we're just taking a parent away, so we're loosening
2641 * restrictions. */
Max Reitz10467792019-05-22 19:03:51 +02002642 bool tighten_restrictions;
2643 int ret;
2644
Kevin Wolf8ee03992017-03-06 13:45:28 +01002645 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
Max Reitz10467792019-05-22 19:03:51 +02002646 ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL,
2647 &tighten_restrictions, NULL);
2648 assert(tighten_restrictions == false);
2649 if (ret < 0) {
2650 /* We only tried to loosen restrictions, so errors are not fatal */
2651 bdrv_abort_perm_update(old_bs);
2652 } else {
2653 bdrv_set_perm(old_bs, perm, shared_perm);
2654 }
Kevin Wolfad943dc2019-04-24 18:04:42 +02002655
2656 /* When the parent requiring a non-default AioContext is removed, the
2657 * node moves back to the main AioContext */
2658 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
Kevin Wolf8ee03992017-03-06 13:45:28 +01002659 }
Kevin Wolff54120f2014-05-26 11:09:59 +02002660}
2661
Alberto Garciab441dc72019-05-13 16:46:18 +03002662/*
2663 * This function steals the reference to child_bs from the caller.
2664 * That reference is later dropped by bdrv_root_unref_child().
2665 *
2666 * On failure NULL is returned, errp is set and the reference to
2667 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02002668 *
2669 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2670 * (unless @child_bs is already in @ctx).
Alberto Garciab441dc72019-05-13 16:46:18 +03002671 */
Kevin Wolff21d96d2016-03-08 13:47:46 +01002672BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2673 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02002674 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002675 BdrvChildRole child_role,
Kevin Wolf132ada82019-04-24 17:41:46 +02002676 AioContext *ctx,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002677 uint64_t perm, uint64_t shared_perm,
2678 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02002679{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002680 BdrvChild *child;
Kevin Wolf132ada82019-04-24 17:41:46 +02002681 Error *local_err = NULL;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002682 int ret;
2683
Max Reitz9eab1542019-05-22 19:03:50 +02002684 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL,
2685 errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002686 if (ret < 0) {
Kevin Wolf33a610c2016-12-15 13:04:20 +01002687 bdrv_abort_perm_update(child_bs);
Alberto Garciab441dc72019-05-13 16:46:18 +03002688 bdrv_unref(child_bs);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002689 return NULL;
2690 }
2691
2692 child = g_new(BdrvChild, 1);
Kevin Wolfdf581792015-06-15 11:53:47 +02002693 *child = (BdrvChild) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002694 .bs = NULL,
2695 .name = g_strdup(child_name),
Max Reitzbd86fb92020-05-13 13:05:13 +02002696 .klass = child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002697 .role = child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002698 .perm = perm,
2699 .shared_perm = shared_perm,
2700 .opaque = opaque,
Kevin Wolfdf581792015-06-15 11:53:47 +02002701 };
2702
Kevin Wolf132ada82019-04-24 17:41:46 +02002703 /* If the AioContexts don't match, first try to move the subtree of
2704 * child_bs into the AioContext of the new parent. If this doesn't work,
2705 * try moving the parent into the AioContext of child_bs instead. */
2706 if (bdrv_get_aio_context(child_bs) != ctx) {
2707 ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
Max Reitzbd86fb92020-05-13 13:05:13 +02002708 if (ret < 0 && child_class->can_set_aio_ctx) {
Philippe Mathieu-Daudé0beab812020-02-18 10:43:52 +01002709 GSList *ignore = g_slist_prepend(NULL, child);
Kevin Wolf132ada82019-04-24 17:41:46 +02002710 ctx = bdrv_get_aio_context(child_bs);
Max Reitzbd86fb92020-05-13 13:05:13 +02002711 if (child_class->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
Kevin Wolf132ada82019-04-24 17:41:46 +02002712 error_free(local_err);
2713 ret = 0;
2714 g_slist_free(ignore);
Philippe Mathieu-Daudé0beab812020-02-18 10:43:52 +01002715 ignore = g_slist_prepend(NULL, child);
Max Reitzbd86fb92020-05-13 13:05:13 +02002716 child_class->set_aio_ctx(child, ctx, &ignore);
Kevin Wolf132ada82019-04-24 17:41:46 +02002717 }
2718 g_slist_free(ignore);
2719 }
2720 if (ret < 0) {
2721 error_propagate(errp, local_err);
2722 g_free(child);
2723 bdrv_abort_perm_update(child_bs);
Vladimir Sementsov-Ogievskiy7a26df22020-03-24 18:59:21 +03002724 bdrv_unref(child_bs);
Kevin Wolf132ada82019-04-24 17:41:46 +02002725 return NULL;
2726 }
2727 }
2728
Kevin Wolf33a610c2016-12-15 13:04:20 +01002729 /* This performs the matching bdrv_set_perm() for the above check. */
Kevin Wolf466787f2017-03-08 14:44:07 +01002730 bdrv_replace_child(child, child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02002731
2732 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02002733}
2734
Alberto Garciab441dc72019-05-13 16:46:18 +03002735/*
2736 * This function transfers the reference to child_bs from the caller
2737 * to parent_bs. That reference is later dropped by parent_bs on
2738 * bdrv_close() or if someone calls bdrv_unref_child().
2739 *
2740 * On failure NULL is returned, errp is set and the reference to
2741 * child_bs is also dropped.
Kevin Wolf132ada82019-04-24 17:41:46 +02002742 *
2743 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2744 * hold the AioContext lock for @child_bs, but not for @parent_bs.
Alberto Garciab441dc72019-05-13 16:46:18 +03002745 */
Wen Congyang98292c62016-05-10 15:36:38 +08002746BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2747 BlockDriverState *child_bs,
2748 const char *child_name,
Max Reitzbd86fb92020-05-13 13:05:13 +02002749 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002750 BdrvChildRole child_role,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002751 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01002752{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002753 BdrvChild *child;
Kevin Wolff68c5982016-12-20 15:51:12 +01002754 uint64_t perm, shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002755
Kevin Wolff68c5982016-12-20 15:51:12 +01002756 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2757
2758 assert(parent_bs->drv);
Max Reitze5d8a402020-05-13 13:05:44 +02002759 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002760 perm, shared_perm, &perm, &shared_perm);
Kevin Wolff68c5982016-12-20 15:51:12 +01002761
Max Reitzbd86fb92020-05-13 13:05:13 +02002762 child = bdrv_root_attach_child(child_bs, child_name, child_class,
Max Reitz258b7762020-05-13 13:05:15 +02002763 child_role, bdrv_get_aio_context(parent_bs),
Kevin Wolff68c5982016-12-20 15:51:12 +01002764 perm, shared_perm, parent_bs, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002765 if (child == NULL) {
2766 return NULL;
2767 }
2768
Kevin Wolff21d96d2016-03-08 13:47:46 +01002769 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2770 return child;
2771}
2772
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02002773static void bdrv_detach_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02002774{
Stefan Hajnoczi195ed8c2020-02-14 17:17:10 +00002775 QLIST_SAFE_REMOVE(child, next);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002776
Kevin Wolf466787f2017-03-08 14:44:07 +01002777 bdrv_replace_child(child, NULL);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002778
Kevin Wolf260fecf2015-04-27 13:46:22 +02002779 g_free(child->name);
Kevin Wolf33a60402015-06-15 13:51:04 +02002780 g_free(child);
2781}
2782
Max Reitz7b99a262019-06-12 16:07:11 +02002783/* Callers must ensure that child->frozen is false. */
Kevin Wolff21d96d2016-03-08 13:47:46 +01002784void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02002785{
Kevin Wolf779020c2015-10-13 14:09:44 +02002786 BlockDriverState *child_bs;
2787
Kevin Wolff21d96d2016-03-08 13:47:46 +01002788 child_bs = child->bs;
2789 bdrv_detach_child(child);
2790 bdrv_unref(child_bs);
2791}
2792
Max Reitz3cf746b2019-07-03 19:28:07 +02002793/**
2794 * Clear all inherits_from pointers from children and grandchildren of
2795 * @root that point to @root, where necessary.
2796 */
2797static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
Kevin Wolff21d96d2016-03-08 13:47:46 +01002798{
Max Reitz3cf746b2019-07-03 19:28:07 +02002799 BdrvChild *c;
Kevin Wolf33a60402015-06-15 13:51:04 +02002800
Max Reitz3cf746b2019-07-03 19:28:07 +02002801 if (child->bs->inherits_from == root) {
2802 /*
2803 * Remove inherits_from only when the last reference between root and
2804 * child->bs goes away.
2805 */
2806 QLIST_FOREACH(c, &root->children, next) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002807 if (c != child && c->bs == child->bs) {
2808 break;
2809 }
2810 }
2811 if (c == NULL) {
2812 child->bs->inherits_from = NULL;
2813 }
Kevin Wolf33a60402015-06-15 13:51:04 +02002814 }
2815
Max Reitz3cf746b2019-07-03 19:28:07 +02002816 QLIST_FOREACH(c, &child->bs->children, next) {
2817 bdrv_unset_inherits_from(root, c);
2818 }
2819}
2820
Max Reitz7b99a262019-06-12 16:07:11 +02002821/* Callers must ensure that child->frozen is false. */
Max Reitz3cf746b2019-07-03 19:28:07 +02002822void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2823{
2824 if (child == NULL) {
2825 return;
2826 }
2827
2828 bdrv_unset_inherits_from(parent, child);
Kevin Wolff21d96d2016-03-08 13:47:46 +01002829 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02002830}
2831
Kevin Wolf5c8cab42016-02-24 15:13:35 +01002832
2833static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2834{
2835 BdrvChild *c;
2836 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02002837 if (c->klass->change_media) {
2838 c->klass->change_media(c, load);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01002839 }
2840 }
2841}
2842
Alberto Garcia0065c452018-10-31 18:16:37 +02002843/* Return true if you can reach parent going through child->inherits_from
2844 * recursively. If parent or child are NULL, return false */
2845static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2846 BlockDriverState *parent)
2847{
2848 while (child && child != parent) {
2849 child = child->inherits_from;
2850 }
2851
2852 return child != NULL;
2853}
2854
Kevin Wolf5db15a52015-09-14 15:33:33 +02002855/*
Max Reitz25191e52020-05-13 13:05:33 +02002856 * Return the BdrvChildRole for @bs's backing child. bs->backing is
2857 * mostly used for COW backing children (role = COW), but also for
2858 * filtered children (role = FILTERED | PRIMARY).
2859 */
2860static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
2861{
2862 if (bs->drv && bs->drv->is_filter) {
2863 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
2864 } else {
2865 return BDRV_CHILD_COW;
2866 }
2867}
2868
2869/*
Max Reitz9ee413c2019-06-12 18:42:34 +02002870 * Sets the bs->backing link of a BDS. A new reference is created; callers
Kevin Wolf5db15a52015-09-14 15:33:33 +02002871 * which don't need their own reference any more must call bdrv_unref().
2872 */
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002873void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2874 Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08002875{
Alberto Garcia0065c452018-10-31 18:16:37 +02002876 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2877 bdrv_inherits_from_recursive(backing_hd, bs);
2878
Max Reitz9ee413c2019-06-12 18:42:34 +02002879 if (bdrv_is_backing_chain_frozen(bs, child_bs(bs->backing), errp)) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02002880 return;
2881 }
2882
Kevin Wolf5db15a52015-09-14 15:33:33 +02002883 if (backing_hd) {
2884 bdrv_ref(backing_hd);
2885 }
Fam Zheng8d24cce2014-05-23 21:29:45 +08002886
Kevin Wolf760e0062015-06-17 14:55:21 +02002887 if (bs->backing) {
Max Reitz7b99a262019-06-12 16:07:11 +02002888 /* Cannot be frozen, we checked that above */
Kevin Wolf5db15a52015-09-14 15:33:33 +02002889 bdrv_unref_child(bs, bs->backing);
Vladimir Sementsov-Ogievskiy6e579632020-03-16 09:06:30 +03002890 bs->backing = NULL;
Fam Zheng826b6ca2014-05-23 21:29:47 +08002891 }
2892
Fam Zheng8d24cce2014-05-23 21:29:45 +08002893 if (!backing_hd) {
2894 goto out;
2895 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002896
Max Reitz25191e52020-05-13 13:05:33 +02002897 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_of_bds,
2898 bdrv_backing_role(bs), errp);
Alberto Garcia0065c452018-10-31 18:16:37 +02002899 /* If backing_hd was already part of bs's backing chain, and
2900 * inherits_from pointed recursively to bs then let's update it to
2901 * point directly to bs (else it will become NULL). */
Alberto Garciab441dc72019-05-13 16:46:18 +03002902 if (bs->backing && update_inherits_from) {
Alberto Garcia0065c452018-10-31 18:16:37 +02002903 backing_hd->inherits_from = bs;
2904 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08002905
Fam Zheng8d24cce2014-05-23 21:29:45 +08002906out:
Kevin Wolf3baca892014-07-16 17:48:16 +02002907 bdrv_refresh_limits(bs, NULL);
Fam Zheng8d24cce2014-05-23 21:29:45 +08002908}
2909
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002910/*
2911 * Opens the backing file for a BlockDriverState if not yet open
2912 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002913 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2914 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2915 * itself, all options starting with "${bdref_key}." are considered part of the
2916 * BlockdevRef.
2917 *
2918 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002919 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002920int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2921 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02002922{
Max Reitz6b6833c2019-02-01 20:29:15 +01002923 char *backing_filename = NULL;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002924 char *bdref_key_dot;
2925 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02002926 int ret = 0;
Max Reitz998c2012019-02-01 20:29:08 +01002927 bool implicit_backing = false;
Fam Zheng8d24cce2014-05-23 21:29:45 +08002928 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002929 QDict *options;
2930 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002931 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002932
Kevin Wolf760e0062015-06-17 14:55:21 +02002933 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002934 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002935 }
2936
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002937 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002938 if (parent_options == NULL) {
2939 tmp_parent_options = qdict_new();
2940 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002941 }
2942
Paolo Bonzini9156df12012-10-18 16:49:17 +02002943 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002944
2945 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2946 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2947 g_free(bdref_key_dot);
2948
Markus Armbruster129c7d12017-03-30 19:43:12 +02002949 /*
2950 * Caution: while qdict_get_try_str() is fine, getting non-string
2951 * types would require more care. When @parent_options come from
2952 * -blockdev or blockdev_add, its members are typed according to
2953 * the QAPI schema, but when they come from -drive, they're all
2954 * QString.
2955 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002956 reference = qdict_get_try_str(parent_options, bdref_key);
2957 if (reference || qdict_haskey(options, "file.filename")) {
Max Reitz6b6833c2019-02-01 20:29:15 +01002958 /* keep backing_filename NULL */
Kevin Wolf1cb6f502013-04-12 20:27:07 +02002959 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002960 qobject_unref(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002961 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08002962 } else {
Max Reitz998c2012019-02-01 20:29:08 +01002963 if (qdict_size(options) == 0) {
2964 /* If the user specifies options that do not modify the
2965 * backing file's behavior, we might still consider it the
2966 * implicit backing file. But it's easier this way, and
2967 * just specifying some of the backing BDS's options is
2968 * only possible with -drive anyway (otherwise the QAPI
2969 * schema forces the user to specify everything). */
2970 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
2971 }
2972
Max Reitz6b6833c2019-02-01 20:29:15 +01002973 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
Max Reitz9f074292014-11-26 17:20:26 +01002974 if (local_err) {
2975 ret = -EINVAL;
2976 error_propagate(errp, local_err);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002977 qobject_unref(options);
Max Reitz9f074292014-11-26 17:20:26 +01002978 goto free_exit;
2979 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02002980 }
2981
Kevin Wolf8ee79e72014-06-04 15:09:35 +02002982 if (!bs->drv || !bs->drv->supports_backing) {
2983 ret = -EINVAL;
2984 error_setg(errp, "Driver doesn't support backing files");
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02002985 qobject_unref(options);
Kevin Wolf8ee79e72014-06-04 15:09:35 +02002986 goto free_exit;
2987 }
2988
Peter Krempa6bff5972017-10-12 16:14:10 +02002989 if (!reference &&
2990 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002991 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02002992 }
2993
Max Reitz6b6833c2019-02-01 20:29:15 +01002994 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
Max Reitz25191e52020-05-13 13:05:33 +02002995 &child_of_bds, bdrv_backing_role(bs), errp);
Max Reitz5b363932016-05-17 16:41:31 +02002996 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02002997 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01002998 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02002999 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003000 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003001 }
Kevin Wolfdf581792015-06-15 11:53:47 +02003002
Max Reitz998c2012019-02-01 20:29:08 +01003003 if (implicit_backing) {
3004 bdrv_refresh_filename(backing_hd);
3005 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3006 backing_hd->filename);
3007 }
3008
Kevin Wolf5db15a52015-09-14 15:33:33 +02003009 /* Hook up the backing file link; drop our reference, bs owns the
3010 * backing_hd reference now */
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003011 bdrv_set_backing_hd(bs, backing_hd, &local_err);
Kevin Wolf5db15a52015-09-14 15:33:33 +02003012 bdrv_unref(backing_hd);
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003013 if (local_err) {
Fam Zheng8cd1a3e2017-03-17 09:56:30 +08003014 error_propagate(errp, local_err);
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003015 ret = -EINVAL;
3016 goto free_exit;
3017 }
Peter Feinerd80ac652014-01-08 19:43:25 +00003018
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003019 qdict_del(parent_options, bdref_key);
3020
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003021free_exit:
3022 g_free(backing_filename);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003023 qobject_unref(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003024 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02003025}
3026
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003027static BlockDriverState *
3028bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
Max Reitzbd86fb92020-05-13 13:05:13 +02003029 BlockDriverState *parent, const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003030 BdrvChildRole child_role, bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01003031{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003032 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01003033 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01003034 char *bdref_key_dot;
3035 const char *reference;
3036
Max Reitzbd86fb92020-05-13 13:05:13 +02003037 assert(child_class != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01003038
Max Reitzda557aa2013-12-20 19:28:11 +01003039 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3040 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3041 g_free(bdref_key_dot);
3042
Markus Armbruster129c7d12017-03-30 19:43:12 +02003043 /*
3044 * Caution: while qdict_get_try_str() is fine, getting non-string
3045 * types would require more care. When @options come from
3046 * -blockdev or blockdev_add, its members are typed according to
3047 * the QAPI schema, but when they come from -drive, they're all
3048 * QString.
3049 */
Max Reitzda557aa2013-12-20 19:28:11 +01003050 reference = qdict_get_try_str(options, bdref_key);
3051 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003052 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01003053 error_setg(errp, "A block device must be specified for \"%s\"",
3054 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01003055 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003056 qobject_unref(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01003057 goto done;
3058 }
3059
Max Reitz5b363932016-05-17 16:41:31 +02003060 bs = bdrv_open_inherit(filename, reference, image_options, 0,
Max Reitz272c02e2020-05-13 13:05:17 +02003061 parent, child_class, child_role, errp);
Max Reitz5b363932016-05-17 16:41:31 +02003062 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02003063 goto done;
3064 }
3065
Max Reitzda557aa2013-12-20 19:28:11 +01003066done:
3067 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003068 return bs;
3069}
3070
3071/*
3072 * Opens a disk image whose options are given as BlockdevRef in another block
3073 * device's options.
3074 *
3075 * If allow_none is true, no image will be opened if filename is false and no
3076 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3077 *
3078 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3079 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3080 * itself, all options starting with "${bdref_key}." are considered part of the
3081 * BlockdevRef.
3082 *
3083 * The BlockdevRef will be removed from the options QDict.
3084 */
3085BdrvChild *bdrv_open_child(const char *filename,
3086 QDict *options, const char *bdref_key,
3087 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003088 const BdrvChildClass *child_class,
Max Reitz258b7762020-05-13 13:05:15 +02003089 BdrvChildRole child_role,
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003090 bool allow_none, Error **errp)
3091{
3092 BlockDriverState *bs;
3093
Max Reitzbd86fb92020-05-13 13:05:13 +02003094 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003095 child_role, allow_none, errp);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01003096 if (bs == NULL) {
3097 return NULL;
3098 }
3099
Max Reitz258b7762020-05-13 13:05:15 +02003100 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3101 errp);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02003102}
3103
Max Reitzbd86fb92020-05-13 13:05:13 +02003104/*
3105 * TODO Future callers may need to specify parent/child_class in order for
3106 * option inheritance to work. Existing callers use it for the root node.
3107 */
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003108BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3109{
3110 BlockDriverState *bs = NULL;
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003111 QObject *obj = NULL;
3112 QDict *qdict = NULL;
3113 const char *reference = NULL;
3114 Visitor *v = NULL;
3115
3116 if (ref->type == QTYPE_QSTRING) {
3117 reference = ref->u.reference;
3118 } else {
3119 BlockdevOptions *options = &ref->u.definition;
3120 assert(ref->type == QTYPE_QDICT);
3121
3122 v = qobject_output_visitor_new(&obj);
Markus Armbruster1f584242020-04-24 10:43:35 +02003123 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003124 visit_complete(v, &obj);
3125
Max Reitz7dc847e2018-02-24 16:40:29 +01003126 qdict = qobject_to(QDict, obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003127 qdict_flatten(qdict);
3128
3129 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3130 * compatibility with other callers) rather than what we want as the
3131 * real defaults. Apply the defaults here instead. */
3132 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3133 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3134 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
Kevin Wolfe35bdc12018-10-05 18:57:40 +02003135 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3136
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003137 }
3138
Max Reitz272c02e2020-05-13 13:05:17 +02003139 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003140 obj = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003141 qobject_unref(obj);
Kevin Wolfe1d74bc2018-01-10 15:52:33 +01003142 visit_free(v);
3143 return bs;
3144}
3145
Max Reitz66836182016-05-17 16:41:27 +02003146static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3147 int flags,
3148 QDict *snapshot_options,
3149 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02003150{
3151 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003152 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003153 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08003154 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05003155 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003156 Error *local_err = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02003157 int ret;
3158
3159 /* if snapshot, we create a temporary backing file and open it
3160 instead of opening 'filename' directly */
3161
3162 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02003163 total_size = bdrv_getlength(bs);
3164 if (total_size < 0) {
3165 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003166 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02003167 }
Kevin Wolfb9988752014-04-03 12:09:34 +02003168
3169 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003170 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02003171 if (ret < 0) {
3172 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003173 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003174 }
3175
Max Reitzef810432014-12-02 18:32:42 +01003176 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08003177 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01003178 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003179 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08003180 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02003181 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01003182 error_prepend(errp, "Could not create temporary overlay '%s': ",
3183 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003184 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003185 }
3186
Kevin Wolf73176be2016-03-07 13:02:15 +01003187 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05003188 qdict_put_str(snapshot_options, "file.driver", "file");
3189 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3190 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02003191
Max Reitz5b363932016-05-17 16:41:31 +02003192 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01003193 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003194 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003195 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02003196 }
3197
Eric Blakeff6ed712017-04-27 16:58:18 -05003198 /* bdrv_append() consumes a strong reference to bs_snapshot
3199 * (i.e. it will call bdrv_unref() on it) even on error, so in
3200 * order to be able to return one, we have to increase
3201 * bs_snapshot's refcount here */
Max Reitz66836182016-05-17 16:41:27 +02003202 bdrv_ref(bs_snapshot);
Kevin Wolfb2c28322017-02-20 12:46:42 +01003203 bdrv_append(bs_snapshot, bs, &local_err);
3204 if (local_err) {
3205 error_propagate(errp, local_err);
Eric Blakeff6ed712017-04-27 16:58:18 -05003206 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01003207 goto out;
3208 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003209
3210out:
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003211 qobject_unref(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02003212 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05003213 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02003214}
3215
Max Reitzda557aa2013-12-20 19:28:11 +01003216/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003217 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003218 *
3219 * options is a QDict of options to pass to the block drivers, or NULL for an
3220 * empty set of options. The reference to the QDict belongs to the block layer
3221 * after the call (even on failure), so if the caller intends to reuse the
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003222 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01003223 *
3224 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3225 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01003226 *
3227 * The reference parameter may be used to specify an existing block device which
3228 * should be opened. If specified, neither options nor a filename may be given,
3229 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003230 */
Max Reitz5b363932016-05-17 16:41:31 +02003231static BlockDriverState *bdrv_open_inherit(const char *filename,
3232 const char *reference,
3233 QDict *options, int flags,
3234 BlockDriverState *parent,
Max Reitzbd86fb92020-05-13 13:05:13 +02003235 const BdrvChildClass *child_class,
Max Reitz272c02e2020-05-13 13:05:17 +02003236 BdrvChildRole child_role,
Max Reitz5b363932016-05-17 16:41:31 +02003237 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00003238{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003239 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003240 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003241 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02003242 BlockDriver *drv = NULL;
Alberto Garcia2f624b82018-06-29 14:37:00 +03003243 BdrvChild *child;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02003244 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003245 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02003246 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01003247 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02003248 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00003249
Max Reitzbd86fb92020-05-13 13:05:13 +02003250 assert(!child_class || !flags);
3251 assert(!child_class == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01003252
Max Reitzddf56362014-02-18 18:33:06 +01003253 if (reference) {
3254 bool options_non_empty = options ? qdict_size(options) : false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003255 qobject_unref(options);
Max Reitzddf56362014-02-18 18:33:06 +01003256
Max Reitzddf56362014-02-18 18:33:06 +01003257 if (filename || options_non_empty) {
3258 error_setg(errp, "Cannot reference an existing block device with "
3259 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02003260 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003261 }
3262
3263 bs = bdrv_lookup_bs(reference, reference, errp);
3264 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02003265 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01003266 }
Kevin Wolf76b22322016-04-04 17:11:13 +02003267
Max Reitzddf56362014-02-18 18:33:06 +01003268 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02003269 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01003270 }
3271
Max Reitz5b363932016-05-17 16:41:31 +02003272 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01003273
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003274 /* NULL means an empty set of options */
3275 if (options == NULL) {
3276 options = qdict_new();
3277 }
3278
Kevin Wolf145f5982015-05-08 16:15:03 +02003279 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003280 parse_json_protocol(options, &filename, &local_err);
3281 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003282 goto fail;
3283 }
3284
Kevin Wolf145f5982015-05-08 16:15:03 +02003285 bs->explicit_options = qdict_clone_shallow(options);
3286
Max Reitzbd86fb92020-05-13 13:05:13 +02003287 if (child_class) {
Max Reitz3cdc69d2020-05-13 13:05:18 +02003288 bool parent_is_format;
3289
3290 if (parent->drv) {
3291 parent_is_format = parent->drv->is_format;
3292 } else {
3293 /*
3294 * parent->drv is not set yet because this node is opened for
3295 * (potential) format probing. That means that @parent is going
3296 * to be a format node.
3297 */
3298 parent_is_format = true;
3299 }
3300
Kevin Wolfbddcec32015-04-09 18:47:50 +02003301 bs->inherits_from = parent;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003302 child_class->inherit_options(child_role, parent_is_format,
3303 &flags, options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003304 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003305 }
3306
Kevin Wolfde3b53f2015-10-29 15:24:41 +01003307 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Philippe Mathieu-Daudédfde4832020-04-22 15:31:44 +02003308 if (ret < 0) {
Kevin Wolf462f5bc2014-05-26 11:39:55 +02003309 goto fail;
3310 }
3311
Markus Armbruster129c7d12017-03-30 19:43:12 +02003312 /*
3313 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3314 * Caution: getting a boolean member of @options requires care.
3315 * When @options come from -blockdev or blockdev_add, members are
3316 * typed according to the QAPI schema, but when they come from
3317 * -drive, they're all QString.
3318 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003319 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3320 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3321 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3322 } else {
3323 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03003324 }
3325
3326 if (flags & BDRV_O_SNAPSHOT) {
3327 snapshot_options = qdict_new();
3328 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3329 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03003330 /* Let bdrv_backing_options() override "read-only" */
3331 qdict_del(options, BDRV_OPT_READ_ONLY);
Max Reitz00ff7ff2020-05-13 13:05:21 +02003332 bdrv_inherited_options(BDRV_CHILD_COW, true,
3333 &flags, options, flags, options);
Alberto Garcia14499ea2016-09-15 17:53:00 +03003334 }
3335
Kevin Wolf62392eb2015-04-24 16:38:02 +02003336 bs->open_flags = flags;
3337 bs->options = options;
3338 options = qdict_clone_shallow(options);
3339
Kevin Wolf76c591b2014-06-04 14:19:44 +02003340 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02003341 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02003342 drvname = qdict_get_try_str(options, "driver");
3343 if (drvname) {
3344 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003345 if (!drv) {
3346 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003347 goto fail;
3348 }
3349 }
3350
3351 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02003352
Markus Armbruster129c7d12017-03-30 19:43:12 +02003353 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003354 backing = qdict_get_try_str(options, "backing");
Max Reitze59a0cf2018-02-24 16:40:32 +01003355 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3356 (backing && *backing == '\0'))
3357 {
Max Reitz4f7be282018-02-24 16:40:33 +01003358 if (backing) {
3359 warn_report("Use of \"backing\": \"\" is deprecated; "
3360 "use \"backing\": null instead");
3361 }
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003362 flags |= BDRV_O_NO_BACKING;
Kevin Wolfae0f57f2019-11-08 09:36:35 +01003363 qdict_del(bs->explicit_options, "backing");
3364 qdict_del(bs->options, "backing");
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02003365 qdict_del(options, "backing");
3366 }
3367
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003368 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003369 * probing, the block drivers will do their own bdrv_open_child() for the
3370 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02003371 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003372 BlockDriverState *file_bs;
3373
3374 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
Max Reitz58944402020-05-13 13:05:37 +02003375 &child_of_bds, BDRV_CHILD_IMAGE,
3376 true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02003377 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01003378 goto fail;
3379 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003380 if (file_bs != NULL) {
Kevin Wolfdacaa162017-11-20 14:59:13 +01003381 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3382 * looking at the header to guess the image format. This works even
3383 * in cases where a guest would not see a consistent state. */
Kevin Wolfd861ab32019-04-25 14:25:10 +02003384 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01003385 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003386 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01003387 if (local_err) {
3388 goto fail;
3389 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003390
Eric Blake46f5ac22017-04-27 16:58:17 -05003391 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003392 }
Max Reitz5469a2a2014-02-18 18:33:10 +01003393 }
3394
Kevin Wolf76c591b2014-06-04 14:19:44 +02003395 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01003396 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02003397 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02003398 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02003399 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003400 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01003401 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02003402 /*
3403 * This option update would logically belong in bdrv_fill_options(),
3404 * but we first need to open bs->file for the probing to work, while
3405 * opening bs->file already requires the (mostly) final set of options
3406 * so that cache mode etc. can be inherited.
3407 *
3408 * Adding the driver later is somewhat ugly, but it's not an option
3409 * that would ever be inherited, so it's correct. We just need to make
3410 * sure to update both bs->options (which has the full effective
3411 * options for bs) and options (which has file.* already removed).
3412 */
Eric Blake46f5ac22017-04-27 16:58:17 -05003413 qdict_put_str(bs->options, "driver", drv->format_name);
3414 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02003415 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02003416 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02003417 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01003418 }
3419
Max Reitz53a29512015-03-19 14:53:16 -04003420 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3421 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3422 /* file must be NULL if a protocol BDS is about to be created
3423 * (the inverse results in an error message from bdrv_open_common()) */
3424 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3425
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003426 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01003427 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003428 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02003429 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01003430 }
3431
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01003432 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003433 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01003434 file = NULL;
3435 }
3436
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003437 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02003438 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01003439 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003440 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003441 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003442 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003443 }
3444
Alberto Garcia50196d72018-09-06 12:37:03 +03003445 /* Remove all children options and references
3446 * from bs->options and bs->explicit_options */
Alberto Garcia2f624b82018-06-29 14:37:00 +03003447 QLIST_FOREACH(child, &bs->children, next) {
3448 char *child_key_dot;
3449 child_key_dot = g_strdup_printf("%s.", child->name);
3450 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3451 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
Alberto Garcia50196d72018-09-06 12:37:03 +03003452 qdict_del(bs->explicit_options, child->name);
3453 qdict_del(bs->options, child->name);
Alberto Garcia2f624b82018-06-29 14:37:00 +03003454 g_free(child_key_dot);
3455 }
3456
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003457 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01003458 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003459 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01003460 if (flags & BDRV_O_PROTOCOL) {
3461 error_setg(errp, "Block protocol '%s' doesn't support the option "
3462 "'%s'", drv->format_name, entry->key);
3463 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01003464 error_setg(errp,
3465 "Block format '%s' does not support the option '%s'",
3466 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01003467 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003468
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003469 goto close_and_fail;
3470 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003471
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01003472 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003473
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003474 qobject_unref(options);
Alberto Garcia8961be32018-09-06 17:25:41 +03003475 options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003476
3477 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3478 * temporary snapshot afterwards. */
3479 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02003480 BlockDriverState *snapshot_bs;
3481 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3482 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01003483 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003484 if (local_err) {
3485 goto close_and_fail;
3486 }
Max Reitz5b363932016-05-17 16:41:31 +02003487 /* We are not going to return bs but the overlay on top of it
3488 * (snapshot_bs); thus, we have to drop the strong reference to bs
3489 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3490 * though, because the overlay still has a reference to it. */
3491 bdrv_unref(bs);
3492 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02003493 }
3494
Max Reitz5b363932016-05-17 16:41:31 +02003495 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003496
Kevin Wolf8bfea152014-04-11 19:16:36 +02003497fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01003498 blk_unref(file);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003499 qobject_unref(snapshot_options);
3500 qobject_unref(bs->explicit_options);
3501 qobject_unref(bs->options);
3502 qobject_unref(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003503 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003504 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02003505 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003506 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003507 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003508
Kevin Wolfb6ad4912013-03-15 10:35:04 +01003509close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02003510 bdrv_unref(bs);
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003511 qobject_unref(snapshot_options);
3512 qobject_unref(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03003513 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02003514 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02003515}
3516
Max Reitz5b363932016-05-17 16:41:31 +02003517BlockDriverState *bdrv_open(const char *filename, const char *reference,
3518 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02003519{
Max Reitz5b363932016-05-17 16:41:31 +02003520 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitz272c02e2020-05-13 13:05:17 +02003521 NULL, 0, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02003522}
3523
Alberto Garciafaf116b2019-03-12 18:48:49 +02003524/* Return true if the NULL-terminated @list contains @str */
3525static bool is_str_in_list(const char *str, const char *const *list)
3526{
3527 if (str && list) {
3528 int i;
3529 for (i = 0; list[i] != NULL; i++) {
3530 if (!strcmp(str, list[i])) {
3531 return true;
3532 }
3533 }
3534 }
3535 return false;
3536}
3537
3538/*
3539 * Check that every option set in @bs->options is also set in
3540 * @new_opts.
3541 *
3542 * Options listed in the common_options list and in
3543 * @bs->drv->mutable_opts are skipped.
3544 *
3545 * Return 0 on success, otherwise return -EINVAL and set @errp.
3546 */
3547static int bdrv_reset_options_allowed(BlockDriverState *bs,
3548 const QDict *new_opts, Error **errp)
3549{
3550 const QDictEntry *e;
3551 /* These options are common to all block drivers and are handled
3552 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3553 const char *const common_options[] = {
3554 "node-name", "discard", "cache.direct", "cache.no-flush",
3555 "read-only", "auto-read-only", "detect-zeroes", NULL
3556 };
3557
3558 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3559 if (!qdict_haskey(new_opts, e->key) &&
3560 !is_str_in_list(e->key, common_options) &&
3561 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3562 error_setg(errp, "Option '%s' cannot be reset "
3563 "to its default value", e->key);
3564 return -EINVAL;
3565 }
3566 }
3567
3568 return 0;
3569}
3570
Jeff Codye971aa12012-09-20 15:13:19 -04003571/*
Alberto Garciacb828c32019-03-12 18:48:47 +02003572 * Returns true if @child can be reached recursively from @bs
3573 */
3574static bool bdrv_recurse_has_child(BlockDriverState *bs,
3575 BlockDriverState *child)
3576{
3577 BdrvChild *c;
3578
3579 if (bs == child) {
3580 return true;
3581 }
3582
3583 QLIST_FOREACH(c, &bs->children, next) {
3584 if (bdrv_recurse_has_child(c->bs, child)) {
3585 return true;
3586 }
3587 }
3588
3589 return false;
3590}
3591
3592/*
Jeff Codye971aa12012-09-20 15:13:19 -04003593 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3594 * reopen of multiple devices.
3595 *
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003596 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
Jeff Codye971aa12012-09-20 15:13:19 -04003597 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3598 * be created and initialized. This newly created BlockReopenQueue should be
3599 * passed back in for subsequent calls that are intended to be of the same
3600 * atomic 'set'.
3601 *
3602 * bs is the BlockDriverState to add to the reopen queue.
3603 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003604 * options contains the changed options for the associated bs
3605 * (the BlockReopenQueue takes ownership)
3606 *
Jeff Codye971aa12012-09-20 15:13:19 -04003607 * flags contains the open flags for the associated bs
3608 *
3609 * returns a pointer to bs_queue, which is either the newly allocated
3610 * bs_queue, or the existing bs_queue being used.
3611 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01003612 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04003613 */
Kevin Wolf28518102015-05-08 17:07:31 +02003614static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3615 BlockDriverState *bs,
3616 QDict *options,
Max Reitzbd86fb92020-05-13 13:05:13 +02003617 const BdrvChildClass *klass,
Max Reitz272c02e2020-05-13 13:05:17 +02003618 BdrvChildRole role,
Max Reitz3cdc69d2020-05-13 13:05:18 +02003619 bool parent_is_format,
Kevin Wolf28518102015-05-08 17:07:31 +02003620 QDict *parent_options,
Alberto Garcia077e8e22019-03-12 18:48:44 +02003621 int parent_flags,
3622 bool keep_old_opts)
Jeff Codye971aa12012-09-20 15:13:19 -04003623{
3624 assert(bs != NULL);
3625
3626 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02003627 BdrvChild *child;
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003628 QDict *old_options, *explicit_options, *options_copy;
3629 int flags;
3630 QemuOpts *opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02003631
Kevin Wolf1a63a902017-12-06 20:24:44 +01003632 /* Make sure that the caller remembered to use a drained section. This is
3633 * important to avoid graph changes between the recursive queuing here and
3634 * bdrv_reopen_multiple(). */
3635 assert(bs->quiesce_counter > 0);
3636
Jeff Codye971aa12012-09-20 15:13:19 -04003637 if (bs_queue == NULL) {
3638 bs_queue = g_new0(BlockReopenQueue, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003639 QTAILQ_INIT(bs_queue);
Jeff Codye971aa12012-09-20 15:13:19 -04003640 }
3641
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003642 if (!options) {
3643 options = qdict_new();
3644 }
3645
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003646 /* Check if this BlockDriverState is already in the queue */
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003647 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003648 if (bs == bs_entry->state.bs) {
3649 break;
3650 }
3651 }
3652
Kevin Wolf28518102015-05-08 17:07:31 +02003653 /*
3654 * Precedence of options:
3655 * 1. Explicitly passed in options (highest)
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003656 * 2. Retained from explicitly set options of bs
3657 * 3. Inherited from parent node
3658 * 4. Retained from effective options of bs
Kevin Wolf28518102015-05-08 17:07:31 +02003659 */
3660
Kevin Wolf145f5982015-05-08 16:15:03 +02003661 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia077e8e22019-03-12 18:48:44 +02003662 if (bs_entry || keep_old_opts) {
3663 old_options = qdict_clone_shallow(bs_entry ?
3664 bs_entry->state.explicit_options :
3665 bs->explicit_options);
3666 bdrv_join_options(bs, options, old_options);
3667 qobject_unref(old_options);
Alberto Garcia5b7ba052016-09-15 17:53:03 +03003668 }
Kevin Wolf145f5982015-05-08 16:15:03 +02003669
3670 explicit_options = qdict_clone_shallow(options);
3671
Kevin Wolf28518102015-05-08 17:07:31 +02003672 /* Inherit from parent node */
3673 if (parent_options) {
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003674 flags = 0;
Max Reitz3cdc69d2020-05-13 13:05:18 +02003675 klass->inherit_options(role, parent_is_format, &flags, options,
Max Reitz272c02e2020-05-13 13:05:17 +02003676 parent_flags, parent_options);
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003677 } else {
3678 flags = bdrv_get_flags(bs);
Kevin Wolf28518102015-05-08 17:07:31 +02003679 }
3680
Alberto Garcia077e8e22019-03-12 18:48:44 +02003681 if (keep_old_opts) {
3682 /* Old values are used for options that aren't set yet */
3683 old_options = qdict_clone_shallow(bs->options);
3684 bdrv_join_options(bs, options, old_options);
3685 qobject_unref(old_options);
3686 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02003687
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003688 /* We have the final set of options so let's update the flags */
3689 options_copy = qdict_clone_shallow(options);
3690 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3691 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3692 update_flags_from_options(&flags, opts);
3693 qemu_opts_del(opts);
3694 qobject_unref(options_copy);
3695
Kevin Wolffd452022017-08-03 17:02:59 +02003696 /* bdrv_open_inherit() sets and clears some additional flags internally */
Kevin Wolff1f25a22014-04-25 19:04:55 +02003697 flags &= ~BDRV_O_PROTOCOL;
Kevin Wolffd452022017-08-03 17:02:59 +02003698 if (flags & BDRV_O_RDWR) {
3699 flags |= BDRV_O_ALLOW_RDWR;
3700 }
Kevin Wolff1f25a22014-04-25 19:04:55 +02003701
Kevin Wolf1857c972017-09-14 14:53:46 +02003702 if (!bs_entry) {
3703 bs_entry = g_new0(BlockReopenQueueEntry, 1);
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003704 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
Kevin Wolf1857c972017-09-14 14:53:46 +02003705 } else {
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003706 qobject_unref(bs_entry->state.options);
3707 qobject_unref(bs_entry->state.explicit_options);
Kevin Wolf1857c972017-09-14 14:53:46 +02003708 }
3709
3710 bs_entry->state.bs = bs;
3711 bs_entry->state.options = options;
3712 bs_entry->state.explicit_options = explicit_options;
3713 bs_entry->state.flags = flags;
3714
Kevin Wolf30450252017-07-03 17:07:35 +02003715 /* This needs to be overwritten in bdrv_reopen_prepare() */
3716 bs_entry->state.perm = UINT64_MAX;
3717 bs_entry->state.shared_perm = 0;
3718
Alberto Garcia85466322019-03-12 18:48:45 +02003719 /*
3720 * If keep_old_opts is false then it means that unspecified
3721 * options must be reset to their original value. We don't allow
3722 * resetting 'backing' but we need to know if the option is
3723 * missing in order to decide if we have to return an error.
3724 */
3725 if (!keep_old_opts) {
3726 bs_entry->state.backing_missing =
3727 !qdict_haskey(options, "backing") &&
3728 !qdict_haskey(options, "backing.driver");
3729 }
3730
Kevin Wolf67251a32015-04-09 18:54:04 +02003731 QLIST_FOREACH(child, &bs->children, next) {
Alberto Garcia85466322019-03-12 18:48:45 +02003732 QDict *new_child_options = NULL;
3733 bool child_keep_old = keep_old_opts;
Kevin Wolf67251a32015-04-09 18:54:04 +02003734
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02003735 /* reopen can only change the options of block devices that were
3736 * implicitly created and inherited options. For other (referenced)
3737 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02003738 if (child->bs->inherits_from != bs) {
3739 continue;
3740 }
3741
Alberto Garcia85466322019-03-12 18:48:45 +02003742 /* Check if the options contain a child reference */
3743 if (qdict_haskey(options, child->name)) {
3744 const char *childref = qdict_get_try_str(options, child->name);
3745 /*
3746 * The current child must not be reopened if the child
3747 * reference is null or points to a different node.
3748 */
3749 if (g_strcmp0(childref, child->bs->node_name)) {
3750 continue;
3751 }
3752 /*
3753 * If the child reference points to the current child then
3754 * reopen it with its existing set of options (note that
3755 * it can still inherit new options from the parent).
3756 */
3757 child_keep_old = true;
3758 } else {
3759 /* Extract child options ("child-name.*") */
3760 char *child_key_dot = g_strdup_printf("%s.", child->name);
3761 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3762 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3763 g_free(child_key_dot);
3764 }
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02003765
Alberto Garcia9aa09dd2018-11-12 16:00:45 +02003766 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
Max Reitz3cdc69d2020-05-13 13:05:18 +02003767 child->klass, child->role, bs->drv->is_format,
3768 options, flags, child_keep_old);
Jeff Codye971aa12012-09-20 15:13:19 -04003769 }
3770
Jeff Codye971aa12012-09-20 15:13:19 -04003771 return bs_queue;
3772}
3773
Kevin Wolf28518102015-05-08 17:07:31 +02003774BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3775 BlockDriverState *bs,
Alberto Garcia077e8e22019-03-12 18:48:44 +02003776 QDict *options, bool keep_old_opts)
Kevin Wolf28518102015-05-08 17:07:31 +02003777{
Max Reitz3cdc69d2020-05-13 13:05:18 +02003778 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
3779 NULL, 0, keep_old_opts);
Kevin Wolf28518102015-05-08 17:07:31 +02003780}
3781
Jeff Codye971aa12012-09-20 15:13:19 -04003782/*
3783 * Reopen multiple BlockDriverStates atomically & transactionally.
3784 *
3785 * The queue passed in (bs_queue) must have been built up previous
3786 * via bdrv_reopen_queue().
3787 *
3788 * Reopens all BDS specified in the queue, with the appropriate
3789 * flags. All devices are prepared for reopen, and failure of any
Stefan Weil50d6a8a2018-07-12 21:51:20 +02003790 * device will cause all device changes to be abandoned, and intermediate
Jeff Codye971aa12012-09-20 15:13:19 -04003791 * data cleaned up.
3792 *
3793 * If all devices prepare successfully, then the changes are committed
3794 * to all devices.
3795 *
Kevin Wolf1a63a902017-12-06 20:24:44 +01003796 * All affected nodes must be drained between bdrv_reopen_queue() and
3797 * bdrv_reopen_multiple().
Jeff Codye971aa12012-09-20 15:13:19 -04003798 */
Alberto Garcia5019aec2019-03-12 18:48:50 +02003799int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04003800{
3801 int ret = -1;
3802 BlockReopenQueueEntry *bs_entry, *next;
Jeff Codye971aa12012-09-20 15:13:19 -04003803
3804 assert(bs_queue != NULL);
3805
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003806 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf1a63a902017-12-06 20:24:44 +01003807 assert(bs_entry->state.bs->quiesce_counter > 0);
Kevin Wolfa4615ab2019-03-05 16:51:13 +01003808 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
Jeff Codye971aa12012-09-20 15:13:19 -04003809 goto cleanup;
3810 }
3811 bs_entry->prepared = true;
3812 }
3813
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003814 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01003815 BDRVReopenState *state = &bs_entry->state;
3816 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
Max Reitz9eab1542019-05-22 19:03:50 +02003817 state->shared_perm, NULL, NULL, errp);
Kevin Wolf69b736e2019-03-05 17:18:22 +01003818 if (ret < 0) {
3819 goto cleanup_perm;
3820 }
Alberto Garciacb828c32019-03-12 18:48:47 +02003821 /* Check if new_backing_bs would accept the new permissions */
3822 if (state->replace_backing_bs && state->new_backing_bs) {
3823 uint64_t nperm, nshared;
3824 bdrv_child_perm(state->bs, state->new_backing_bs,
Max Reitze5d8a402020-05-13 13:05:44 +02003825 NULL, bdrv_backing_role(state->bs),
Max Reitz25191e52020-05-13 13:05:33 +02003826 bs_queue, state->perm, state->shared_perm,
Alberto Garciacb828c32019-03-12 18:48:47 +02003827 &nperm, &nshared);
3828 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
Max Reitz9eab1542019-05-22 19:03:50 +02003829 nperm, nshared, NULL, NULL, errp);
Alberto Garciacb828c32019-03-12 18:48:47 +02003830 if (ret < 0) {
3831 goto cleanup_perm;
3832 }
3833 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01003834 bs_entry->perms_checked = true;
3835 }
3836
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03003837 /*
3838 * If we reach this point, we have success and just need to apply the
3839 * changes.
3840 *
3841 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3842 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3843 * children are usually goes after parents in reopen-queue, so go from last
3844 * to first element.
Jeff Codye971aa12012-09-20 15:13:19 -04003845 */
Vladimir Sementsov-Ogievskiyfcd6a4f2019-09-27 15:23:48 +03003846 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
Jeff Codye971aa12012-09-20 15:13:19 -04003847 bdrv_reopen_commit(&bs_entry->state);
3848 }
3849
3850 ret = 0;
Kevin Wolf69b736e2019-03-05 17:18:22 +01003851cleanup_perm:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003852 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Kevin Wolf69b736e2019-03-05 17:18:22 +01003853 BDRVReopenState *state = &bs_entry->state;
Jeff Codye971aa12012-09-20 15:13:19 -04003854
Kevin Wolf69b736e2019-03-05 17:18:22 +01003855 if (!bs_entry->perms_checked) {
3856 continue;
3857 }
3858
3859 if (ret == 0) {
3860 bdrv_set_perm(state->bs, state->perm, state->shared_perm);
3861 } else {
3862 bdrv_abort_perm_update(state->bs);
Alberto Garciacb828c32019-03-12 18:48:47 +02003863 if (state->replace_backing_bs && state->new_backing_bs) {
3864 bdrv_abort_perm_update(state->new_backing_bs);
3865 }
Kevin Wolf69b736e2019-03-05 17:18:22 +01003866 }
3867 }
Peter Krempa17e1e2b2020-02-28 13:44:46 +01003868
3869 if (ret == 0) {
3870 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3871 BlockDriverState *bs = bs_entry->state.bs;
3872
3873 if (bs->drv->bdrv_reopen_commit_post)
3874 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
3875 }
3876 }
Jeff Codye971aa12012-09-20 15:13:19 -04003877cleanup:
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003878 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
Alberto Garcia1bab38e2018-06-29 14:37:01 +03003879 if (ret) {
3880 if (bs_entry->prepared) {
3881 bdrv_reopen_abort(&bs_entry->state);
3882 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02003883 qobject_unref(bs_entry->state.explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03003884 qobject_unref(bs_entry->state.options);
Jeff Codye971aa12012-09-20 15:13:19 -04003885 }
Alberto Garciacb828c32019-03-12 18:48:47 +02003886 if (bs_entry->state.new_backing_bs) {
3887 bdrv_unref(bs_entry->state.new_backing_bs);
3888 }
Jeff Codye971aa12012-09-20 15:13:19 -04003889 g_free(bs_entry);
3890 }
3891 g_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03003892
Jeff Codye971aa12012-09-20 15:13:19 -04003893 return ret;
3894}
3895
Alberto Garcia6e1000a2018-11-12 16:00:33 +02003896int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3897 Error **errp)
3898{
3899 int ret;
3900 BlockReopenQueue *queue;
3901 QDict *opts = qdict_new();
3902
3903 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3904
3905 bdrv_subtree_drained_begin(bs);
Alberto Garcia077e8e22019-03-12 18:48:44 +02003906 queue = bdrv_reopen_queue(NULL, bs, opts, true);
Alberto Garcia5019aec2019-03-12 18:48:50 +02003907 ret = bdrv_reopen_multiple(queue, errp);
Alberto Garcia6e1000a2018-11-12 16:00:33 +02003908 bdrv_subtree_drained_end(bs);
3909
3910 return ret;
3911}
3912
Kevin Wolf30450252017-07-03 17:07:35 +02003913static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3914 BdrvChild *c)
3915{
3916 BlockReopenQueueEntry *entry;
3917
Vladimir Sementsov-Ogievskiy859443b2019-09-27 15:23:47 +03003918 QTAILQ_FOREACH(entry, q, entry) {
Kevin Wolf30450252017-07-03 17:07:35 +02003919 BlockDriverState *bs = entry->state.bs;
3920 BdrvChild *child;
3921
3922 QLIST_FOREACH(child, &bs->children, next) {
3923 if (child == c) {
3924 return entry;
3925 }
3926 }
3927 }
3928
3929 return NULL;
3930}
3931
3932static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3933 uint64_t *perm, uint64_t *shared)
3934{
3935 BdrvChild *c;
3936 BlockReopenQueueEntry *parent;
3937 uint64_t cumulative_perms = 0;
3938 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3939
3940 QLIST_FOREACH(c, &bs->parents, next_parent) {
3941 parent = find_parent_in_reopen_queue(q, c);
3942 if (!parent) {
3943 cumulative_perms |= c->perm;
3944 cumulative_shared_perms &= c->shared_perm;
3945 } else {
3946 uint64_t nperm, nshared;
3947
Max Reitze5d8a402020-05-13 13:05:44 +02003948 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
Kevin Wolf30450252017-07-03 17:07:35 +02003949 parent->state.perm, parent->state.shared_perm,
3950 &nperm, &nshared);
3951
3952 cumulative_perms |= nperm;
3953 cumulative_shared_perms &= nshared;
3954 }
3955 }
3956 *perm = cumulative_perms;
3957 *shared = cumulative_shared_perms;
3958}
Jeff Codye971aa12012-09-20 15:13:19 -04003959
Kevin Wolf1de6b452020-03-06 15:14:13 +01003960static bool bdrv_reopen_can_attach(BlockDriverState *parent,
3961 BdrvChild *child,
3962 BlockDriverState *new_child,
3963 Error **errp)
3964{
3965 AioContext *parent_ctx = bdrv_get_aio_context(parent);
3966 AioContext *child_ctx = bdrv_get_aio_context(new_child);
3967 GSList *ignore;
3968 bool ret;
3969
3970 ignore = g_slist_prepend(NULL, child);
3971 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
3972 g_slist_free(ignore);
3973 if (ret) {
3974 return ret;
3975 }
3976
3977 ignore = g_slist_prepend(NULL, child);
3978 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
3979 g_slist_free(ignore);
3980 return ret;
3981}
3982
Jeff Codye971aa12012-09-20 15:13:19 -04003983/*
Alberto Garciacb828c32019-03-12 18:48:47 +02003984 * Take a BDRVReopenState and check if the value of 'backing' in the
3985 * reopen_state->options QDict is valid or not.
3986 *
3987 * If 'backing' is missing from the QDict then return 0.
3988 *
3989 * If 'backing' contains the node name of the backing file of
3990 * reopen_state->bs then return 0.
3991 *
3992 * If 'backing' contains a different node name (or is null) then check
3993 * whether the current backing file can be replaced with the new one.
3994 * If that's the case then reopen_state->replace_backing_bs is set to
3995 * true and reopen_state->new_backing_bs contains a pointer to the new
3996 * backing BlockDriverState (or NULL).
3997 *
3998 * Return 0 on success, otherwise return < 0 and set @errp.
3999 */
4000static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
4001 Error **errp)
4002{
4003 BlockDriverState *bs = reopen_state->bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004004 BlockDriverState *overlay_bs, *below_bs, *new_backing_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004005 QObject *value;
4006 const char *str;
4007
4008 value = qdict_get(reopen_state->options, "backing");
4009 if (value == NULL) {
4010 return 0;
4011 }
4012
4013 switch (qobject_type(value)) {
4014 case QTYPE_QNULL:
4015 new_backing_bs = NULL;
4016 break;
4017 case QTYPE_QSTRING:
4018 str = qobject_get_try_str(value);
4019 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4020 if (new_backing_bs == NULL) {
4021 return -EINVAL;
4022 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4023 error_setg(errp, "Making '%s' a backing file of '%s' "
4024 "would create a cycle", str, bs->node_name);
4025 return -EINVAL;
4026 }
4027 break;
4028 default:
4029 /* 'backing' does not allow any other data type */
4030 g_assert_not_reached();
4031 }
4032
4033 /*
Kevin Wolf1de6b452020-03-06 15:14:13 +01004034 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4035 * bdrv_reopen_commit() won't fail.
Alberto Garciacb828c32019-03-12 18:48:47 +02004036 */
4037 if (new_backing_bs) {
Kevin Wolf1de6b452020-03-06 15:14:13 +01004038 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004039 return -EINVAL;
4040 }
4041 }
4042
4043 /*
Max Reitz1d42f482019-06-12 17:24:39 +02004044 * Ensure that @bs can really handle backing files, because we are
4045 * about to give it one (or swap the existing one)
4046 */
4047 if (bs->drv->is_filter) {
4048 /* Filters always have a file or a backing child */
4049 if (!bs->backing) {
4050 error_setg(errp, "'%s' is a %s filter node that does not support a "
4051 "backing child", bs->node_name, bs->drv->format_name);
4052 return -EINVAL;
4053 }
4054 } else if (!bs->drv->supports_backing) {
4055 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
4056 "files", bs->drv->format_name, bs->node_name);
4057 return -EINVAL;
4058 }
4059
4060 /*
Alberto Garciacb828c32019-03-12 18:48:47 +02004061 * Find the "actual" backing file by skipping all links that point
4062 * to an implicit node, if any (e.g. a commit filter node).
Max Reitz1d42f482019-06-12 17:24:39 +02004063 * We cannot use any of the bdrv_skip_*() functions here because
4064 * those return the first explicit node, while we are looking for
4065 * its overlay here.
Alberto Garciacb828c32019-03-12 18:48:47 +02004066 */
4067 overlay_bs = bs;
Max Reitz1d42f482019-06-12 17:24:39 +02004068 for (below_bs = bdrv_filter_or_cow_bs(overlay_bs);
4069 below_bs && below_bs->implicit;
4070 below_bs = bdrv_filter_or_cow_bs(overlay_bs))
4071 {
4072 overlay_bs = below_bs;
Alberto Garciacb828c32019-03-12 18:48:47 +02004073 }
4074
4075 /* If we want to replace the backing file we need some extra checks */
Max Reitz1d42f482019-06-12 17:24:39 +02004076 if (new_backing_bs != bdrv_filter_or_cow_bs(overlay_bs)) {
Alberto Garciacb828c32019-03-12 18:48:47 +02004077 /* Check for implicit nodes between bs and its backing file */
4078 if (bs != overlay_bs) {
4079 error_setg(errp, "Cannot change backing link if '%s' has "
4080 "an implicit backing file", bs->node_name);
4081 return -EPERM;
4082 }
Max Reitz1d42f482019-06-12 17:24:39 +02004083 /*
4084 * Check if the backing link that we want to replace is frozen.
4085 * Note that
4086 * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4087 * because we know that overlay_bs == bs, and that @bs
4088 * either is a filter that uses ->backing or a COW format BDS
4089 * with bs->drv->supports_backing == true.
4090 */
4091 if (bdrv_is_backing_chain_frozen(overlay_bs,
4092 child_bs(overlay_bs->backing), errp))
4093 {
Alberto Garciacb828c32019-03-12 18:48:47 +02004094 return -EPERM;
4095 }
4096 reopen_state->replace_backing_bs = true;
4097 if (new_backing_bs) {
4098 bdrv_ref(new_backing_bs);
4099 reopen_state->new_backing_bs = new_backing_bs;
4100 }
4101 }
4102
4103 return 0;
4104}
4105
4106/*
Jeff Codye971aa12012-09-20 15:13:19 -04004107 * Prepares a BlockDriverState for reopen. All changes are staged in the
4108 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4109 * the block driver layer .bdrv_reopen_prepare()
4110 *
4111 * bs is the BlockDriverState to reopen
4112 * flags are the new open flags
4113 * queue is the reopen queue
4114 *
4115 * Returns 0 on success, non-zero on error. On error errp will be set
4116 * as well.
4117 *
4118 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4119 * It is the responsibility of the caller to then call the abort() or
4120 * commit() for any other BDS that have been left in a prepare() state
4121 *
4122 */
4123int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4124 Error **errp)
4125{
4126 int ret = -1;
Alberto Garciae6d79c42018-11-12 16:00:47 +02004127 int old_flags;
Jeff Codye971aa12012-09-20 15:13:19 -04004128 Error *local_err = NULL;
4129 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004130 QemuOpts *opts;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004131 QDict *orig_reopen_opts;
Alberto Garcia593b3072018-09-06 12:37:08 +03004132 char *discard = NULL;
Jeff Cody3d8ce172017-04-07 16:55:30 -04004133 bool read_only;
Max Reitz9ad08c42018-11-16 17:45:24 +01004134 bool drv_prepared = false;
Jeff Codye971aa12012-09-20 15:13:19 -04004135
4136 assert(reopen_state != NULL);
4137 assert(reopen_state->bs->drv != NULL);
4138 drv = reopen_state->bs->drv;
4139
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004140 /* This function and each driver's bdrv_reopen_prepare() remove
4141 * entries from reopen_state->options as they are processed, so
4142 * we need to make a copy of the original QDict. */
4143 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4144
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004145 /* Process generic block layer options */
4146 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
Markus Armbrusteraf175e82020-07-07 18:06:03 +02004147 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004148 ret = -EINVAL;
4149 goto error;
4150 }
4151
Alberto Garciae6d79c42018-11-12 16:00:47 +02004152 /* This was already called in bdrv_reopen_queue_child() so the flags
4153 * are up-to-date. This time we simply want to remove the options from
4154 * QemuOpts in order to indicate that they have been processed. */
4155 old_flags = reopen_state->flags;
Kevin Wolf91a097e2015-05-08 17:49:53 +02004156 update_flags_from_options(&reopen_state->flags, opts);
Alberto Garciae6d79c42018-11-12 16:00:47 +02004157 assert(old_flags == reopen_state->flags);
Kevin Wolf91a097e2015-05-08 17:49:53 +02004158
Alberto Garcia415bbca2018-10-03 13:23:13 +03004159 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
Alberto Garcia593b3072018-09-06 12:37:08 +03004160 if (discard != NULL) {
4161 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4162 error_setg(errp, "Invalid discard option");
4163 ret = -EINVAL;
4164 goto error;
4165 }
4166 }
4167
Alberto Garcia543770b2018-09-06 12:37:09 +03004168 reopen_state->detect_zeroes =
4169 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4170 if (local_err) {
4171 error_propagate(errp, local_err);
4172 ret = -EINVAL;
4173 goto error;
4174 }
4175
Alberto Garcia57f9db92018-09-06 12:37:06 +03004176 /* All other options (including node-name and driver) must be unchanged.
4177 * Put them back into the QDict, so that they are checked at the end
4178 * of this function. */
4179 qemu_opts_to_qdict(opts, reopen_state->options);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004180
Jeff Cody3d8ce172017-04-07 16:55:30 -04004181 /* If we are to stay read-only, do not allow permission change
4182 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4183 * not set, or if the BDS still has copy_on_read enabled */
4184 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02004185 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04004186 if (local_err) {
4187 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04004188 goto error;
4189 }
4190
Kevin Wolf30450252017-07-03 17:07:35 +02004191 /* Calculate required permissions after reopening */
4192 bdrv_reopen_perm(queue, reopen_state->bs,
4193 &reopen_state->perm, &reopen_state->shared_perm);
Jeff Codye971aa12012-09-20 15:13:19 -04004194
4195 ret = bdrv_flush(reopen_state->bs);
4196 if (ret) {
Eric Blake455b0fd2015-11-10 23:51:20 -07004197 error_setg_errno(errp, -ret, "Error flushing drive");
Jeff Codye971aa12012-09-20 15:13:19 -04004198 goto error;
4199 }
4200
4201 if (drv->bdrv_reopen_prepare) {
Alberto Garciafaf116b2019-03-12 18:48:49 +02004202 /*
4203 * If a driver-specific option is missing, it means that we
4204 * should reset it to its default value.
4205 * But not all options allow that, so we need to check it first.
4206 */
4207 ret = bdrv_reset_options_allowed(reopen_state->bs,
4208 reopen_state->options, errp);
4209 if (ret) {
4210 goto error;
4211 }
4212
Jeff Codye971aa12012-09-20 15:13:19 -04004213 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4214 if (ret) {
4215 if (local_err != NULL) {
4216 error_propagate(errp, local_err);
4217 } else {
Max Reitzf30c66b2019-02-01 20:29:05 +01004218 bdrv_refresh_filename(reopen_state->bs);
Luiz Capitulinod8b68952013-06-10 11:29:27 -04004219 error_setg(errp, "failed while preparing to reopen image '%s'",
4220 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04004221 }
4222 goto error;
4223 }
4224 } else {
4225 /* It is currently mandatory to have a bdrv_reopen_prepare()
4226 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03004227 error_setg(errp, "Block format '%s' used by node '%s' "
4228 "does not support reopening files", drv->format_name,
4229 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04004230 ret = -1;
4231 goto error;
4232 }
4233
Max Reitz9ad08c42018-11-16 17:45:24 +01004234 drv_prepared = true;
4235
Alberto Garciabacd9b82019-03-12 18:48:46 +02004236 /*
4237 * We must provide the 'backing' option if the BDS has a backing
4238 * file or if the image file has a backing file name as part of
4239 * its metadata. Otherwise the 'backing' option can be omitted.
4240 */
4241 if (drv->supports_backing && reopen_state->backing_missing &&
Max Reitz1d42f482019-06-12 17:24:39 +02004242 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
Alberto Garcia85466322019-03-12 18:48:45 +02004243 error_setg(errp, "backing is missing for '%s'",
4244 reopen_state->bs->node_name);
4245 ret = -EINVAL;
4246 goto error;
4247 }
4248
Alberto Garciacb828c32019-03-12 18:48:47 +02004249 /*
4250 * Allow changing the 'backing' option. The new value can be
4251 * either a reference to an existing node (using its node name)
4252 * or NULL to simply detach the current backing file.
4253 */
4254 ret = bdrv_reopen_parse_backing(reopen_state, errp);
4255 if (ret < 0) {
4256 goto error;
4257 }
4258 qdict_del(reopen_state->options, "backing");
4259
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004260 /* Options that are not handled are only okay if they are unchanged
4261 * compared to the old state. It is expected that some options are only
4262 * used for the initial open, but not reopen (e.g. filename) */
4263 if (qdict_size(reopen_state->options)) {
4264 const QDictEntry *entry = qdict_first(reopen_state->options);
4265
4266 do {
Max Reitz54fd1b02017-11-14 19:01:26 +01004267 QObject *new = entry->value;
4268 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004269
Alberto Garciadb905282018-09-06 12:37:05 +03004270 /* Allow child references (child_name=node_name) as long as they
4271 * point to the current child (i.e. everything stays the same). */
4272 if (qobject_type(new) == QTYPE_QSTRING) {
4273 BdrvChild *child;
4274 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4275 if (!strcmp(child->name, entry->key)) {
4276 break;
4277 }
4278 }
4279
4280 if (child) {
4281 const char *str = qobject_get_try_str(new);
4282 if (!strcmp(child->bs->node_name, str)) {
4283 continue; /* Found child with this name, skip option */
4284 }
4285 }
4286 }
4287
Max Reitz54fd1b02017-11-14 19:01:26 +01004288 /*
4289 * TODO: When using -drive to specify blockdev options, all values
4290 * will be strings; however, when using -blockdev, blockdev-add or
4291 * filenames using the json:{} pseudo-protocol, they will be
4292 * correctly typed.
4293 * In contrast, reopening options are (currently) always strings
4294 * (because you can only specify them through qemu-io; all other
4295 * callers do not specify any options).
4296 * Therefore, when using anything other than -drive to create a BDS,
4297 * this cannot detect non-string options as unchanged, because
4298 * qobject_is_equal() always returns false for objects of different
4299 * type. In the future, this should be remedied by correctly typing
4300 * all options. For now, this is not too big of an issue because
4301 * the user can simply omit options which cannot be changed anyway,
4302 * so they will stay unchanged.
4303 */
4304 if (!qobject_is_equal(new, old)) {
Kevin Wolf4d2cb092015-04-10 17:50:50 +02004305 error_setg(errp, "Cannot change the option '%s'", entry->key);
4306 ret = -EINVAL;
4307 goto error;
4308 }
4309 } while ((entry = qdict_next(reopen_state->options, entry)));
4310 }
4311
Jeff Codye971aa12012-09-20 15:13:19 -04004312 ret = 0;
4313
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004314 /* Restore the original reopen_state->options QDict */
4315 qobject_unref(reopen_state->options);
4316 reopen_state->options = qobject_ref(orig_reopen_opts);
4317
Jeff Codye971aa12012-09-20 15:13:19 -04004318error:
Max Reitz9ad08c42018-11-16 17:45:24 +01004319 if (ret < 0 && drv_prepared) {
4320 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4321 * call drv->bdrv_reopen_abort() before signaling an error
4322 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4323 * when the respective bdrv_reopen_prepare() has failed) */
4324 if (drv->bdrv_reopen_abort) {
4325 drv->bdrv_reopen_abort(reopen_state);
4326 }
4327 }
Kevin Wolfccf9dc02015-05-08 17:24:56 +02004328 qemu_opts_del(opts);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004329 qobject_unref(orig_reopen_opts);
Alberto Garcia593b3072018-09-06 12:37:08 +03004330 g_free(discard);
Jeff Codye971aa12012-09-20 15:13:19 -04004331 return ret;
4332}
4333
4334/*
4335 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4336 * makes them final by swapping the staging BlockDriverState contents into
4337 * the active BlockDriverState contents.
4338 */
4339void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4340{
4341 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004342 BlockDriverState *bs;
Alberto Garcia50196d72018-09-06 12:37:03 +03004343 BdrvChild *child;
Jeff Codye971aa12012-09-20 15:13:19 -04004344
4345 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004346 bs = reopen_state->bs;
4347 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04004348 assert(drv != NULL);
4349
4350 /* If there are any driver level actions to take */
4351 if (drv->bdrv_reopen_commit) {
4352 drv->bdrv_reopen_commit(reopen_state);
4353 }
4354
4355 /* set BDS specific flags now */
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004356 qobject_unref(bs->explicit_options);
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004357 qobject_unref(bs->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02004358
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004359 bs->explicit_options = reopen_state->explicit_options;
Alberto Garcia4c8350f2018-06-29 14:37:02 +03004360 bs->options = reopen_state->options;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004361 bs->open_flags = reopen_state->flags;
4362 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
Alberto Garcia543770b2018-09-06 12:37:09 +03004363 bs->detect_zeroes = reopen_state->detect_zeroes;
Kevin Wolf355ef4a2013-12-11 20:14:09 +01004364
Alberto Garciacb828c32019-03-12 18:48:47 +02004365 if (reopen_state->replace_backing_bs) {
4366 qdict_del(bs->explicit_options, "backing");
4367 qdict_del(bs->options, "backing");
4368 }
4369
Alberto Garcia50196d72018-09-06 12:37:03 +03004370 /* Remove child references from bs->options and bs->explicit_options.
4371 * Child options were already removed in bdrv_reopen_queue_child() */
4372 QLIST_FOREACH(child, &bs->children, next) {
4373 qdict_del(bs->explicit_options, child->name);
4374 qdict_del(bs->options, child->name);
4375 }
4376
Alberto Garciacb828c32019-03-12 18:48:47 +02004377 /*
4378 * Change the backing file if a new one was specified. We do this
4379 * after updating bs->options, so bdrv_refresh_filename() (called
4380 * from bdrv_set_backing_hd()) has the new values.
4381 */
4382 if (reopen_state->replace_backing_bs) {
Max Reitz1d42f482019-06-12 17:24:39 +02004383 BlockDriverState *old_backing_bs = child_bs(bs->backing);
Alberto Garciacb828c32019-03-12 18:48:47 +02004384 assert(!old_backing_bs || !old_backing_bs->implicit);
4385 /* Abort the permission update on the backing bs we're detaching */
4386 if (old_backing_bs) {
4387 bdrv_abort_perm_update(old_backing_bs);
4388 }
4389 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4390 }
4391
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03004392 bdrv_refresh_limits(bs, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04004393}
4394
4395/*
4396 * Abort the reopen, and delete and free the staged changes in
4397 * reopen_state
4398 */
4399void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4400{
4401 BlockDriver *drv;
4402
4403 assert(reopen_state != NULL);
4404 drv = reopen_state->bs->drv;
4405 assert(drv != NULL);
4406
4407 if (drv->bdrv_reopen_abort) {
4408 drv->bdrv_reopen_abort(reopen_state);
4409 }
4410}
4411
4412
Max Reitz64dff522016-01-29 16:36:10 +01004413static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00004414{
Max Reitz33384422014-06-20 21:57:33 +02004415 BdrvAioNotifier *ban, *ban_next;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004416 BdrvChild *child, *next;
Max Reitz33384422014-06-20 21:57:33 +02004417
Max Reitz30f55fb2016-05-17 16:41:32 +02004418 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03004419
Paolo Bonzinifc272912015-12-23 11:48:24 +01004420 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02004421 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004422 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01004423
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02004424 if (bs->drv) {
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004425 if (bs->drv->bdrv_close) {
Max Reitz7b99a262019-06-12 16:07:11 +02004426 /* Must unfreeze all children, so bdrv_unref_child() works */
Vladimir Sementsov-Ogievskiy3c005292018-08-14 15:43:19 +03004427 bs->drv->bdrv_close(bs);
4428 }
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004429 bs->drv = NULL;
bellardb3380822004-03-14 21:38:54 +00004430 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08004431
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004432 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Alberto Garciadd4118c2019-05-13 16:46:17 +03004433 bdrv_unref_child(bs, child);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004434 }
4435
Alberto Garciadd4118c2019-05-13 16:46:17 +03004436 bs->backing = NULL;
4437 bs->file = NULL;
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004438 g_free(bs->opaque);
4439 bs->opaque = NULL;
Stefan Hajnoczid73415a2020-09-23 11:56:46 +01004440 qatomic_set(&bs->copy_on_read, 0);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004441 bs->backing_file[0] = '\0';
4442 bs->backing_format[0] = '\0';
4443 bs->total_sectors = 0;
4444 bs->encrypted = false;
4445 bs->sg = false;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004446 qobject_unref(bs->options);
4447 qobject_unref(bs->explicit_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004448 bs->options = NULL;
4449 bs->explicit_options = NULL;
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02004450 qobject_unref(bs->full_open_options);
Alberto Garcia50a3efb2017-11-06 16:53:45 +02004451 bs->full_open_options = NULL;
4452
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03004453 bdrv_release_named_dirty_bitmaps(bs);
4454 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4455
Max Reitz33384422014-06-20 21:57:33 +02004456 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4457 g_free(ban);
4458 }
4459 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01004460 bdrv_drained_end(bs);
Greg Kurz1a6d3bd2020-10-23 17:01:10 +02004461
4462 /*
4463 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4464 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4465 * gets called.
4466 */
4467 if (bs->quiesce_counter) {
4468 bdrv_drain_all_end_quiesce(bs);
4469 }
bellardb3380822004-03-14 21:38:54 +00004470}
4471
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004472void bdrv_close_all(void)
4473{
Kevin Wolfb3b52992018-05-16 13:46:37 +02004474 assert(job_next(NULL) == NULL);
Kevin Wolfbc4ee652020-09-24 17:27:03 +02004475 blk_exp_close_all();
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004476
Max Reitzca9bd242016-01-29 16:36:14 +01004477 /* Drop references from requests still in flight, such as canceled block
4478 * jobs whose AIO context has not been polled yet */
4479 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004480
Max Reitzca9bd242016-01-29 16:36:14 +01004481 blk_remove_all_bs();
4482 blockdev_close_all_bdrv_states();
4483
Kevin Wolfa1a2af02016-04-08 18:26:37 +02004484 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09004485}
4486
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004487static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004488{
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004489 GQueue *queue;
4490 GHashTable *found;
4491 bool ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004492
Max Reitzbd86fb92020-05-13 13:05:13 +02004493 if (c->klass->stay_at_node) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004494 return false;
4495 }
4496
Max Reitzec9f10f2018-06-13 20:18:15 +02004497 /* If the child @c belongs to the BDS @to, replacing the current
4498 * c->bs by @to would mean to create a loop.
4499 *
4500 * Such a case occurs when appending a BDS to a backing chain.
4501 * For instance, imagine the following chain:
4502 *
4503 * guest device -> node A -> further backing chain...
4504 *
4505 * Now we create a new BDS B which we want to put on top of this
4506 * chain, so we first attach A as its backing node:
4507 *
4508 * node B
4509 * |
4510 * v
4511 * guest device -> node A -> further backing chain...
4512 *
4513 * Finally we want to replace A by B. When doing that, we want to
4514 * replace all pointers to A by pointers to B -- except for the
4515 * pointer from B because (1) that would create a loop, and (2)
4516 * that pointer should simply stay intact:
4517 *
4518 * guest device -> node B
4519 * |
4520 * v
4521 * node A -> further backing chain...
4522 *
4523 * In general, when replacing a node A (c->bs) by a node B (@to),
4524 * if A is a child of B, that means we cannot replace A by B there
4525 * because that would create a loop. Silently detaching A from B
4526 * is also not really an option. So overall just leaving A in
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004527 * place there is the most sensible choice.
4528 *
4529 * We would also create a loop in any cases where @c is only
4530 * indirectly referenced by @to. Prevent this by returning false
4531 * if @c is found (by breadth-first search) anywhere in the whole
4532 * subtree of @to.
4533 */
4534
4535 ret = true;
4536 found = g_hash_table_new(NULL, NULL);
4537 g_hash_table_add(found, to);
4538 queue = g_queue_new();
4539 g_queue_push_tail(queue, to);
4540
4541 while (!g_queue_is_empty(queue)) {
4542 BlockDriverState *v = g_queue_pop_head(queue);
4543 BdrvChild *c2;
4544
4545 QLIST_FOREACH(c2, &v->children, next) {
4546 if (c2 == c) {
4547 ret = false;
4548 break;
4549 }
4550
4551 if (g_hash_table_contains(found, c2->bs)) {
4552 continue;
4553 }
4554
4555 g_queue_push_tail(queue, c2->bs);
4556 g_hash_table_add(found, c2->bs);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004557 }
4558 }
4559
Vladimir Sementsov-Ogievskiy2f30b7c2019-02-23 22:20:39 +03004560 g_queue_free(queue);
4561 g_hash_table_destroy(found);
4562
4563 return ret;
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004564}
4565
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004566/*
4567 * With auto_skip=true bdrv_replace_node_common skips updating from parents
4568 * if it creates a parent-child relation loop or if parent is block-job.
4569 *
4570 * With auto_skip=false the error is returned if from has a parent which should
4571 * not be updated.
4572 */
4573static void bdrv_replace_node_common(BlockDriverState *from,
4574 BlockDriverState *to,
4575 bool auto_skip, Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004576{
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004577 BdrvChild *c, *next;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004578 GSList *list = NULL, *p;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004579 uint64_t perm = 0, shared = BLK_PERM_ALL;
4580 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004581
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004582 /* Make sure that @from doesn't go away until we have successfully attached
4583 * all of its parents to @to. */
4584 bdrv_ref(from);
4585
Kevin Wolff871abd2019-05-21 19:00:25 +02004586 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
Kevin Wolf30dd65f2020-03-10 12:38:29 +01004587 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
Kevin Wolff871abd2019-05-21 19:00:25 +02004588 bdrv_drained_begin(from);
4589
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004590 /* Put all parents into @list and calculate their cumulative permissions */
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004591 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
Max Reitzec9f10f2018-06-13 20:18:15 +02004592 assert(c->bs == from);
Kevin Wolfd0ac0382017-03-01 17:30:41 +01004593 if (!should_update_child(c, to)) {
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004594 if (auto_skip) {
4595 continue;
4596 }
4597 error_setg(errp, "Should not change '%s' link to '%s'",
4598 c->name, from->node_name);
4599 goto out;
Kevin Wolf26de9432017-01-17 13:39:34 +01004600 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004601 if (c->frozen) {
4602 error_setg(errp, "Cannot change '%s' link to '%s'",
4603 c->name, from->node_name);
4604 goto out;
4605 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004606 list = g_slist_prepend(list, c);
4607 perm |= c->perm;
4608 shared &= c->shared_perm;
4609 }
4610
4611 /* Check whether the required permissions can be granted on @to, ignoring
4612 * all BdrvChild in @list so that they can't block themselves. */
Max Reitz9eab1542019-05-22 19:03:50 +02004613 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004614 if (ret < 0) {
4615 bdrv_abort_perm_update(to);
4616 goto out;
4617 }
4618
4619 /* Now actually perform the change. We performed the permission check for
4620 * all elements of @list at once, so set the permissions all at once at the
4621 * very end. */
4622 for (p = list; p != NULL; p = p->next) {
4623 c = p->data;
Max Reitz9bd910e2016-06-10 20:57:46 +02004624
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004625 bdrv_ref(to);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004626 bdrv_replace_child_noperm(c, to);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004627 bdrv_unref(from);
4628 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004629
Vladimir Sementsov-Ogievskiyb503de62019-08-24 13:07:40 +03004630 bdrv_get_cumulative_perm(to, &perm, &shared);
4631 bdrv_set_perm(to, perm, shared);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004632
4633out:
4634 g_slist_free(list);
Kevin Wolff871abd2019-05-21 19:00:25 +02004635 bdrv_drained_end(from);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004636 bdrv_unref(from);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004637}
4638
Vladimir Sementsov-Ogievskiy313274b2020-11-06 15:42:36 +03004639void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4640 Error **errp)
4641{
4642 return bdrv_replace_node_common(from, to, true, errp);
4643}
4644
Jeff Cody8802d1f2012-02-28 15:54:06 -05004645/*
4646 * Add new bs contents at the top of an image chain while the chain is
4647 * live, while keeping required fields on the top layer.
4648 *
4649 * This will modify the BlockDriverState fields, and swap contents
4650 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4651 *
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02004652 * bs_new must not be attached to a BlockBackend.
Jeff Codyf6801b82012-03-27 16:30:19 -04004653 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05004654 * This function does not create any image files.
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004655 *
4656 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4657 * that's what the callers commonly need. bs_new will be referenced by the old
4658 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4659 * reference of its own, it must call bdrv_ref().
Jeff Cody8802d1f2012-02-28 15:54:06 -05004660 */
Kevin Wolfb2c28322017-02-20 12:46:42 +01004661void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4662 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05004663{
Kevin Wolfb2c28322017-02-20 12:46:42 +01004664 Error *local_err = NULL;
4665
Kevin Wolfb2c28322017-02-20 12:46:42 +01004666 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
4667 if (local_err) {
4668 error_propagate(errp, local_err);
4669 goto out;
4670 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004671
Kevin Wolf5fe31c22017-03-06 16:20:51 +01004672 bdrv_replace_node(bs_top, bs_new, &local_err);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01004673 if (local_err) {
4674 error_propagate(errp, local_err);
4675 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
4676 goto out;
4677 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004678
4679 /* bs_new is now referenced by its new parents, we don't need the
4680 * additional reference any more. */
Kevin Wolfb2c28322017-02-20 12:46:42 +01004681out:
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02004682 bdrv_unref(bs_new);
Jeff Cody8802d1f2012-02-28 15:54:06 -05004683}
4684
Fam Zheng4f6fd342013-08-23 09:14:47 +08004685static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00004686{
Fam Zheng3718d8a2014-05-23 21:29:43 +08004687 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08004688 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02004689
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01004690 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01004691 if (bs->node_name[0] != '\0') {
4692 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4693 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01004694 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4695
Anton Kuchin30c321f2019-05-07 11:12:56 +03004696 bdrv_close(bs);
4697
Anthony Liguori7267c092011-08-20 22:09:37 -05004698 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00004699}
4700
aliguorie97fc192009-04-21 23:11:50 +00004701/*
4702 * Run consistency checks on an image
4703 *
Kevin Wolfe076f332010-06-29 11:43:13 +02004704 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02004705 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02004706 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00004707 */
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03004708int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4709 BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00004710{
Max Reitz908bcd52014-08-07 22:47:55 +02004711 if (bs->drv == NULL) {
4712 return -ENOMEDIUM;
4713 }
Paolo Bonzini2fd61632018-03-01 17:36:19 +01004714 if (bs->drv->bdrv_co_check == NULL) {
aliguorie97fc192009-04-21 23:11:50 +00004715 return -ENOTSUP;
4716 }
4717
Kevin Wolfe076f332010-06-29 11:43:13 +02004718 memset(res, 0, sizeof(*res));
Paolo Bonzini2fd61632018-03-01 17:36:19 +01004719 return bs->drv->bdrv_co_check(bs, res, fix);
4720}
4721
Kevin Wolf756e6732010-01-12 12:55:17 +01004722/*
4723 * Return values:
4724 * 0 - success
4725 * -EINVAL - backing format specified, but no file
4726 * -ENOSPC - can't update the backing file because no space is left in the
4727 * image file header
4728 * -ENOTSUP - format driver doesn't support changing the backing file
4729 */
Eric Blakee54ee1b2020-07-06 15:39:53 -05004730int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
4731 const char *backing_fmt, bool warn)
Kevin Wolf756e6732010-01-12 12:55:17 +01004732{
4733 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02004734 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01004735
Max Reitzd470ad42017-11-10 21:31:09 +01004736 if (!drv) {
4737 return -ENOMEDIUM;
4738 }
4739
Paolo Bonzini5f377792012-04-12 14:01:01 +02004740 /* Backing file format doesn't make sense without a backing file */
4741 if (backing_fmt && !backing_file) {
4742 return -EINVAL;
4743 }
4744
Eric Blakee54ee1b2020-07-06 15:39:53 -05004745 if (warn && backing_file && !backing_fmt) {
4746 warn_report("Deprecated use of backing file without explicit "
4747 "backing format, use of this image requires "
4748 "potentially unsafe format probing");
4749 }
4750
Kevin Wolf756e6732010-01-12 12:55:17 +01004751 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02004752 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01004753 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02004754 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01004755 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02004756
4757 if (ret == 0) {
4758 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4759 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
Max Reitz998c2012019-02-01 20:29:08 +01004760 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4761 backing_file ?: "");
Paolo Bonzini469ef352012-04-12 14:01:02 +02004762 }
4763 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01004764}
4765
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004766/*
Max Reitzdcf3f9b2019-06-12 17:34:45 +02004767 * Finds the first non-filter node above bs in the chain between
4768 * active and bs. The returned node is either an immediate parent of
4769 * bs, or there are only filter nodes between the two.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004770 *
4771 * Returns NULL if bs is not found in active's image chain,
4772 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04004773 *
4774 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004775 */
4776BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4777 BlockDriverState *bs)
4778{
Max Reitzdcf3f9b2019-06-12 17:34:45 +02004779 bs = bdrv_skip_filters(bs);
4780 active = bdrv_skip_filters(active);
4781
4782 while (active) {
4783 BlockDriverState *next = bdrv_backing_chain_next(active);
4784 if (bs == next) {
4785 return active;
4786 }
4787 active = next;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004788 }
4789
Max Reitzdcf3f9b2019-06-12 17:34:45 +02004790 return NULL;
Jeff Cody4caf0fc2014-06-25 15:35:26 -04004791}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004792
Jeff Cody4caf0fc2014-06-25 15:35:26 -04004793/* Given a BDS, searches for the base layer. */
4794BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4795{
4796 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004797}
4798
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004799/*
Max Reitz7b99a262019-06-12 16:07:11 +02004800 * Return true if at least one of the COW (backing) and filter links
4801 * between @bs and @base is frozen. @errp is set if that's the case.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004802 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004803 */
4804bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4805 Error **errp)
4806{
4807 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02004808 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004809
Max Reitz7b99a262019-06-12 16:07:11 +02004810 for (i = bs; i != base; i = child_bs(child)) {
4811 child = bdrv_filter_or_cow_child(i);
4812
4813 if (child && child->frozen) {
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004814 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02004815 child->name, i->node_name, child->bs->node_name);
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004816 return true;
4817 }
4818 }
4819
4820 return false;
4821}
4822
4823/*
Max Reitz7b99a262019-06-12 16:07:11 +02004824 * Freeze all COW (backing) and filter links between @bs and @base.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004825 * If any of the links is already frozen the operation is aborted and
4826 * none of the links are modified.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004827 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004828 * Returns 0 on success. On failure returns < 0 and sets @errp.
4829 */
4830int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4831 Error **errp)
4832{
4833 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02004834 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004835
4836 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4837 return -EPERM;
4838 }
4839
Max Reitz7b99a262019-06-12 16:07:11 +02004840 for (i = bs; i != base; i = child_bs(child)) {
4841 child = bdrv_filter_or_cow_child(i);
4842 if (child && child->bs->never_freeze) {
Max Reitze5182c12019-07-03 19:28:02 +02004843 error_setg(errp, "Cannot freeze '%s' link to '%s'",
Max Reitz7b99a262019-06-12 16:07:11 +02004844 child->name, child->bs->node_name);
Max Reitze5182c12019-07-03 19:28:02 +02004845 return -EPERM;
4846 }
4847 }
4848
Max Reitz7b99a262019-06-12 16:07:11 +02004849 for (i = bs; i != base; i = child_bs(child)) {
4850 child = bdrv_filter_or_cow_child(i);
4851 if (child) {
4852 child->frozen = true;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004853 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004854 }
4855
4856 return 0;
4857}
4858
4859/*
Max Reitz7b99a262019-06-12 16:07:11 +02004860 * Unfreeze all COW (backing) and filter links between @bs and @base.
4861 * The caller must ensure that all links are frozen before using this
4862 * function.
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004863 * @base must be reachable from @bs, or NULL.
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004864 */
4865void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
4866{
4867 BlockDriverState *i;
Max Reitz7b99a262019-06-12 16:07:11 +02004868 BdrvChild *child;
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004869
Max Reitz7b99a262019-06-12 16:07:11 +02004870 for (i = bs; i != base; i = child_bs(child)) {
4871 child = bdrv_filter_or_cow_child(i);
4872 if (child) {
4873 assert(child->frozen);
4874 child->frozen = false;
Alberto Garcia0f0998f2019-03-28 18:25:09 +02004875 }
Alberto Garcia2cad1eb2019-03-12 18:48:40 +02004876 }
4877}
4878
4879/*
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004880 * Drops images above 'base' up to and including 'top', and sets the image
4881 * above 'top' to have base as its backing file.
4882 *
4883 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4884 * information in 'bs' can be properly updated.
4885 *
4886 * E.g., this will convert the following chain:
4887 * bottom <- base <- intermediate <- top <- active
4888 *
4889 * to
4890 *
4891 * bottom <- base <- active
4892 *
4893 * It is allowed for bottom==base, in which case it converts:
4894 *
4895 * base <- intermediate <- top <- active
4896 *
4897 * to
4898 *
4899 * base <- active
4900 *
Jeff Cody54e26902014-06-25 15:40:10 -04004901 * If backing_file_str is non-NULL, it will be used when modifying top's
4902 * overlay image metadata.
4903 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004904 * Error conditions:
4905 * if active == top, that is considered an error
4906 *
4907 */
Kevin Wolfbde70712017-06-27 20:36:18 +02004908int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
4909 const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004910{
Alberto Garcia6bd858b2018-10-31 18:16:38 +02004911 BlockDriverState *explicit_top = top;
4912 bool update_inherits_from;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03004913 BdrvChild *c;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01004914 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004915 int ret = -EIO;
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03004916 g_autoptr(GSList) updated_children = NULL;
4917 GSList *p;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004918
Kevin Wolf6858eba2017-06-29 19:32:21 +02004919 bdrv_ref(top);
Max Reitz637d54a2019-07-22 15:33:43 +02004920 bdrv_subtree_drained_begin(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02004921
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004922 if (!top->drv || !base->drv) {
4923 goto exit;
4924 }
4925
Kevin Wolf5db15a52015-09-14 15:33:33 +02004926 /* Make sure that base is in the backing chain of top */
4927 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004928 goto exit;
4929 }
4930
Alberto Garcia6bd858b2018-10-31 18:16:38 +02004931 /* If 'base' recursively inherits from 'top' then we should set
4932 * base->inherits_from to top->inherits_from after 'top' and all
4933 * other intermediate nodes have been dropped.
4934 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4935 * it because no one inherits from it. We use explicit_top for that. */
Max Reitzdcf3f9b2019-06-12 17:34:45 +02004936 explicit_top = bdrv_skip_implicit_filters(explicit_top);
Alberto Garcia6bd858b2018-10-31 18:16:38 +02004937 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
4938
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004939 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolfbde70712017-06-27 20:36:18 +02004940 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4941 * we've figured out how they should work. */
Max Reitzf30c66b2019-02-01 20:29:05 +01004942 if (!backing_file_str) {
4943 bdrv_refresh_filename(base);
4944 backing_file_str = base->filename;
4945 }
Kevin Wolf61f09ce2017-09-19 16:22:54 +02004946
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03004947 QLIST_FOREACH(c, &top->parents, next_parent) {
4948 updated_children = g_slist_prepend(updated_children, c);
4949 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01004950
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03004951 bdrv_replace_node_common(top, base, false, &local_err);
4952 if (local_err) {
4953 error_report_err(local_err);
4954 goto exit;
4955 }
4956
4957 for (p = updated_children; p; p = p->next) {
4958 c = p->data;
4959
Max Reitzbd86fb92020-05-13 13:05:13 +02004960 if (c->klass->update_filename) {
4961 ret = c->klass->update_filename(c, base, backing_file_str,
4962 &local_err);
Kevin Wolf61f09ce2017-09-19 16:22:54 +02004963 if (ret < 0) {
Vladimir Sementsov-Ogievskiyd669ed62020-11-06 15:42:37 +03004964 /*
4965 * TODO: Actually, we want to rollback all previous iterations
4966 * of this loop, and (which is almost impossible) previous
4967 * bdrv_replace_node()...
4968 *
4969 * Note, that c->klass->update_filename may lead to permission
4970 * update, so it's a bad idea to call it inside permission
4971 * update transaction of bdrv_replace_node.
4972 */
Kevin Wolf61f09ce2017-09-19 16:22:54 +02004973 error_report_err(local_err);
4974 goto exit;
4975 }
4976 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01004977 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004978
Alberto Garcia6bd858b2018-10-31 18:16:38 +02004979 if (update_inherits_from) {
4980 base->inherits_from = explicit_top->inherits_from;
4981 }
4982
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004983 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004984exit:
Max Reitz637d54a2019-07-22 15:33:43 +02004985 bdrv_subtree_drained_end(top);
Kevin Wolf6858eba2017-06-29 19:32:21 +02004986 bdrv_unref(top);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04004987 return ret;
4988}
4989
bellard83f64092006-08-01 16:21:11 +00004990/**
Max Reitz081e4652019-06-12 18:14:13 +02004991 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
4992 * sums the size of all data-bearing children. (This excludes backing
4993 * children.)
4994 */
4995static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
4996{
4997 BdrvChild *child;
4998 int64_t child_size, sum = 0;
4999
5000 QLIST_FOREACH(child, &bs->children, next) {
5001 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5002 BDRV_CHILD_FILTERED))
5003 {
5004 child_size = bdrv_get_allocated_file_size(child->bs);
5005 if (child_size < 0) {
5006 return child_size;
5007 }
5008 sum += child_size;
5009 }
5010 }
5011
5012 return sum;
5013}
5014
5015/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005016 * Length of a allocated file in bytes. Sparse files are counted by actual
5017 * allocated space. Return < 0 if error or unknown.
5018 */
5019int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5020{
5021 BlockDriver *drv = bs->drv;
5022 if (!drv) {
5023 return -ENOMEDIUM;
5024 }
5025 if (drv->bdrv_get_allocated_file_size) {
5026 return drv->bdrv_get_allocated_file_size(bs);
5027 }
Max Reitz081e4652019-06-12 18:14:13 +02005028
5029 if (drv->bdrv_file_open) {
5030 /*
5031 * Protocol drivers default to -ENOTSUP (most of their data is
5032 * not stored in any of their children (if they even have any),
5033 * so there is no generic way to figure it out).
5034 */
5035 return -ENOTSUP;
5036 } else if (drv->is_filter) {
5037 /* Filter drivers default to the size of their filtered child */
5038 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5039 } else {
5040 /* Other drivers default to summing their children's sizes */
5041 return bdrv_sum_allocated_file_size(bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005042 }
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005043}
5044
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01005045/*
5046 * bdrv_measure:
5047 * @drv: Format driver
5048 * @opts: Creation options for new image
5049 * @in_bs: Existing image containing data for new image (may be NULL)
5050 * @errp: Error object
5051 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5052 * or NULL on error
5053 *
5054 * Calculate file size required to create a new image.
5055 *
5056 * If @in_bs is given then space for allocated clusters and zero clusters
5057 * from that image are included in the calculation. If @opts contains a
5058 * backing file that is shared by @in_bs then backing clusters may be omitted
5059 * from the calculation.
5060 *
5061 * If @in_bs is NULL then the calculation includes no allocated clusters
5062 * unless a preallocation option is given in @opts.
5063 *
5064 * Note that @in_bs may use a different BlockDriver from @drv.
5065 *
5066 * If an error occurs the @errp pointer is set.
5067 */
5068BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5069 BlockDriverState *in_bs, Error **errp)
5070{
5071 if (!drv->bdrv_measure) {
5072 error_setg(errp, "Block driver '%s' does not support size measurement",
5073 drv->format_name);
5074 return NULL;
5075 }
5076
5077 return drv->bdrv_measure(opts, in_bs, errp);
5078}
5079
Fam Zheng4a1d5e12011-07-12 19:56:39 +08005080/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005081 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00005082 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005083int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00005084{
5085 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005086
bellard83f64092006-08-01 16:21:11 +00005087 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00005088 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01005089
Kevin Wolfb94a2612013-10-29 12:18:58 +01005090 if (drv->has_variable_length) {
5091 int ret = refresh_total_sectors(bs, bs->total_sectors);
5092 if (ret < 0) {
5093 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01005094 }
bellard83f64092006-08-01 16:21:11 +00005095 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005096 return bs->total_sectors;
5097}
5098
5099/**
5100 * Return length in bytes on success, -errno on error.
5101 * The length is always a multiple of BDRV_SECTOR_SIZE.
5102 */
5103int64_t bdrv_getlength(BlockDriverState *bs)
5104{
5105 int64_t ret = bdrv_nb_sectors(bs);
5106
Eric Blake122860b2020-11-05 09:51:22 -06005107 if (ret < 0) {
5108 return ret;
5109 }
5110 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5111 return -EFBIG;
5112 }
5113 return ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00005114}
5115
bellard19cb3732006-08-19 11:45:59 +00005116/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00005117void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00005118{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02005119 int64_t nb_sectors = bdrv_nb_sectors(bs);
5120
5121 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00005122}
bellardcf989512004-02-16 21:56:36 +00005123
Eric Blake54115412016-06-23 16:37:26 -06005124bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00005125{
5126 return bs->sg;
5127}
5128
Max Reitzae23f782019-06-12 22:57:15 +02005129/**
5130 * Return whether the given node supports compressed writes.
5131 */
5132bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5133{
5134 BlockDriverState *filtered;
5135
5136 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5137 return false;
5138 }
5139
5140 filtered = bdrv_filter_bs(bs);
5141 if (filtered) {
5142 /*
5143 * Filters can only forward compressed writes, so we have to
5144 * check the child.
5145 */
5146 return bdrv_supports_compressed_writes(filtered);
5147 }
5148
5149 return true;
5150}
5151
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005152const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005153{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02005154 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00005155}
5156
Stefan Hajnocziada42402014-08-27 12:08:55 +01005157static int qsort_strcmp(const void *a, const void *b)
5158{
Max Reitzceff5bd2016-10-12 22:49:05 +02005159 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01005160}
5161
ths5fafdf22007-09-16 21:08:06 +00005162void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005163 void *opaque, bool read_only)
bellardea2384d2004-08-01 21:59:26 +00005164{
5165 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04005166 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01005167 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04005168 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00005169
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01005170 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04005171 if (drv->format_name) {
5172 bool found = false;
5173 int i = count;
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005174
5175 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5176 continue;
5177 }
5178
Jeff Codye855e4f2014-04-28 18:29:54 -04005179 while (formats && i && !found) {
5180 found = !strcmp(formats[--i], drv->format_name);
5181 }
5182
5183 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02005184 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04005185 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04005186 }
5187 }
bellardea2384d2004-08-01 21:59:26 +00005188 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01005189
Max Reitzeb0df692016-10-12 22:49:06 +02005190 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5191 const char *format_name = block_driver_modules[i].format_name;
5192
5193 if (format_name) {
5194 bool found = false;
5195 int j = count;
5196
Andrey Shinkevich9ac404c2019-03-07 16:33:58 +03005197 if (use_bdrv_whitelist &&
5198 !bdrv_format_is_whitelisted(format_name, read_only)) {
5199 continue;
5200 }
5201
Max Reitzeb0df692016-10-12 22:49:06 +02005202 while (formats && j && !found) {
5203 found = !strcmp(formats[--j], format_name);
5204 }
5205
5206 if (!found) {
5207 formats = g_renew(const char *, formats, count + 1);
5208 formats[count++] = format_name;
5209 }
5210 }
5211 }
5212
Stefan Hajnocziada42402014-08-27 12:08:55 +01005213 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5214
5215 for (i = 0; i < count; i++) {
5216 it(opaque, formats[i]);
5217 }
5218
Jeff Codye855e4f2014-04-28 18:29:54 -04005219 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00005220}
5221
Benoît Canetdc364f42014-01-23 21:31:32 +01005222/* This function is to find a node in the bs graph */
5223BlockDriverState *bdrv_find_node(const char *node_name)
5224{
5225 BlockDriverState *bs;
5226
5227 assert(node_name);
5228
5229 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5230 if (!strcmp(node_name, bs->node_name)) {
5231 return bs;
5232 }
5233 }
5234 return NULL;
5235}
5236
Benoît Canetc13163f2014-01-23 21:31:34 +01005237/* Put this QMP function here so it can access the static graph_bdrv_states. */
Peter Krempafacda542020-01-20 09:50:49 +01005238BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5239 Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01005240{
Eric Blake9812e712020-10-27 00:05:47 -05005241 BlockDeviceInfoList *list;
Benoît Canetc13163f2014-01-23 21:31:34 +01005242 BlockDriverState *bs;
5243
5244 list = NULL;
5245 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Peter Krempafacda542020-01-20 09:50:49 +01005246 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03005247 if (!info) {
5248 qapi_free_BlockDeviceInfoList(list);
5249 return NULL;
5250 }
Eric Blake9812e712020-10-27 00:05:47 -05005251 QAPI_LIST_PREPEND(list, info);
Benoît Canetc13163f2014-01-23 21:31:34 +01005252 }
5253
5254 return list;
5255}
5256
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005257typedef struct XDbgBlockGraphConstructor {
5258 XDbgBlockGraph *graph;
5259 GHashTable *graph_nodes;
5260} XDbgBlockGraphConstructor;
5261
5262static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5263{
5264 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5265
5266 gr->graph = g_new0(XDbgBlockGraph, 1);
5267 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5268
5269 return gr;
5270}
5271
5272static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5273{
5274 XDbgBlockGraph *graph = gr->graph;
5275
5276 g_hash_table_destroy(gr->graph_nodes);
5277 g_free(gr);
5278
5279 return graph;
5280}
5281
5282static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5283{
5284 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5285
5286 if (ret != 0) {
5287 return ret;
5288 }
5289
5290 /*
5291 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5292 * answer of g_hash_table_lookup.
5293 */
5294 ret = g_hash_table_size(gr->graph_nodes) + 1;
5295 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5296
5297 return ret;
5298}
5299
5300static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5301 XDbgBlockGraphNodeType type, const char *name)
5302{
5303 XDbgBlockGraphNode *n;
5304
5305 n = g_new0(XDbgBlockGraphNode, 1);
5306
5307 n->id = xdbg_graph_node_num(gr, node);
5308 n->type = type;
5309 n->name = g_strdup(name);
5310
Eric Blake9812e712020-10-27 00:05:47 -05005311 QAPI_LIST_PREPEND(gr->graph->nodes, n);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005312}
5313
5314static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5315 const BdrvChild *child)
5316{
Max Reitzcdb1cec2019-11-08 13:34:52 +01005317 BlockPermission qapi_perm;
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005318 XDbgBlockGraphEdge *edge;
5319
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005320 edge = g_new0(XDbgBlockGraphEdge, 1);
5321
5322 edge->parent = xdbg_graph_node_num(gr, parent);
5323 edge->child = xdbg_graph_node_num(gr, child->bs);
5324 edge->name = g_strdup(child->name);
5325
Max Reitzcdb1cec2019-11-08 13:34:52 +01005326 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5327 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5328
5329 if (flag & child->perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005330 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005331 }
Max Reitzcdb1cec2019-11-08 13:34:52 +01005332 if (flag & child->shared_perm) {
Eric Blake9812e712020-10-27 00:05:47 -05005333 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005334 }
5335 }
5336
Eric Blake9812e712020-10-27 00:05:47 -05005337 QAPI_LIST_PREPEND(gr->graph->edges, edge);
Vladimir Sementsov-Ogievskiy5d3b4e92018-12-21 20:09:07 +03005338}
5339
5340
5341XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5342{
5343 BlockBackend *blk;
5344 BlockJob *job;
5345 BlockDriverState *bs;
5346 BdrvChild *child;
5347 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5348
5349 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5350 char *allocated_name = NULL;
5351 const char *name = blk_name(blk);
5352
5353 if (!*name) {
5354 name = allocated_name = blk_get_attached_dev_id(blk);
5355 }
5356 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5357 name);
5358 g_free(allocated_name);
5359 if (blk_root(blk)) {
5360 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5361 }
5362 }
5363
5364 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5365 GSList *el;
5366
5367 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5368 job->job.id);
5369 for (el = job->nodes; el; el = el->next) {
5370 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5371 }
5372 }
5373
5374 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5375 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5376 bs->node_name);
5377 QLIST_FOREACH(child, &bs->children, next) {
5378 xdbg_graph_add_edge(gr, bs, child);
5379 }
5380 }
5381
5382 return xdbg_graph_finalize(gr);
5383}
5384
Benoît Canet12d3ba82014-01-23 21:31:35 +01005385BlockDriverState *bdrv_lookup_bs(const char *device,
5386 const char *node_name,
5387 Error **errp)
5388{
Markus Armbruster7f06d472014-10-07 13:59:12 +02005389 BlockBackend *blk;
5390 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005391
Benoît Canet12d3ba82014-01-23 21:31:35 +01005392 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02005393 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005394
Markus Armbruster7f06d472014-10-07 13:59:12 +02005395 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005396 bs = blk_bs(blk);
5397 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02005398 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02005399 }
5400
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02005401 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005402 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005403 }
5404
Benoît Canetdd67fa52014-02-12 17:15:06 +01005405 if (node_name) {
5406 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01005407
Benoît Canetdd67fa52014-02-12 17:15:06 +01005408 if (bs) {
5409 return bs;
5410 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01005411 }
5412
Benoît Canetdd67fa52014-02-12 17:15:06 +01005413 error_setg(errp, "Cannot find device=%s nor node_name=%s",
5414 device ? device : "",
5415 node_name ? node_name : "");
5416 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01005417}
5418
Jeff Cody5a6684d2014-06-25 15:40:09 -04005419/* If 'base' is in the same chain as 'top', return true. Otherwise,
5420 * return false. If either argument is NULL, return false. */
5421bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5422{
5423 while (top && top != base) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005424 top = bdrv_filter_or_cow_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04005425 }
5426
5427 return top != NULL;
5428}
5429
Fam Zheng04df7652014-10-31 11:32:54 +08005430BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5431{
5432 if (!bs) {
5433 return QTAILQ_FIRST(&graph_bdrv_states);
5434 }
5435 return QTAILQ_NEXT(bs, node_list);
5436}
5437
Kevin Wolf0f122642018-03-28 18:29:18 +02005438BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5439{
5440 if (!bs) {
5441 return QTAILQ_FIRST(&all_bdrv_states);
5442 }
5443 return QTAILQ_NEXT(bs, bs_list);
5444}
5445
Fam Zheng20a9e772014-10-31 11:32:55 +08005446const char *bdrv_get_node_name(const BlockDriverState *bs)
5447{
5448 return bs->node_name;
5449}
5450
Kevin Wolf1f0c4612016-03-22 18:38:44 +01005451const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005452{
5453 BdrvChild *c;
5454 const char *name;
5455
5456 /* If multiple parents have a name, just pick the first one. */
5457 QLIST_FOREACH(c, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005458 if (c->klass->get_name) {
5459 name = c->klass->get_name(c);
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005460 if (name && *name) {
5461 return name;
5462 }
5463 }
5464 }
5465
5466 return NULL;
5467}
5468
Markus Armbruster7f06d472014-10-07 13:59:12 +02005469/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02005470const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00005471{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005472 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00005473}
5474
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005475/* This can be used to identify nodes that might not have a device
5476 * name associated. Since node and device names live in the same
5477 * namespace, the result is unambiguous. The exception is if both are
5478 * absent, then this returns an empty (non-null) string. */
5479const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5480{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01005481 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03005482}
5483
Markus Armbrusterc8433282012-06-05 16:49:24 +02005484int bdrv_get_flags(BlockDriverState *bs)
5485{
5486 return bs->open_flags;
5487}
5488
Peter Lieven3ac21622013-06-28 12:47:42 +02005489int bdrv_has_zero_init_1(BlockDriverState *bs)
5490{
5491 return 1;
5492}
5493
Kevin Wolff2feebb2010-04-14 17:30:35 +02005494int bdrv_has_zero_init(BlockDriverState *bs)
5495{
Max Reitz93393e62019-06-12 17:03:38 +02005496 BlockDriverState *filtered;
5497
Max Reitzd470ad42017-11-10 21:31:09 +01005498 if (!bs->drv) {
5499 return 0;
5500 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005501
Paolo Bonzini11212d82013-09-04 19:00:27 +02005502 /* If BS is a copy on write image, it is initialized to
5503 the contents of the base image, which may not be zeroes. */
Max Reitz34778172019-06-12 17:10:46 +02005504 if (bdrv_cow_child(bs)) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02005505 return 0;
5506 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02005507 if (bs->drv->bdrv_has_zero_init) {
5508 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02005509 }
Max Reitz93393e62019-06-12 17:03:38 +02005510
5511 filtered = bdrv_filter_bs(bs);
5512 if (filtered) {
5513 return bdrv_has_zero_init(filtered);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005514 }
Kevin Wolff2feebb2010-04-14 17:30:35 +02005515
Peter Lieven3ac21622013-06-28 12:47:42 +02005516 /* safe default */
5517 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02005518}
5519
Peter Lieven4ce78692013-10-24 12:06:54 +02005520bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5521{
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03005522 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02005523 return false;
5524 }
5525
Eric Blakee24d8132018-01-26 13:34:39 -06005526 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
Peter Lieven4ce78692013-10-24 12:06:54 +02005527}
5528
ths5fafdf22007-09-16 21:08:06 +00005529void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00005530 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00005531{
Kevin Wolf3574c602011-10-26 11:02:11 +02005532 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00005533}
5534
bellardfaea38e2006-08-05 21:31:00 +00005535int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5536{
5537 BlockDriver *drv = bs->drv;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005538 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5539 if (!drv) {
bellard19cb3732006-08-19 11:45:59 +00005540 return -ENOMEDIUM;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005541 }
5542 if (!drv->bdrv_get_info) {
Max Reitz93393e62019-06-12 17:03:38 +02005543 BlockDriverState *filtered = bdrv_filter_bs(bs);
5544 if (filtered) {
5545 return bdrv_get_info(filtered, bdi);
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005546 }
bellardfaea38e2006-08-05 21:31:00 +00005547 return -ENOTSUP;
Manos Pitsidianakis5a612c02017-07-13 18:30:25 +03005548 }
bellardfaea38e2006-08-05 21:31:00 +00005549 memset(bdi, 0, sizeof(*bdi));
5550 return drv->bdrv_get_info(bs, bdi);
5551}
5552
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005553ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5554 Error **errp)
Max Reitzeae041f2013-10-09 10:46:16 +02005555{
5556 BlockDriver *drv = bs->drv;
5557 if (drv && drv->bdrv_get_specific_info) {
Andrey Shinkevich1bf6e9c2019-02-08 18:06:06 +03005558 return drv->bdrv_get_specific_info(bs, errp);
Max Reitzeae041f2013-10-09 10:46:16 +02005559 }
5560 return NULL;
5561}
5562
Anton Nefedovd9245592019-09-23 15:17:37 +03005563BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5564{
5565 BlockDriver *drv = bs->drv;
5566 if (!drv || !drv->bdrv_get_specific_stats) {
5567 return NULL;
5568 }
5569 return drv->bdrv_get_specific_stats(bs);
5570}
5571
Eric Blakea31939e2015-11-18 01:52:54 -07005572void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005573{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005574 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005575 return;
5576 }
5577
Kevin Wolfbf736fe2013-06-05 15:17:55 +02005578 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005579}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005580
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005581static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
Kevin Wolf41c695c2012-12-06 14:32:58 +01005582{
5583 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Max Reitzf706a922019-06-12 17:42:13 +02005584 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005585 }
5586
5587 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005588 assert(bs->drv->bdrv_debug_remove_breakpoint);
5589 return bs;
5590 }
5591
5592 return NULL;
5593}
5594
5595int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5596 const char *tag)
5597{
5598 bs = bdrv_find_debug_node(bs);
5599 if (bs) {
Kevin Wolf41c695c2012-12-06 14:32:58 +01005600 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5601 }
5602
5603 return -ENOTSUP;
5604}
5605
Fam Zheng4cc70e92013-11-20 10:01:54 +08005606int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5607{
Vladimir Sementsov-Ogievskiyd10529a2019-09-20 17:20:49 +03005608 bs = bdrv_find_debug_node(bs);
5609 if (bs) {
Fam Zheng4cc70e92013-11-20 10:01:54 +08005610 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5611 }
5612
5613 return -ENOTSUP;
5614}
5615
Kevin Wolf41c695c2012-12-06 14:32:58 +01005616int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5617{
Max Reitz938789e2014-03-10 23:44:08 +01005618 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Max Reitzf706a922019-06-12 17:42:13 +02005619 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005620 }
5621
5622 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5623 return bs->drv->bdrv_debug_resume(bs, tag);
5624 }
5625
5626 return -ENOTSUP;
5627}
5628
5629bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5630{
5631 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Max Reitzf706a922019-06-12 17:42:13 +02005632 bs = bdrv_primary_bs(bs);
Kevin Wolf41c695c2012-12-06 14:32:58 +01005633 }
5634
5635 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5636 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5637 }
5638
5639 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01005640}
5641
Jeff Codyb1b1d782012-10-16 15:49:09 -04005642/* backing_file can either be relative, or absolute, or a protocol. If it is
5643 * relative, it must be relative to the chain. So, passing in bs->filename
5644 * from a BDS as backing_file should not be done, as that may be relative to
5645 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005646BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5647 const char *backing_file)
5648{
Jeff Codyb1b1d782012-10-16 15:49:09 -04005649 char *filename_full = NULL;
5650 char *backing_file_full = NULL;
5651 char *filename_tmp = NULL;
5652 int is_protocol = 0;
Max Reitz0b877d02018-08-01 20:34:11 +02005653 bool filenames_refreshed = false;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005654 BlockDriverState *curr_bs = NULL;
5655 BlockDriverState *retval = NULL;
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005656 BlockDriverState *bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005657
5658 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005659 return NULL;
5660 }
5661
Jeff Codyb1b1d782012-10-16 15:49:09 -04005662 filename_full = g_malloc(PATH_MAX);
5663 backing_file_full = g_malloc(PATH_MAX);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005664
5665 is_protocol = path_has_protocol(backing_file);
5666
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005667 /*
5668 * Being largely a legacy function, skip any filters here
5669 * (because filters do not have normal filenames, so they cannot
5670 * match anyway; and allowing json:{} filenames is a bit out of
5671 * scope).
5672 */
5673 for (curr_bs = bdrv_skip_filters(bs);
5674 bdrv_cow_child(curr_bs) != NULL;
5675 curr_bs = bs_below)
5676 {
5677 bs_below = bdrv_backing_chain_next(curr_bs);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005678
Max Reitz0b877d02018-08-01 20:34:11 +02005679 if (bdrv_backing_overridden(curr_bs)) {
5680 /*
5681 * If the backing file was overridden, we can only compare
5682 * directly against the backing node's filename.
5683 */
5684
5685 if (!filenames_refreshed) {
5686 /*
5687 * This will automatically refresh all of the
5688 * filenames in the rest of the backing chain, so we
5689 * only need to do this once.
5690 */
5691 bdrv_refresh_filename(bs_below);
5692 filenames_refreshed = true;
5693 }
5694
5695 if (strcmp(backing_file, bs_below->filename) == 0) {
5696 retval = bs_below;
5697 break;
5698 }
5699 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
5700 /*
5701 * If either of the filename paths is actually a protocol, then
5702 * compare unmodified paths; otherwise make paths relative.
5703 */
Max Reitz6b6833c2019-02-01 20:29:15 +01005704 char *backing_file_full_ret;
5705
Jeff Codyb1b1d782012-10-16 15:49:09 -04005706 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005707 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005708 break;
5709 }
Jeff Cody418661e2017-01-25 20:08:20 -05005710 /* Also check against the full backing filename for the image */
Max Reitz6b6833c2019-02-01 20:29:15 +01005711 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5712 NULL);
5713 if (backing_file_full_ret) {
5714 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5715 g_free(backing_file_full_ret);
5716 if (equal) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005717 retval = bs_below;
Jeff Cody418661e2017-01-25 20:08:20 -05005718 break;
5719 }
Jeff Cody418661e2017-01-25 20:08:20 -05005720 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005721 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04005722 /* If not an absolute filename path, make it relative to the current
5723 * image's filename path */
Max Reitz2d9158c2019-02-01 20:29:17 +01005724 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5725 NULL);
5726 /* We are going to compare canonicalized absolute pathnames */
5727 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5728 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005729 continue;
5730 }
Max Reitz2d9158c2019-02-01 20:29:17 +01005731 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005732
5733 /* We need to make sure the backing filename we are comparing against
5734 * is relative to the current image filename (or absolute) */
Max Reitz2d9158c2019-02-01 20:29:17 +01005735 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5736 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5737 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005738 continue;
5739 }
Max Reitz2d9158c2019-02-01 20:29:17 +01005740 g_free(filename_tmp);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005741
5742 if (strcmp(backing_file_full, filename_full) == 0) {
Max Reitzdcf3f9b2019-06-12 17:34:45 +02005743 retval = bs_below;
Jeff Codyb1b1d782012-10-16 15:49:09 -04005744 break;
5745 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005746 }
5747 }
5748
Jeff Codyb1b1d782012-10-16 15:49:09 -04005749 g_free(filename_full);
5750 g_free(backing_file_full);
Jeff Codyb1b1d782012-10-16 15:49:09 -04005751 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00005752}
5753
bellardea2384d2004-08-01 21:59:26 +00005754void bdrv_init(void)
5755{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05005756 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00005757}
pbrookce1a14d2006-08-07 02:38:06 +00005758
Markus Armbrustereb852012009-10-27 18:41:44 +01005759void bdrv_init_with_whitelist(void)
5760{
5761 use_bdrv_whitelist = 1;
5762 bdrv_init();
5763}
5764
Vladimir Sementsov-Ogievskiy21c22832020-09-24 21:54:10 +03005765int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06005766{
Kevin Wolf4417ab72017-05-04 18:52:37 +02005767 BdrvChild *child, *parent;
Kevin Wolf9c5e6592017-05-04 18:52:40 +02005768 uint64_t perm, shared_perm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005769 Error *local_err = NULL;
5770 int ret;
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04005771 BdrvDirtyBitmap *bm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005772
Kevin Wolf3456a8d2014-03-11 10:58:39 +01005773 if (!bs->drv) {
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005774 return -ENOMEDIUM;
Anthony Liguori0f154232011-11-14 15:09:45 -06005775 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01005776
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03005777 QLIST_FOREACH(child, &bs->children, next) {
Paolo Bonzini2b148f32018-03-01 17:36:18 +01005778 bdrv_co_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005779 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005780 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005781 return -EINVAL;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005782 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005783 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005784
Kevin Wolfdafe0962017-11-16 13:00:01 +01005785 /*
5786 * Update permissions, they may differ for inactive nodes.
5787 *
5788 * Note that the required permissions of inactive images are always a
5789 * subset of the permissions required after activating the image. This
5790 * allows us to just get the permissions upfront without restricting
5791 * drv->bdrv_invalidate_cache().
5792 *
5793 * It also means that in error cases, we don't have to try and revert to
5794 * the old permissions (which is an operation that could fail, too). We can
5795 * just keep the extended permissions for the next time that an activation
5796 * of the image is tried.
5797 */
Kevin Wolf7bb49412019-12-17 15:06:38 +01005798 if (bs->open_flags & BDRV_O_INACTIVE) {
5799 bs->open_flags &= ~BDRV_O_INACTIVE;
5800 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
Markus Armbruster668f62e2020-07-07 18:06:02 +02005801 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, errp);
Kevin Wolf7bb49412019-12-17 15:06:38 +01005802 if (ret < 0) {
Vladimir Sementsov-Ogievskiy6c5f7b32020-11-06 15:42:35 +03005803 bdrv_abort_perm_update(bs);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005804 bs->open_flags |= BDRV_O_INACTIVE;
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005805 return ret;
Fam Zheng0d1c5c92016-05-11 10:45:33 +08005806 }
Kevin Wolf7bb49412019-12-17 15:06:38 +01005807 bdrv_set_perm(bs, perm, shared_perm);
Kevin Wolf3456a8d2014-03-11 10:58:39 +01005808
Kevin Wolf7bb49412019-12-17 15:06:38 +01005809 if (bs->drv->bdrv_co_invalidate_cache) {
5810 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5811 if (local_err) {
5812 bs->open_flags |= BDRV_O_INACTIVE;
5813 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005814 return -EINVAL;
Kevin Wolf7bb49412019-12-17 15:06:38 +01005815 }
5816 }
Vladimir Sementsov-Ogievskiy9c98f142018-10-29 16:23:17 -04005817
Kevin Wolf7bb49412019-12-17 15:06:38 +01005818 FOR_EACH_DIRTY_BITMAP(bs, bm) {
5819 bdrv_dirty_bitmap_skip_store(bm, false);
5820 }
5821
5822 ret = refresh_total_sectors(bs, bs->total_sectors);
5823 if (ret < 0) {
5824 bs->open_flags |= BDRV_O_INACTIVE;
5825 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005826 return ret;
Kevin Wolf7bb49412019-12-17 15:06:38 +01005827 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005828 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02005829
5830 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005831 if (parent->klass->activate) {
5832 parent->klass->activate(parent, &local_err);
Kevin Wolf4417ab72017-05-04 18:52:37 +02005833 if (local_err) {
Kevin Wolf78fc3b32019-01-31 15:16:10 +01005834 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf4417ab72017-05-04 18:52:37 +02005835 error_propagate(errp, local_err);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005836 return -EINVAL;
Kevin Wolf4417ab72017-05-04 18:52:37 +02005837 }
5838 }
5839 }
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005840
5841 return 0;
Anthony Liguori0f154232011-11-14 15:09:45 -06005842}
5843
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005844void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06005845{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01005846 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02005847 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06005848
Kevin Wolf88be7b42016-05-20 18:49:07 +02005849 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02005850 AioContext *aio_context = bdrv_get_aio_context(bs);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005851 int ret;
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02005852
5853 aio_context_acquire(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005854 ret = bdrv_invalidate_cache(bs, errp);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02005855 aio_context_release(aio_context);
Vladimir Sementsov-Ogievskiy54166452020-09-24 21:54:08 +03005856 if (ret < 0) {
Max Reitz5e003f12017-11-10 18:25:45 +01005857 bdrv_next_cleanup(&it);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01005858 return;
5859 }
Anthony Liguori0f154232011-11-14 15:09:45 -06005860 }
5861}
5862
Kevin Wolf9e372712018-11-23 15:11:14 +01005863static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
5864{
5865 BdrvChild *parent;
5866
5867 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005868 if (parent->klass->parent_is_bds) {
Kevin Wolf9e372712018-11-23 15:11:14 +01005869 BlockDriverState *parent_bs = parent->opaque;
5870 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
5871 return true;
5872 }
5873 }
5874 }
5875
5876 return false;
5877}
5878
5879static int bdrv_inactivate_recurse(BlockDriverState *bs)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005880{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02005881 BdrvChild *child, *parent;
Max Reitz10467792019-05-22 19:03:51 +02005882 bool tighten_restrictions;
Kevin Wolf9e372712018-11-23 15:11:14 +01005883 uint64_t perm, shared_perm;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005884 int ret;
5885
Max Reitzd470ad42017-11-10 21:31:09 +01005886 if (!bs->drv) {
5887 return -ENOMEDIUM;
5888 }
5889
Kevin Wolf9e372712018-11-23 15:11:14 +01005890 /* Make sure that we don't inactivate a child before its parent.
5891 * It will be covered by recursion from the yet active parent. */
5892 if (bdrv_has_bds_parent(bs, true)) {
5893 return 0;
5894 }
5895
5896 assert(!(bs->open_flags & BDRV_O_INACTIVE));
5897
5898 /* Inactivate this node */
5899 if (bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005900 ret = bs->drv->bdrv_inactivate(bs);
5901 if (ret < 0) {
5902 return ret;
5903 }
5904 }
5905
Kevin Wolf9e372712018-11-23 15:11:14 +01005906 QLIST_FOREACH(parent, &bs->parents, next_parent) {
Max Reitzbd86fb92020-05-13 13:05:13 +02005907 if (parent->klass->inactivate) {
5908 ret = parent->klass->inactivate(parent);
Kevin Wolf9e372712018-11-23 15:11:14 +01005909 if (ret < 0) {
5910 return ret;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02005911 }
5912 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08005913 }
Kevin Wolf38701b62017-05-04 18:52:39 +02005914
Kevin Wolf9e372712018-11-23 15:11:14 +01005915 bs->open_flags |= BDRV_O_INACTIVE;
5916
5917 /* Update permissions, they may differ for inactive nodes */
5918 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
Max Reitz10467792019-05-22 19:03:51 +02005919 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
5920 &tighten_restrictions, NULL);
5921 assert(tighten_restrictions == false);
5922 if (ret < 0) {
5923 /* We only tried to loosen restrictions, so errors are not fatal */
5924 bdrv_abort_perm_update(bs);
5925 } else {
5926 bdrv_set_perm(bs, perm, shared_perm);
5927 }
Kevin Wolf9e372712018-11-23 15:11:14 +01005928
5929
5930 /* Recursively inactivate children */
Kevin Wolf38701b62017-05-04 18:52:39 +02005931 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf9e372712018-11-23 15:11:14 +01005932 ret = bdrv_inactivate_recurse(child->bs);
Kevin Wolf38701b62017-05-04 18:52:39 +02005933 if (ret < 0) {
5934 return ret;
5935 }
5936 }
5937
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005938 return 0;
5939}
5940
5941int bdrv_inactivate_all(void)
5942{
Max Reitz79720af2016-03-16 19:54:44 +01005943 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02005944 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08005945 int ret = 0;
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00005946 GSList *aio_ctxs = NULL, *ctx;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005947
Kevin Wolf88be7b42016-05-20 18:49:07 +02005948 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00005949 AioContext *aio_context = bdrv_get_aio_context(bs);
5950
5951 if (!g_slist_find(aio_ctxs, aio_context)) {
5952 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
5953 aio_context_acquire(aio_context);
5954 }
Fam Zhengaad0b7a2016-05-11 10:45:35 +08005955 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005956
Kevin Wolf9e372712018-11-23 15:11:14 +01005957 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5958 /* Nodes with BDS parents are covered by recursion from the last
5959 * parent that gets inactivated. Don't inactivate them a second
5960 * time if that has already happened. */
5961 if (bdrv_has_bds_parent(bs, false)) {
5962 continue;
5963 }
5964 ret = bdrv_inactivate_recurse(bs);
5965 if (ret < 0) {
5966 bdrv_next_cleanup(&it);
5967 goto out;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005968 }
5969 }
5970
Fam Zhengaad0b7a2016-05-11 10:45:35 +08005971out:
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00005972 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
5973 AioContext *aio_context = ctx->data;
5974 aio_context_release(aio_context);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08005975 }
Paolo Bonzinibd6458e2017-12-07 20:13:15 +00005976 g_slist_free(aio_ctxs);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08005977
5978 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01005979}
5980
Kevin Wolff9f05dc2011-07-15 13:50:26 +02005981/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00005982/* removable device support */
5983
5984/**
5985 * Return TRUE if the media is present
5986 */
Max Reitze031f752015-10-19 17:53:11 +02005987bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00005988{
5989 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02005990 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02005991
Max Reitze031f752015-10-19 17:53:11 +02005992 if (!drv) {
5993 return false;
5994 }
Max Reitz28d7a782015-10-19 17:53:13 +02005995 if (drv->bdrv_is_inserted) {
5996 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02005997 }
Max Reitz28d7a782015-10-19 17:53:13 +02005998 QLIST_FOREACH(child, &bs->children, next) {
5999 if (!bdrv_is_inserted(child->bs)) {
6000 return false;
6001 }
6002 }
6003 return true;
bellard19cb3732006-08-19 11:45:59 +00006004}
6005
6006/**
bellard19cb3732006-08-19 11:45:59 +00006007 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6008 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02006009void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00006010{
6011 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00006012
Markus Armbruster822e1cd2011-07-20 18:23:42 +02006013 if (drv && drv->bdrv_eject) {
6014 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00006015 }
bellard19cb3732006-08-19 11:45:59 +00006016}
6017
bellard19cb3732006-08-19 11:45:59 +00006018/**
6019 * Lock or unlock the media (if it is locked, the user won't be able
6020 * to eject it manually).
6021 */
Markus Armbruster025e8492011-09-06 18:58:47 +02006022void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00006023{
6024 BlockDriver *drv = bs->drv;
6025
Markus Armbruster025e8492011-09-06 18:58:47 +02006026 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01006027
Markus Armbruster025e8492011-09-06 18:58:47 +02006028 if (drv && drv->bdrv_lock_medium) {
6029 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00006030 }
6031}
ths985a03b2007-12-24 16:10:43 +00006032
Fam Zheng9fcb0252013-08-23 09:14:46 +08006033/* Get a reference to bs */
6034void bdrv_ref(BlockDriverState *bs)
6035{
6036 bs->refcnt++;
6037}
6038
6039/* Release a previously grabbed reference to bs.
6040 * If after releasing, reference count is zero, the BlockDriverState is
6041 * deleted. */
6042void bdrv_unref(BlockDriverState *bs)
6043{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04006044 if (!bs) {
6045 return;
6046 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08006047 assert(bs->refcnt > 0);
6048 if (--bs->refcnt == 0) {
6049 bdrv_delete(bs);
6050 }
6051}
6052
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006053struct BdrvOpBlocker {
6054 Error *reason;
6055 QLIST_ENTRY(BdrvOpBlocker) list;
6056};
6057
6058bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6059{
6060 BdrvOpBlocker *blocker;
6061 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6062 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6063 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Markus Armbruster4b576642018-10-17 10:26:25 +02006064 error_propagate_prepend(errp, error_copy(blocker->reason),
6065 "Node '%s' is busy: ",
6066 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006067 return true;
6068 }
6069 return false;
6070}
6071
6072void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6073{
6074 BdrvOpBlocker *blocker;
6075 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6076
Markus Armbruster5839e532014-08-19 10:31:08 +02006077 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08006078 blocker->reason = reason;
6079 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6080}
6081
6082void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6083{
6084 BdrvOpBlocker *blocker, *next;
6085 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6086 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6087 if (blocker->reason == reason) {
6088 QLIST_REMOVE(blocker, list);
6089 g_free(blocker);
6090 }
6091 }
6092}
6093
6094void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6095{
6096 int i;
6097 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6098 bdrv_op_block(bs, i, reason);
6099 }
6100}
6101
6102void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6103{
6104 int i;
6105 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6106 bdrv_op_unblock(bs, i, reason);
6107 }
6108}
6109
6110bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6111{
6112 int i;
6113
6114 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6115 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6116 return false;
6117 }
6118 }
6119 return true;
6120}
6121
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006122void bdrv_img_create(const char *filename, const char *fmt,
6123 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08006124 char *options, uint64_t img_size, int flags, bool quiet,
6125 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006126{
Chunyan Liu83d05212014-06-05 17:20:51 +08006127 QemuOptsList *create_opts = NULL;
6128 QemuOpts *opts = NULL;
6129 const char *backing_fmt, *backing_file;
6130 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006131 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02006132 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006133 int ret = 0;
6134
6135 /* Find driver and parse its options */
6136 drv = bdrv_find_format(fmt);
6137 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006138 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006139 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006140 }
6141
Max Reitzb65a5e12015-02-05 13:58:12 -05006142 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006143 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02006144 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006145 }
6146
Max Reitzc6149722014-12-02 18:32:45 +01006147 if (!drv->create_opts) {
6148 error_setg(errp, "Format driver '%s' does not support image creation",
6149 drv->format_name);
6150 return;
6151 }
6152
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006153 if (!proto_drv->create_opts) {
6154 error_setg(errp, "Protocol driver '%s' does not support image creation",
6155 proto_drv->format_name);
6156 return;
6157 }
6158
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006159 /* Create parameter list */
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006160 create_opts = qemu_opts_append(create_opts, drv->create_opts);
Maxim Levitsky5a5e7f82020-03-26 03:12:18 +02006161 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006162
Chunyan Liu83d05212014-06-05 17:20:51 +08006163 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006164
6165 /* Parse -o options */
6166 if (options) {
Markus Armbrustera5f9b9d2020-07-07 18:06:05 +02006167 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006168 goto out;
6169 }
6170 }
6171
Kevin Wolff6dc1c32019-11-26 16:45:49 +01006172 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6173 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6174 } else if (img_size != UINT64_C(-1)) {
6175 error_setg(errp, "The image size must be specified only once");
6176 goto out;
6177 }
6178
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006179 if (base_filename) {
Markus Armbruster235e59c2020-07-07 18:05:42 +02006180 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
Markus Armbruster38825782020-07-07 18:05:43 +02006181 NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006182 error_setg(errp, "Backing file not supported for file format '%s'",
6183 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006184 goto out;
6185 }
6186 }
6187
6188 if (base_fmt) {
Markus Armbruster38825782020-07-07 18:05:43 +02006189 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006190 error_setg(errp, "Backing file format not supported for file "
6191 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006192 goto out;
6193 }
6194 }
6195
Chunyan Liu83d05212014-06-05 17:20:51 +08006196 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6197 if (backing_file) {
6198 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02006199 error_setg(errp, "Error: Trying to create an image with the "
6200 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01006201 goto out;
6202 }
Connor Kuehl975a7bd2020-08-13 08:47:22 -05006203 if (backing_file[0] == '\0') {
6204 error_setg(errp, "Expected backing file name, got empty string");
6205 goto out;
6206 }
Jes Sorensen792da932010-12-16 13:52:17 +01006207 }
6208
Chunyan Liu83d05212014-06-05 17:20:51 +08006209 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006210
John Snow6e6e55f2017-07-17 20:34:22 -04006211 /* The size for the image must always be specified, unless we have a backing
6212 * file and we have not been forbidden from opening it. */
Eric Blakea8b42a12017-09-25 09:55:07 -05006213 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
John Snow6e6e55f2017-07-17 20:34:22 -04006214 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6215 BlockDriverState *bs;
Max Reitz645ae7d2019-02-01 20:29:14 +01006216 char *full_backing;
John Snow6e6e55f2017-07-17 20:34:22 -04006217 int back_flags;
6218 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02006219
Max Reitz645ae7d2019-02-01 20:29:14 +01006220 full_backing =
6221 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6222 &local_err);
John Snow6e6e55f2017-07-17 20:34:22 -04006223 if (local_err) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006224 goto out;
6225 }
Max Reitz645ae7d2019-02-01 20:29:14 +01006226 assert(full_backing);
John Snow6e6e55f2017-07-17 20:34:22 -04006227
6228 /* backing files always opened read-only */
6229 back_flags = flags;
6230 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6231
Fam Zhengcc954f02017-12-15 16:04:45 +08006232 backing_options = qdict_new();
John Snow6e6e55f2017-07-17 20:34:22 -04006233 if (backing_fmt) {
John Snow6e6e55f2017-07-17 20:34:22 -04006234 qdict_put_str(backing_options, "driver", backing_fmt);
6235 }
Fam Zhengcc954f02017-12-15 16:04:45 +08006236 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
John Snow6e6e55f2017-07-17 20:34:22 -04006237
6238 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6239 &local_err);
6240 g_free(full_backing);
Eric Blakeadd82002020-07-06 15:39:50 -05006241 if (!bs) {
6242 error_append_hint(&local_err, "Could not open backing image.\n");
John Snow6e6e55f2017-07-17 20:34:22 -04006243 goto out;
6244 } else {
Eric Blaked9f059a2020-07-06 15:39:54 -05006245 if (!backing_fmt) {
6246 warn_report("Deprecated use of backing file without explicit "
6247 "backing format (detected format of %s)",
6248 bs->drv->format_name);
6249 if (bs->drv != &bdrv_raw) {
6250 /*
6251 * A probe of raw deserves the most attention:
6252 * leaving the backing format out of the image
6253 * will ensure bs->probed is set (ensuring we
6254 * don't accidentally commit into the backing
6255 * file), and allow more spots to warn the users
6256 * to fix their toolchain when opening this image
6257 * later. For other images, we can safely record
6258 * the format that we probed.
6259 */
6260 backing_fmt = bs->drv->format_name;
6261 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
6262 NULL);
6263 }
6264 }
John Snow6e6e55f2017-07-17 20:34:22 -04006265 if (size == -1) {
6266 /* Opened BS, have no size */
6267 size = bdrv_getlength(bs);
6268 if (size < 0) {
6269 error_setg_errno(errp, -size, "Could not get size of '%s'",
6270 backing_file);
6271 bdrv_unref(bs);
6272 goto out;
6273 }
6274 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6275 }
6276 bdrv_unref(bs);
6277 }
Eric Blaked9f059a2020-07-06 15:39:54 -05006278 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6279 } else if (backing_file && !backing_fmt) {
6280 warn_report("Deprecated use of unopened backing file without "
6281 "explicit backing format, use of this image requires "
6282 "potentially unsafe format probing");
6283 }
John Snow6e6e55f2017-07-17 20:34:22 -04006284
6285 if (size == -1) {
6286 error_setg(errp, "Image creation needs a size parameter");
6287 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006288 }
6289
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006290 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02006291 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08006292 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006293 puts("");
Eric Blake4e2f4412020-07-06 15:39:45 -05006294 fflush(stdout);
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01006295 }
Chunyan Liu83d05212014-06-05 17:20:51 +08006296
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006297 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08006298
Max Reitzcc84d902013-09-06 17:14:26 +02006299 if (ret == -EFBIG) {
6300 /* This is generally a better message than whatever the driver would
6301 * deliver (especially because of the cluster_size_hint), since that
6302 * is most probably not much different from "image too large". */
6303 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08006304 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02006305 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006306 }
Max Reitzcc84d902013-09-06 17:14:26 +02006307 error_setg(errp, "The image size is too large for file format '%s'"
6308 "%s", fmt, cluster_size_hint);
6309 error_free(local_err);
6310 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006311 }
6312
6313out:
Chunyan Liu83d05212014-06-05 17:20:51 +08006314 qemu_opts_del(opts);
6315 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03006316 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01006317}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006318
6319AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6320{
Stefan Hajnoczi33f2a752018-02-16 16:50:13 +00006321 return bs ? bs->aio_context : qemu_get_aio_context();
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006322}
6323
Kevin Wolfe336fd42020-10-05 17:58:53 +02006324AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
6325{
6326 Coroutine *self = qemu_coroutine_self();
6327 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
6328 AioContext *new_ctx;
6329
6330 /*
6331 * Increase bs->in_flight to ensure that this operation is completed before
6332 * moving the node to a different AioContext. Read new_ctx only afterwards.
6333 */
6334 bdrv_inc_in_flight(bs);
6335
6336 new_ctx = bdrv_get_aio_context(bs);
6337 aio_co_reschedule_self(new_ctx);
6338 return old_ctx;
6339}
6340
6341void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
6342{
6343 aio_co_reschedule_self(old_ctx);
6344 bdrv_dec_in_flight(bs);
6345}
6346
Kevin Wolf18c6ac12020-10-05 17:58:54 +02006347void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
6348{
6349 AioContext *ctx = bdrv_get_aio_context(bs);
6350
6351 /* In the main thread, bs->aio_context won't change concurrently */
6352 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6353
6354 /*
6355 * We're in coroutine context, so we already hold the lock of the main
6356 * loop AioContext. Don't lock it twice to avoid deadlocks.
6357 */
6358 assert(qemu_in_coroutine());
6359 if (ctx != qemu_get_aio_context()) {
6360 aio_context_acquire(ctx);
6361 }
6362}
6363
6364void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
6365{
6366 AioContext *ctx = bdrv_get_aio_context(bs);
6367
6368 assert(qemu_in_coroutine());
6369 if (ctx != qemu_get_aio_context()) {
6370 aio_context_release(ctx);
6371 }
6372}
6373
Fam Zheng052a7572017-04-10 20:09:25 +08006374void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6375{
6376 aio_co_enter(bdrv_get_aio_context(bs), co);
6377}
6378
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006379static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6380{
6381 QLIST_REMOVE(ban, list);
6382 g_free(ban);
6383}
6384
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006385static void bdrv_detach_aio_context(BlockDriverState *bs)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006386{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006387 BdrvAioNotifier *baf, *baf_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006388
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006389 assert(!bs->walking_aio_notifiers);
6390 bs->walking_aio_notifiers = true;
6391 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6392 if (baf->deleted) {
6393 bdrv_do_remove_aio_context_notifier(baf);
6394 } else {
6395 baf->detach_aio_context(baf->opaque);
6396 }
Max Reitz33384422014-06-20 21:57:33 +02006397 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006398 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6399 * remove remaining aio notifiers if we aren't called again.
6400 */
6401 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02006402
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006403 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006404 bs->drv->bdrv_detach_aio_context(bs);
6405 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006406
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006407 if (bs->quiesce_counter) {
6408 aio_enable_external(bs->aio_context);
6409 }
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006410 bs->aio_context = NULL;
6411}
6412
Kevin Wolfa3a683c2019-05-06 19:17:57 +02006413static void bdrv_attach_aio_context(BlockDriverState *bs,
6414 AioContext *new_context)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006415{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006416 BdrvAioNotifier *ban, *ban_tmp;
Max Reitz33384422014-06-20 21:57:33 +02006417
Kevin Wolfe64f25f2019-02-08 16:51:17 +01006418 if (bs->quiesce_counter) {
6419 aio_disable_external(new_context);
6420 }
6421
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006422 bs->aio_context = new_context;
6423
Kevin Wolf1bffe1a2019-04-17 17:15:25 +02006424 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006425 bs->drv->bdrv_attach_aio_context(bs, new_context);
6426 }
Max Reitz33384422014-06-20 21:57:33 +02006427
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006428 assert(!bs->walking_aio_notifiers);
6429 bs->walking_aio_notifiers = true;
6430 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6431 if (ban->deleted) {
6432 bdrv_do_remove_aio_context_notifier(ban);
6433 } else {
6434 ban->attached_aio_context(new_context, ban->opaque);
6435 }
Max Reitz33384422014-06-20 21:57:33 +02006436 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006437 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006438}
6439
Kevin Wolf42a65f02019-05-07 18:31:38 +02006440/*
6441 * Changes the AioContext used for fd handlers, timers, and BHs by this
6442 * BlockDriverState and all its children and parents.
6443 *
Max Reitz43eaaae2019-07-22 15:30:54 +02006444 * Must be called from the main AioContext.
6445 *
Kevin Wolf42a65f02019-05-07 18:31:38 +02006446 * The caller must own the AioContext lock for the old AioContext of bs, but it
6447 * must not own the AioContext lock for new_context (unless new_context is the
6448 * same as the current context of bs).
6449 *
6450 * @ignore will accumulate all visited BdrvChild object. The caller is
6451 * responsible for freeing the list afterwards.
6452 */
Kevin Wolf53a7d042019-05-06 19:17:59 +02006453void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6454 AioContext *new_context, GSList **ignore)
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006455{
Max Reitze037c092019-07-19 11:26:14 +02006456 AioContext *old_context = bdrv_get_aio_context(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02006457 BdrvChild *child;
6458
Max Reitz43eaaae2019-07-22 15:30:54 +02006459 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6460
Max Reitze037c092019-07-19 11:26:14 +02006461 if (old_context == new_context) {
Denis Plotnikov57830a42019-02-15 16:03:25 +03006462 return;
6463 }
6464
Kevin Wolfd70d5952019-02-08 16:53:37 +01006465 bdrv_drained_begin(bs);
Kevin Wolf0d837082019-05-06 19:17:58 +02006466
6467 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf53a7d042019-05-06 19:17:59 +02006468 if (g_slist_find(*ignore, child)) {
6469 continue;
6470 }
6471 *ignore = g_slist_prepend(*ignore, child);
6472 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6473 }
6474 QLIST_FOREACH(child, &bs->parents, next_parent) {
6475 if (g_slist_find(*ignore, child)) {
6476 continue;
6477 }
Max Reitzbd86fb92020-05-13 13:05:13 +02006478 assert(child->klass->set_aio_ctx);
Kevin Wolf42a65f02019-05-07 18:31:38 +02006479 *ignore = g_slist_prepend(*ignore, child);
Max Reitzbd86fb92020-05-13 13:05:13 +02006480 child->klass->set_aio_ctx(child, new_context, ignore);
Kevin Wolf0d837082019-05-06 19:17:58 +02006481 }
6482
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006483 bdrv_detach_aio_context(bs);
6484
Max Reitze037c092019-07-19 11:26:14 +02006485 /* Acquire the new context, if necessary */
Max Reitz43eaaae2019-07-22 15:30:54 +02006486 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006487 aio_context_acquire(new_context);
6488 }
6489
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02006490 bdrv_attach_aio_context(bs, new_context);
Max Reitze037c092019-07-19 11:26:14 +02006491
6492 /*
6493 * If this function was recursively called from
6494 * bdrv_set_aio_context_ignore(), there may be nodes in the
6495 * subtree that have not yet been moved to the new AioContext.
6496 * Release the old one so bdrv_drained_end() can poll them.
6497 */
Max Reitz43eaaae2019-07-22 15:30:54 +02006498 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006499 aio_context_release(old_context);
6500 }
6501
Kevin Wolfd70d5952019-02-08 16:53:37 +01006502 bdrv_drained_end(bs);
Max Reitze037c092019-07-19 11:26:14 +02006503
Max Reitz43eaaae2019-07-22 15:30:54 +02006504 if (qemu_get_aio_context() != old_context) {
Max Reitze037c092019-07-19 11:26:14 +02006505 aio_context_acquire(old_context);
6506 }
Max Reitz43eaaae2019-07-22 15:30:54 +02006507 if (qemu_get_aio_context() != new_context) {
Max Reitze037c092019-07-19 11:26:14 +02006508 aio_context_release(new_context);
6509 }
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01006510}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02006511
Kevin Wolf5d231842019-05-06 19:17:56 +02006512static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6513 GSList **ignore, Error **errp)
6514{
6515 if (g_slist_find(*ignore, c)) {
6516 return true;
6517 }
6518 *ignore = g_slist_prepend(*ignore, c);
6519
Max Reitzbd86fb92020-05-13 13:05:13 +02006520 /*
6521 * A BdrvChildClass that doesn't handle AioContext changes cannot
6522 * tolerate any AioContext changes
6523 */
6524 if (!c->klass->can_set_aio_ctx) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006525 char *user = bdrv_child_user_desc(c);
6526 error_setg(errp, "Changing iothreads is not supported by %s", user);
6527 g_free(user);
6528 return false;
6529 }
Max Reitzbd86fb92020-05-13 13:05:13 +02006530 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
Kevin Wolf5d231842019-05-06 19:17:56 +02006531 assert(!errp || *errp);
6532 return false;
6533 }
6534 return true;
6535}
6536
6537bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6538 GSList **ignore, Error **errp)
6539{
6540 if (g_slist_find(*ignore, c)) {
6541 return true;
6542 }
6543 *ignore = g_slist_prepend(*ignore, c);
6544 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6545}
6546
6547/* @ignore will accumulate all visited BdrvChild object. The caller is
6548 * responsible for freeing the list afterwards. */
6549bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6550 GSList **ignore, Error **errp)
6551{
6552 BdrvChild *c;
6553
6554 if (bdrv_get_aio_context(bs) == ctx) {
6555 return true;
6556 }
6557
6558 QLIST_FOREACH(c, &bs->parents, next_parent) {
6559 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6560 return false;
6561 }
6562 }
6563 QLIST_FOREACH(c, &bs->children, next) {
6564 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6565 return false;
6566 }
6567 }
6568
6569 return true;
6570}
6571
6572int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6573 BdrvChild *ignore_child, Error **errp)
6574{
6575 GSList *ignore;
6576 bool ret;
6577
6578 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6579 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6580 g_slist_free(ignore);
6581
6582 if (!ret) {
6583 return -EPERM;
6584 }
6585
Kevin Wolf53a7d042019-05-06 19:17:59 +02006586 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6587 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6588 g_slist_free(ignore);
6589
Kevin Wolf5d231842019-05-06 19:17:56 +02006590 return 0;
6591}
6592
6593int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6594 Error **errp)
6595{
6596 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6597}
6598
Max Reitz33384422014-06-20 21:57:33 +02006599void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6600 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6601 void (*detach_aio_context)(void *opaque), void *opaque)
6602{
6603 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6604 *ban = (BdrvAioNotifier){
6605 .attached_aio_context = attached_aio_context,
6606 .detach_aio_context = detach_aio_context,
6607 .opaque = opaque
6608 };
6609
6610 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6611}
6612
6613void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6614 void (*attached_aio_context)(AioContext *,
6615 void *),
6616 void (*detach_aio_context)(void *),
6617 void *opaque)
6618{
6619 BdrvAioNotifier *ban, *ban_next;
6620
6621 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6622 if (ban->attached_aio_context == attached_aio_context &&
6623 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006624 ban->opaque == opaque &&
6625 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02006626 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01006627 if (bs->walking_aio_notifiers) {
6628 ban->deleted = true;
6629 } else {
6630 bdrv_do_remove_aio_context_notifier(ban);
6631 }
Max Reitz33384422014-06-20 21:57:33 +02006632 return;
6633 }
6634 }
6635
6636 abort();
6637}
6638
Max Reitz77485432014-10-27 11:12:50 +01006639int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitzd1402b52018-05-09 23:00:18 +02006640 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
Maxim Levitskya3579bf2020-06-25 14:55:38 +02006641 bool force,
Max Reitzd1402b52018-05-09 23:00:18 +02006642 Error **errp)
Max Reitz6f176b42013-09-03 10:09:50 +02006643{
Max Reitzd470ad42017-11-10 21:31:09 +01006644 if (!bs->drv) {
Max Reitzd1402b52018-05-09 23:00:18 +02006645 error_setg(errp, "Node is ejected");
Max Reitzd470ad42017-11-10 21:31:09 +01006646 return -ENOMEDIUM;
6647 }
Chunyan Liuc282e1f2014-06-05 17:21:11 +08006648 if (!bs->drv->bdrv_amend_options) {
Max Reitzd1402b52018-05-09 23:00:18 +02006649 error_setg(errp, "Block driver '%s' does not support option amendment",
6650 bs->drv->format_name);
Max Reitz6f176b42013-09-03 10:09:50 +02006651 return -ENOTSUP;
6652 }
Maxim Levitskya3579bf2020-06-25 14:55:38 +02006653 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
6654 cb_opaque, force, errp);
Max Reitz6f176b42013-09-03 10:09:50 +02006655}
Benoît Canetf6186f42013-10-02 14:33:48 +02006656
Max Reitz5d69b5a2020-02-18 11:34:41 +01006657/*
6658 * This function checks whether the given @to_replace is allowed to be
6659 * replaced by a node that always shows the same data as @bs. This is
6660 * used for example to verify whether the mirror job can replace
6661 * @to_replace by the target mirrored from @bs.
6662 * To be replaceable, @bs and @to_replace may either be guaranteed to
6663 * always show the same data (because they are only connected through
6664 * filters), or some driver may allow replacing one of its children
6665 * because it can guarantee that this child's data is not visible at
6666 * all (for example, for dissenting quorum children that have no other
6667 * parents).
6668 */
6669bool bdrv_recurse_can_replace(BlockDriverState *bs,
6670 BlockDriverState *to_replace)
6671{
Max Reitz93393e62019-06-12 17:03:38 +02006672 BlockDriverState *filtered;
6673
Max Reitz5d69b5a2020-02-18 11:34:41 +01006674 if (!bs || !bs->drv) {
6675 return false;
6676 }
6677
6678 if (bs == to_replace) {
6679 return true;
6680 }
6681
6682 /* See what the driver can do */
6683 if (bs->drv->bdrv_recurse_can_replace) {
6684 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
6685 }
6686
6687 /* For filters without an own implementation, we can recurse on our own */
Max Reitz93393e62019-06-12 17:03:38 +02006688 filtered = bdrv_filter_bs(bs);
6689 if (filtered) {
6690 return bdrv_recurse_can_replace(filtered, to_replace);
Max Reitz5d69b5a2020-02-18 11:34:41 +01006691 }
6692
6693 /* Safe default */
6694 return false;
6695}
6696
Max Reitz810803a2020-02-18 11:34:44 +01006697/*
6698 * Check whether the given @node_name can be replaced by a node that
6699 * has the same data as @parent_bs. If so, return @node_name's BDS;
6700 * NULL otherwise.
6701 *
6702 * @node_name must be a (recursive) *child of @parent_bs (or this
6703 * function will return NULL).
6704 *
6705 * The result (whether the node can be replaced or not) is only valid
6706 * for as long as no graph or permission changes occur.
6707 */
Wen Congyange12f3782015-07-17 10:12:22 +08006708BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6709 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02006710{
6711 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006712 AioContext *aio_context;
6713
Benoît Canet09158f02014-06-27 18:25:25 +02006714 if (!to_replace_bs) {
6715 error_setg(errp, "Node name '%s' not found", node_name);
6716 return NULL;
6717 }
6718
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006719 aio_context = bdrv_get_aio_context(to_replace_bs);
6720 aio_context_acquire(aio_context);
6721
Benoît Canet09158f02014-06-27 18:25:25 +02006722 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006723 to_replace_bs = NULL;
6724 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02006725 }
6726
6727 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6728 * most non filter in order to prevent data corruption.
6729 * Another benefit is that this tests exclude backing files which are
6730 * blocked by the backing blockers.
6731 */
Max Reitz810803a2020-02-18 11:34:44 +01006732 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
6733 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
6734 "because it cannot be guaranteed that doing so would not "
6735 "lead to an abrupt change of visible data",
6736 node_name, parent_bs->node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006737 to_replace_bs = NULL;
6738 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02006739 }
6740
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01006741out:
6742 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02006743 return to_replace_bs;
6744}
Ming Lei448ad912014-07-04 18:04:33 +08006745
Max Reitz97e2f022019-02-01 20:29:27 +01006746/**
6747 * Iterates through the list of runtime option keys that are said to
6748 * be "strong" for a BDS. An option is called "strong" if it changes
6749 * a BDS's data. For example, the null block driver's "size" and
6750 * "read-zeroes" options are strong, but its "latency-ns" option is
6751 * not.
6752 *
6753 * If a key returned by this function ends with a dot, all options
6754 * starting with that prefix are strong.
6755 */
6756static const char *const *strong_options(BlockDriverState *bs,
6757 const char *const *curopt)
6758{
6759 static const char *const global_options[] = {
6760 "driver", "filename", NULL
6761 };
6762
6763 if (!curopt) {
6764 return &global_options[0];
6765 }
6766
6767 curopt++;
6768 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6769 curopt = bs->drv->strong_runtime_opts;
6770 }
6771
6772 return (curopt && *curopt) ? curopt : NULL;
6773}
6774
6775/**
6776 * Copies all strong runtime options from bs->options to the given
6777 * QDict. The set of strong option keys is determined by invoking
6778 * strong_options().
6779 *
6780 * Returns true iff any strong option was present in bs->options (and
6781 * thus copied to the target QDict) with the exception of "filename"
6782 * and "driver". The caller is expected to use this value to decide
6783 * whether the existence of strong options prevents the generation of
6784 * a plain filename.
6785 */
6786static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6787{
6788 bool found_any = false;
6789 const char *const *option_name = NULL;
6790
6791 if (!bs->drv) {
6792 return false;
6793 }
6794
6795 while ((option_name = strong_options(bs, option_name))) {
6796 bool option_given = false;
6797
6798 assert(strlen(*option_name) > 0);
6799 if ((*option_name)[strlen(*option_name) - 1] != '.') {
6800 QObject *entry = qdict_get(bs->options, *option_name);
6801 if (!entry) {
6802 continue;
6803 }
6804
6805 qdict_put_obj(d, *option_name, qobject_ref(entry));
6806 option_given = true;
6807 } else {
6808 const QDictEntry *entry;
6809 for (entry = qdict_first(bs->options); entry;
6810 entry = qdict_next(bs->options, entry))
6811 {
6812 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6813 qdict_put_obj(d, qdict_entry_key(entry),
6814 qobject_ref(qdict_entry_value(entry)));
6815 option_given = true;
6816 }
6817 }
6818 }
6819
6820 /* While "driver" and "filename" need to be included in a JSON filename,
6821 * their existence does not prohibit generation of a plain filename. */
6822 if (!found_any && option_given &&
6823 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6824 {
6825 found_any = true;
6826 }
6827 }
6828
Max Reitz62a01a272019-02-01 20:29:34 +01006829 if (!qdict_haskey(d, "driver")) {
6830 /* Drivers created with bdrv_new_open_driver() may not have a
6831 * @driver option. Add it here. */
6832 qdict_put_str(d, "driver", bs->drv->format_name);
6833 }
6834
Max Reitz97e2f022019-02-01 20:29:27 +01006835 return found_any;
6836}
6837
Max Reitz90993622019-02-01 20:29:09 +01006838/* Note: This function may return false positives; it may return true
6839 * even if opening the backing file specified by bs's image header
6840 * would result in exactly bs->backing. */
Max Reitz0b877d02018-08-01 20:34:11 +02006841bool bdrv_backing_overridden(BlockDriverState *bs)
Max Reitz90993622019-02-01 20:29:09 +01006842{
6843 if (bs->backing) {
6844 return strcmp(bs->auto_backing_file,
6845 bs->backing->bs->filename);
6846 } else {
6847 /* No backing BDS, so if the image header reports any backing
6848 * file, it must have been suppressed */
6849 return bs->auto_backing_file[0] != '\0';
6850 }
6851}
6852
Max Reitz91af7012014-07-18 20:24:56 +02006853/* Updates the following BDS fields:
6854 * - exact_filename: A filename which may be used for opening a block device
6855 * which (mostly) equals the given BDS (even without any
6856 * other options; so reading and writing must return the same
6857 * results, but caching etc. may be different)
6858 * - full_open_options: Options which, when given when opening a block device
6859 * (without a filename), result in a BDS (mostly)
6860 * equalling the given one
6861 * - filename: If exact_filename is set, it is copied here. Otherwise,
6862 * full_open_options is converted to a JSON object, prefixed with
6863 * "json:" (for use through the JSON pseudo protocol) and put here.
6864 */
6865void bdrv_refresh_filename(BlockDriverState *bs)
6866{
6867 BlockDriver *drv = bs->drv;
Max Reitze24518e2019-02-01 20:29:06 +01006868 BdrvChild *child;
Max Reitz52f72d62019-06-12 17:43:03 +02006869 BlockDriverState *primary_child_bs;
Max Reitz91af7012014-07-18 20:24:56 +02006870 QDict *opts;
Max Reitz90993622019-02-01 20:29:09 +01006871 bool backing_overridden;
Max Reitz998b3a12019-02-01 20:29:28 +01006872 bool generate_json_filename; /* Whether our default implementation should
6873 fill exact_filename (false) or not (true) */
Max Reitz91af7012014-07-18 20:24:56 +02006874
6875 if (!drv) {
6876 return;
6877 }
6878
Max Reitze24518e2019-02-01 20:29:06 +01006879 /* This BDS's file name may depend on any of its children's file names, so
6880 * refresh those first */
6881 QLIST_FOREACH(child, &bs->children, next) {
6882 bdrv_refresh_filename(child->bs);
Max Reitz91af7012014-07-18 20:24:56 +02006883 }
6884
Max Reitzbb808d52019-02-01 20:29:07 +01006885 if (bs->implicit) {
6886 /* For implicit nodes, just copy everything from the single child */
6887 child = QLIST_FIRST(&bs->children);
6888 assert(QLIST_NEXT(child, next) == NULL);
6889
6890 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
6891 child->bs->exact_filename);
6892 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
6893
Pan Nengyuancb895612020-01-16 16:56:00 +08006894 qobject_unref(bs->full_open_options);
Max Reitzbb808d52019-02-01 20:29:07 +01006895 bs->full_open_options = qobject_ref(child->bs->full_open_options);
6896
6897 return;
6898 }
6899
Max Reitz90993622019-02-01 20:29:09 +01006900 backing_overridden = bdrv_backing_overridden(bs);
6901
6902 if (bs->open_flags & BDRV_O_NO_IO) {
6903 /* Without I/O, the backing file does not change anything.
6904 * Therefore, in such a case (primarily qemu-img), we can
6905 * pretend the backing file has not been overridden even if
6906 * it technically has been. */
6907 backing_overridden = false;
6908 }
6909
Max Reitz97e2f022019-02-01 20:29:27 +01006910 /* Gather the options QDict */
6911 opts = qdict_new();
Max Reitz998b3a12019-02-01 20:29:28 +01006912 generate_json_filename = append_strong_runtime_options(opts, bs);
6913 generate_json_filename |= backing_overridden;
Max Reitz97e2f022019-02-01 20:29:27 +01006914
6915 if (drv->bdrv_gather_child_options) {
6916 /* Some block drivers may not want to present all of their children's
6917 * options, or name them differently from BdrvChild.name */
6918 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
6919 } else {
6920 QLIST_FOREACH(child, &bs->children, next) {
Max Reitz25191e52020-05-13 13:05:33 +02006921 if (child == bs->backing && !backing_overridden) {
Max Reitz97e2f022019-02-01 20:29:27 +01006922 /* We can skip the backing BDS if it has not been overridden */
6923 continue;
6924 }
6925
6926 qdict_put(opts, child->name,
6927 qobject_ref(child->bs->full_open_options));
6928 }
6929
6930 if (backing_overridden && !bs->backing) {
6931 /* Force no backing file */
6932 qdict_put_null(opts, "backing");
6933 }
6934 }
6935
6936 qobject_unref(bs->full_open_options);
6937 bs->full_open_options = opts;
6938
Max Reitz52f72d62019-06-12 17:43:03 +02006939 primary_child_bs = bdrv_primary_bs(bs);
6940
Max Reitz998b3a12019-02-01 20:29:28 +01006941 if (drv->bdrv_refresh_filename) {
6942 /* Obsolete information is of no use here, so drop the old file name
6943 * information before refreshing it */
6944 bs->exact_filename[0] = '\0';
6945
6946 drv->bdrv_refresh_filename(bs);
Max Reitz52f72d62019-06-12 17:43:03 +02006947 } else if (primary_child_bs) {
6948 /*
6949 * Try to reconstruct valid information from the underlying
6950 * file -- this only works for format nodes (filter nodes
6951 * cannot be probed and as such must be selected by the user
6952 * either through an options dict, or through a special
6953 * filename which the filter driver must construct in its
6954 * .bdrv_refresh_filename() implementation).
6955 */
Max Reitz998b3a12019-02-01 20:29:28 +01006956
6957 bs->exact_filename[0] = '\0';
6958
Max Reitzfb695c72019-02-01 20:29:29 +01006959 /*
6960 * We can use the underlying file's filename if:
6961 * - it has a filename,
Max Reitz52f72d62019-06-12 17:43:03 +02006962 * - the current BDS is not a filter,
Max Reitzfb695c72019-02-01 20:29:29 +01006963 * - the file is a protocol BDS, and
6964 * - opening that file (as this BDS's format) will automatically create
6965 * the BDS tree we have right now, that is:
6966 * - the user did not significantly change this BDS's behavior with
6967 * some explicit (strong) options
6968 * - no non-file child of this BDS has been overridden by the user
6969 * Both of these conditions are represented by generate_json_filename.
6970 */
Max Reitz52f72d62019-06-12 17:43:03 +02006971 if (primary_child_bs->exact_filename[0] &&
6972 primary_child_bs->drv->bdrv_file_open &&
6973 !drv->is_filter && !generate_json_filename)
Max Reitzfb695c72019-02-01 20:29:29 +01006974 {
Max Reitz52f72d62019-06-12 17:43:03 +02006975 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
Max Reitz998b3a12019-02-01 20:29:28 +01006976 }
6977 }
6978
Max Reitz91af7012014-07-18 20:24:56 +02006979 if (bs->exact_filename[0]) {
6980 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
Max Reitz97e2f022019-02-01 20:29:27 +01006981 } else {
Max Reitz91af7012014-07-18 20:24:56 +02006982 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
Eric Blake5c86bdf2020-06-08 13:26:38 -05006983 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
6984 qstring_get_str(json)) >= sizeof(bs->filename)) {
6985 /* Give user a hint if we truncated things. */
6986 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
6987 }
Marc-André Lureaucb3e7f02018-04-19 17:01:43 +02006988 qobject_unref(json);
Max Reitz91af7012014-07-18 20:24:56 +02006989 }
6990}
Wen Congyange06018a2016-05-10 15:36:37 +08006991
Max Reitz1e89d0f2019-02-01 20:29:18 +01006992char *bdrv_dirname(BlockDriverState *bs, Error **errp)
6993{
6994 BlockDriver *drv = bs->drv;
Max Reitz52f72d62019-06-12 17:43:03 +02006995 BlockDriverState *child_bs;
Max Reitz1e89d0f2019-02-01 20:29:18 +01006996
6997 if (!drv) {
6998 error_setg(errp, "Node '%s' is ejected", bs->node_name);
6999 return NULL;
7000 }
7001
7002 if (drv->bdrv_dirname) {
7003 return drv->bdrv_dirname(bs, errp);
7004 }
7005
Max Reitz52f72d62019-06-12 17:43:03 +02007006 child_bs = bdrv_primary_bs(bs);
7007 if (child_bs) {
7008 return bdrv_dirname(child_bs, errp);
Max Reitz1e89d0f2019-02-01 20:29:18 +01007009 }
7010
7011 bdrv_refresh_filename(bs);
7012 if (bs->exact_filename[0] != '\0') {
7013 return path_combine(bs->exact_filename, "");
7014 }
7015
7016 error_setg(errp, "Cannot generate a base directory for %s nodes",
7017 drv->format_name);
7018 return NULL;
7019}
7020
Wen Congyange06018a2016-05-10 15:36:37 +08007021/*
7022 * Hot add/remove a BDS's child. So the user can take a child offline when
7023 * it is broken and take a new child online
7024 */
7025void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7026 Error **errp)
7027{
7028
7029 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7030 error_setg(errp, "The node %s does not support adding a child",
7031 bdrv_get_device_or_node_name(parent_bs));
7032 return;
7033 }
7034
7035 if (!QLIST_EMPTY(&child_bs->parents)) {
7036 error_setg(errp, "The node %s already has a parent",
7037 child_bs->node_name);
7038 return;
7039 }
7040
7041 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7042}
7043
7044void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7045{
7046 BdrvChild *tmp;
7047
7048 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7049 error_setg(errp, "The node %s does not support removing a child",
7050 bdrv_get_device_or_node_name(parent_bs));
7051 return;
7052 }
7053
7054 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7055 if (tmp == child) {
7056 break;
7057 }
7058 }
7059
7060 if (!tmp) {
7061 error_setg(errp, "The node %s does not have a child named %s",
7062 bdrv_get_device_or_node_name(parent_bs),
7063 bdrv_get_device_or_node_name(child->bs));
7064 return;
7065 }
7066
7067 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7068}
Max Reitz6f7a3b52020-04-29 16:11:23 +02007069
7070int bdrv_make_empty(BdrvChild *c, Error **errp)
7071{
7072 BlockDriver *drv = c->bs->drv;
7073 int ret;
7074
7075 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7076
7077 if (!drv->bdrv_make_empty) {
7078 error_setg(errp, "%s does not support emptying nodes",
7079 drv->format_name);
7080 return -ENOTSUP;
7081 }
7082
7083 ret = drv->bdrv_make_empty(c->bs);
7084 if (ret < 0) {
7085 error_setg_errno(errp, -ret, "Failed to empty %s",
7086 c->bs->filename);
7087 return ret;
7088 }
7089
7090 return 0;
7091}
Max Reitz9a6fc882019-05-31 15:23:11 +02007092
7093/*
7094 * Return the child that @bs acts as an overlay for, and from which data may be
7095 * copied in COW or COR operations. Usually this is the backing file.
7096 */
7097BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7098{
7099 if (!bs || !bs->drv) {
7100 return NULL;
7101 }
7102
7103 if (bs->drv->is_filter) {
7104 return NULL;
7105 }
7106
7107 if (!bs->backing) {
7108 return NULL;
7109 }
7110
7111 assert(bs->backing->role & BDRV_CHILD_COW);
7112 return bs->backing;
7113}
7114
7115/*
7116 * If @bs acts as a filter for exactly one of its children, return
7117 * that child.
7118 */
7119BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7120{
7121 BdrvChild *c;
7122
7123 if (!bs || !bs->drv) {
7124 return NULL;
7125 }
7126
7127 if (!bs->drv->is_filter) {
7128 return NULL;
7129 }
7130
7131 /* Only one of @backing or @file may be used */
7132 assert(!(bs->backing && bs->file));
7133
7134 c = bs->backing ?: bs->file;
7135 if (!c) {
7136 return NULL;
7137 }
7138
7139 assert(c->role & BDRV_CHILD_FILTERED);
7140 return c;
7141}
7142
7143/*
7144 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7145 * whichever is non-NULL.
7146 *
7147 * Return NULL if both are NULL.
7148 */
7149BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7150{
7151 BdrvChild *cow_child = bdrv_cow_child(bs);
7152 BdrvChild *filter_child = bdrv_filter_child(bs);
7153
7154 /* Filter nodes cannot have COW backing files */
7155 assert(!(cow_child && filter_child));
7156
7157 return cow_child ?: filter_child;
7158}
7159
7160/*
7161 * Return the primary child of this node: For filters, that is the
7162 * filtered child. For other nodes, that is usually the child storing
7163 * metadata.
7164 * (A generally more helpful description is that this is (usually) the
7165 * child that has the same filename as @bs.)
7166 *
7167 * Drivers do not necessarily have a primary child; for example quorum
7168 * does not.
7169 */
7170BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7171{
7172 BdrvChild *c, *found = NULL;
7173
7174 QLIST_FOREACH(c, &bs->children, next) {
7175 if (c->role & BDRV_CHILD_PRIMARY) {
7176 assert(!found);
7177 found = c;
7178 }
7179 }
7180
7181 return found;
7182}
Max Reitzd38d7eb2019-06-12 15:06:37 +02007183
7184static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
7185 bool stop_on_explicit_filter)
7186{
7187 BdrvChild *c;
7188
7189 if (!bs) {
7190 return NULL;
7191 }
7192
7193 while (!(stop_on_explicit_filter && !bs->implicit)) {
7194 c = bdrv_filter_child(bs);
7195 if (!c) {
7196 /*
7197 * A filter that is embedded in a working block graph must
7198 * have a child. Assert this here so this function does
7199 * not return a filter node that is not expected by the
7200 * caller.
7201 */
7202 assert(!bs->drv || !bs->drv->is_filter);
7203 break;
7204 }
7205 bs = c->bs;
7206 }
7207 /*
7208 * Note that this treats nodes with bs->drv == NULL as not being
7209 * filters (bs->drv == NULL should be replaced by something else
7210 * anyway).
7211 * The advantage of this behavior is that this function will thus
7212 * always return a non-NULL value (given a non-NULL @bs).
7213 */
7214
7215 return bs;
7216}
7217
7218/*
7219 * Return the first BDS that has not been added implicitly or that
7220 * does not have a filtered child down the chain starting from @bs
7221 * (including @bs itself).
7222 */
7223BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
7224{
7225 return bdrv_do_skip_filters(bs, true);
7226}
7227
7228/*
7229 * Return the first BDS that does not have a filtered child down the
7230 * chain starting from @bs (including @bs itself).
7231 */
7232BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
7233{
7234 return bdrv_do_skip_filters(bs, false);
7235}
7236
7237/*
7238 * For a backing chain, return the first non-filter backing image of
7239 * the first non-filter image.
7240 */
7241BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
7242{
7243 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
7244}