blob: 2711c3dd3b7b9d05c6bc9f70f3b37ea3aef954ae [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 */
Peter Maydelld38ea872016-01-29 17:50:05 +000024#include "qemu/osdep.h"
Daniel P. Berrange0ab8ed12017-01-25 16:14:15 +000025#include "block/trace.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010026#include "block/block_int.h"
27#include "block/blockjob.h"
Kevin Wolfcd7fca92016-07-06 11:22:39 +020028#include "block/nbd.h"
Markus Armbrusterd49b6832015-03-17 18:29:20 +010029#include "qemu/error-report.h"
Marc Mari88d88792016-08-12 09:27:03 -040030#include "module_block.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010031#include "qemu/module.h"
Markus Armbrustercc7a8ea2015-03-17 17:22:46 +010032#include "qapi/qmp/qerror.h"
Kevin Wolf91a097e2015-05-08 17:49:53 +020033#include "qapi/qmp/qbool.h"
Paolo Bonzini7b1b5d12012-12-17 18:19:43 +010034#include "qapi/qmp/qjson.h"
Markus Armbrusterbfb197e2014-10-07 13:59:11 +020035#include "sysemu/block-backend.h"
Paolo Bonzini9c17d612012-12-17 18:20:04 +010036#include "sysemu/sysemu.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010037#include "qemu/notify.h"
Daniel P. Berrange10817bf2015-09-01 14:48:02 +010038#include "qemu/coroutine.h"
Benoît Canetc13163f2014-01-23 21:31:34 +010039#include "block/qapi.h"
Luiz Capitulinob2023812011-09-21 17:16:47 -030040#include "qmp-commands.h"
Paolo Bonzini1de7afc2012-12-17 18:20:00 +010041#include "qemu/timer.h"
Wenchao Xiaa5ee7bd2014-06-18 08:43:44 +020042#include "qapi-event.h"
Veronia Bahaaf348b6d2016-03-20 19:16:19 +020043#include "qemu/cutils.h"
44#include "qemu/id.h"
Kevin Wolf692e01a2016-09-12 21:00:41 +020045#include "qapi/util.h"
bellardfc01f7e2003-06-30 10:03:06 +000046
Juan Quintela71e72a12009-07-27 16:12:56 +020047#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000048#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000049#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000050#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000051#include <sys/disk.h>
52#endif
blueswir1c5e97232009-03-07 20:06:23 +000053#endif
bellard7674e7b2005-04-26 21:59:26 +000054
aliguori49dc7682009-03-08 16:26:59 +000055#ifdef _WIN32
56#include <windows.h>
57#endif
58
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010059#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
60
Benoît Canetdc364f42014-01-23 21:31:32 +010061static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
62 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
63
Max Reitz2c1d04e2016-01-29 16:36:11 +010064static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
65 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
66
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010067static QLIST_HEAD(, BlockDriver) bdrv_drivers =
68 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +000069
Max Reitz5b363932016-05-17 16:41:31 +020070static BlockDriverState *bdrv_open_inherit(const char *filename,
71 const char *reference,
72 QDict *options, int flags,
73 BlockDriverState *parent,
74 const BdrvChildRole *child_role,
75 Error **errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +020076
Markus Armbrustereb852012009-10-27 18:41:44 +010077/* If non-zero, use only whitelisted block drivers */
78static int use_bdrv_whitelist;
79
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +000080#ifdef _WIN32
81static int is_windows_drive_prefix(const char *filename)
82{
83 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
84 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
85 filename[1] == ':');
86}
87
88int is_windows_drive(const char *filename)
89{
90 if (is_windows_drive_prefix(filename) &&
91 filename[2] == '\0')
92 return 1;
93 if (strstart(filename, "\\\\.\\", NULL) ||
94 strstart(filename, "//./", NULL))
95 return 1;
96 return 0;
97}
98#endif
99
Kevin Wolf339064d2013-11-28 10:23:32 +0100100size_t bdrv_opt_mem_align(BlockDriverState *bs)
101{
102 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300103 /* page size or 4k (hdd sector size) should be on the safe side */
104 return MAX(4096, getpagesize());
Kevin Wolf339064d2013-11-28 10:23:32 +0100105 }
106
107 return bs->bl.opt_mem_alignment;
108}
109
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300110size_t bdrv_min_mem_align(BlockDriverState *bs)
111{
112 if (!bs || !bs->drv) {
Denis V. Lunev459b4e62015-05-12 17:30:56 +0300113 /* page size or 4k (hdd sector size) should be on the safe side */
114 return MAX(4096, getpagesize());
Denis V. Lunev4196d2f2015-05-12 17:30:55 +0300115 }
116
117 return bs->bl.min_mem_alignment;
118}
119
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000120/* check if the path starts with "<protocol>:" */
Max Reitz5c984152014-12-03 14:57:22 +0100121int path_has_protocol(const char *path)
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000122{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200123 const char *p;
124
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000125#ifdef _WIN32
126 if (is_windows_drive(path) ||
127 is_windows_drive_prefix(path)) {
128 return 0;
129 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200130 p = path + strcspn(path, ":/\\");
131#else
132 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000133#endif
134
Paolo Bonzini947995c2012-05-08 16:51:48 +0200135 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000136}
137
bellard83f64092006-08-01 16:21:11 +0000138int path_is_absolute(const char *path)
139{
bellard21664422007-01-07 18:22:37 +0000140#ifdef _WIN32
141 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200142 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000143 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200144 }
145 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000146#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200147 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000148#endif
bellard83f64092006-08-01 16:21:11 +0000149}
150
151/* if filename is absolute, just copy it to dest. Otherwise, build a
152 path to it by considering it is relative to base_path. URL are
153 supported. */
154void path_combine(char *dest, int dest_size,
155 const char *base_path,
156 const char *filename)
157{
158 const char *p, *p1;
159 int len;
160
161 if (dest_size <= 0)
162 return;
163 if (path_is_absolute(filename)) {
164 pstrcpy(dest, dest_size, filename);
165 } else {
Max Reitz0d54a6f2017-05-22 21:52:15 +0200166 const char *protocol_stripped = NULL;
167
168 if (path_has_protocol(base_path)) {
169 protocol_stripped = strchr(base_path, ':');
170 if (protocol_stripped) {
171 protocol_stripped++;
172 }
173 }
174 p = protocol_stripped ?: base_path;
175
bellard3b9f94e2007-01-07 17:27:07 +0000176 p1 = strrchr(base_path, '/');
177#ifdef _WIN32
178 {
179 const char *p2;
180 p2 = strrchr(base_path, '\\');
181 if (!p1 || p2 > p1)
182 p1 = p2;
183 }
184#endif
bellard83f64092006-08-01 16:21:11 +0000185 if (p1)
186 p1++;
187 else
188 p1 = base_path;
189 if (p1 > p)
190 p = p1;
191 len = p - base_path;
192 if (len > dest_size - 1)
193 len = dest_size - 1;
194 memcpy(dest, base_path, len);
195 dest[len] = '\0';
196 pstrcat(dest, dest_size, filename);
197 }
198}
199
Max Reitz03c320d2017-05-22 21:52:16 +0200200/*
201 * Helper function for bdrv_parse_filename() implementations to remove optional
202 * protocol prefixes (especially "file:") from a filename and for putting the
203 * stripped filename into the options QDict if there is such a prefix.
204 */
205void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
206 QDict *options)
207{
208 if (strstart(filename, prefix, &filename)) {
209 /* Stripping the explicit protocol prefix may result in a protocol
210 * prefix being (wrongly) detected (if the filename contains a colon) */
211 if (path_has_protocol(filename)) {
212 QString *fat_filename;
213
214 /* This means there is some colon before the first slash; therefore,
215 * this cannot be an absolute path */
216 assert(!path_is_absolute(filename));
217
218 /* And we can thus fix the protocol detection issue by prefixing it
219 * by "./" */
220 fat_filename = qstring_from_str("./");
221 qstring_append(fat_filename, filename);
222
223 assert(!path_has_protocol(qstring_get_str(fat_filename)));
224
225 qdict_put(options, "filename", fat_filename);
226 } else {
227 /* If no protocol prefix was detected, we can use the shortened
228 * filename as-is */
229 qdict_put_str(options, "filename", filename);
230 }
231 }
232}
233
234
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200235/* Returns whether the image file is opened as read-only. Note that this can
236 * return false and writing to the image file is still not possible because the
237 * image is inactivated. */
Jeff Cody93ed5242017-04-07 16:55:28 -0400238bool bdrv_is_read_only(BlockDriverState *bs)
239{
240 return bs->read_only;
241}
242
Kevin Wolf9c5e6592017-05-04 18:52:40 +0200243/* Returns whether the image file can be written to right now */
244bool bdrv_is_writable(BlockDriverState *bs)
245{
246 return !bdrv_is_read_only(bs) && !(bs->open_flags & BDRV_O_INACTIVE);
247}
248
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200249int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
250 bool ignore_allow_rdw, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400251{
Jeff Codye2b82472017-04-07 16:55:26 -0400252 /* Do not set read_only if copy_on_read is enabled */
253 if (bs->copy_on_read && read_only) {
254 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
255 bdrv_get_device_or_node_name(bs));
256 return -EINVAL;
257 }
258
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400259 /* Do not clear read_only if it is prohibited */
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200260 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
261 !ignore_allow_rdw)
262 {
Jeff Codyd6fcdf02017-04-07 16:55:27 -0400263 error_setg(errp, "Node '%s' is read only",
264 bdrv_get_device_or_node_name(bs));
265 return -EPERM;
266 }
267
Jeff Cody45803a02017-04-07 16:55:29 -0400268 return 0;
269}
270
271int bdrv_set_read_only(BlockDriverState *bs, bool read_only, Error **errp)
272{
273 int ret = 0;
274
Kevin Wolf54a32bf2017-08-03 17:02:58 +0200275 ret = bdrv_can_set_read_only(bs, read_only, false, errp);
Jeff Cody45803a02017-04-07 16:55:29 -0400276 if (ret < 0) {
277 return ret;
278 }
279
Jeff Codyfe5241b2017-04-07 16:55:25 -0400280 bs->read_only = read_only;
Jeff Codye2b82472017-04-07 16:55:26 -0400281 return 0;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400282}
283
Max Reitz0a828552014-11-26 17:20:25 +0100284void bdrv_get_full_backing_filename_from_filename(const char *backed,
285 const char *backing,
Max Reitz9f074292014-11-26 17:20:26 +0100286 char *dest, size_t sz,
287 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100288{
Max Reitz9f074292014-11-26 17:20:26 +0100289 if (backing[0] == '\0' || path_has_protocol(backing) ||
290 path_is_absolute(backing))
291 {
Max Reitz0a828552014-11-26 17:20:25 +0100292 pstrcpy(dest, sz, backing);
Max Reitz9f074292014-11-26 17:20:26 +0100293 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
294 error_setg(errp, "Cannot use relative backing file names for '%s'",
295 backed);
Max Reitz0a828552014-11-26 17:20:25 +0100296 } else {
297 path_combine(dest, sz, backed, backing);
298 }
299}
300
Max Reitz9f074292014-11-26 17:20:26 +0100301void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
302 Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200303{
Max Reitz9f074292014-11-26 17:20:26 +0100304 char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
305
306 bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
307 dest, sz, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200308}
309
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100310void bdrv_register(BlockDriver *bdrv)
311{
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100312 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000313}
bellardb3380822004-03-14 21:38:54 +0000314
Markus Armbrustere4e99862014-10-07 13:59:03 +0200315BlockDriverState *bdrv_new(void)
316{
317 BlockDriverState *bs;
318 int i;
319
Markus Armbruster5839e532014-08-19 10:31:08 +0200320 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800321 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800322 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
323 QLIST_INIT(&bs->op_blockers[i]);
324 }
Stefan Hajnoczid616b222013-06-24 17:13:10 +0200325 notifier_with_return_list_init(&bs->before_write_notifiers);
Paolo Bonzini3783fa32017-06-05 14:39:02 +0200326 qemu_co_mutex_init(&bs->reqs_lock);
Paolo Bonzini21198822017-06-05 14:39:03 +0200327 qemu_mutex_init(&bs->dirty_bitmap_mutex);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800328 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200329 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200330
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300331 qemu_co_queue_init(&bs->flush_queue);
332
Max Reitz2c1d04e2016-01-29 16:36:11 +0100333 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
334
bellardb3380822004-03-14 21:38:54 +0000335 return bs;
336}
337
Marc Mari88d88792016-08-12 09:27:03 -0400338static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000339{
340 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400341
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100342 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
343 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000344 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100345 }
bellardea2384d2004-08-01 21:59:26 +0000346 }
Marc Mari88d88792016-08-12 09:27:03 -0400347
bellardea2384d2004-08-01 21:59:26 +0000348 return NULL;
349}
350
Marc Mari88d88792016-08-12 09:27:03 -0400351BlockDriver *bdrv_find_format(const char *format_name)
352{
353 BlockDriver *drv1;
354 int i;
355
356 drv1 = bdrv_do_find_format(format_name);
357 if (drv1) {
358 return drv1;
359 }
360
361 /* The driver isn't registered, maybe we need to load a module */
362 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
363 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
364 block_module_load_one(block_driver_modules[i].library_name);
365 break;
366 }
367 }
368
369 return bdrv_do_find_format(format_name);
370}
371
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800372static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100373{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800374 static const char *whitelist_rw[] = {
375 CONFIG_BDRV_RW_WHITELIST
376 };
377 static const char *whitelist_ro[] = {
378 CONFIG_BDRV_RO_WHITELIST
Markus Armbrustereb852012009-10-27 18:41:44 +0100379 };
380 const char **p;
381
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800382 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100383 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800384 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100385
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800386 for (p = whitelist_rw; *p; p++) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100387 if (!strcmp(drv->format_name, *p)) {
388 return 1;
389 }
390 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800391 if (read_only) {
392 for (p = whitelist_ro; *p; p++) {
393 if (!strcmp(drv->format_name, *p)) {
394 return 1;
395 }
396 }
397 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100398 return 0;
399}
400
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000401bool bdrv_uses_whitelist(void)
402{
403 return use_bdrv_whitelist;
404}
405
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800406typedef struct CreateCo {
407 BlockDriver *drv;
408 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800409 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800410 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200411 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800412} CreateCo;
413
414static void coroutine_fn bdrv_create_co_entry(void *opaque)
415{
Max Reitzcc84d902013-09-06 17:14:26 +0200416 Error *local_err = NULL;
417 int ret;
418
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800419 CreateCo *cco = opaque;
420 assert(cco->drv);
421
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800422 ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300423 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200424 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800425}
426
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200427int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800428 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000429{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800430 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200431
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800432 Coroutine *co;
433 CreateCo cco = {
434 .drv = drv,
435 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800436 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800437 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200438 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800439 };
440
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800441 if (!drv->bdrv_create) {
Max Reitzcc84d902013-09-06 17:14:26 +0200442 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300443 ret = -ENOTSUP;
444 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800445 }
446
447 if (qemu_in_coroutine()) {
448 /* Fast-path if already in coroutine context */
449 bdrv_create_co_entry(&cco);
450 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200451 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
452 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800453 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200454 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800455 }
456 }
457
458 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200459 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100460 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200461 error_propagate(errp, cco.err);
462 } else {
463 error_setg_errno(errp, -ret, "Could not create image");
464 }
465 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800466
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300467out:
468 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800469 return ret;
bellardea2384d2004-08-01 21:59:26 +0000470}
471
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800472int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200473{
474 BlockDriver *drv;
Max Reitzcc84d902013-09-06 17:14:26 +0200475 Error *local_err = NULL;
476 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200477
Max Reitzb65a5e12015-02-05 13:58:12 -0500478 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200479 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000480 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200481 }
482
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800483 ret = bdrv_create(drv, filename, opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300484 error_propagate(errp, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200485 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200486}
487
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100488/**
489 * Try to get @bs's logical and physical block size.
490 * On success, store them in @bsz struct and return 0.
491 * On failure return -errno.
492 * @bs must not be empty.
493 */
494int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
495{
496 BlockDriver *drv = bs->drv;
497
498 if (drv && drv->bdrv_probe_blocksizes) {
499 return drv->bdrv_probe_blocksizes(bs, bsz);
500 }
501
502 return -ENOTSUP;
503}
504
505/**
506 * Try to get @bs's geometry (cyls, heads, sectors).
507 * On success, store them in @geo struct and return 0.
508 * On failure return -errno.
509 * @bs must not be empty.
510 */
511int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
512{
513 BlockDriver *drv = bs->drv;
514
515 if (drv && drv->bdrv_probe_geometry) {
516 return drv->bdrv_probe_geometry(bs, geo);
517 }
518
519 return -ENOTSUP;
520}
521
Jim Meyeringeba25052012-05-28 09:27:54 +0200522/*
523 * Create a uniquely-named empty temporary file.
524 * Return 0 upon success, otherwise a negative errno value.
525 */
526int get_tmp_filename(char *filename, int size)
527{
bellardd5249392004-08-03 21:14:23 +0000528#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000529 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200530 /* GetTempFileName requires that its output buffer (4th param)
531 have length MAX_PATH or greater. */
532 assert(size >= MAX_PATH);
533 return (GetTempPath(MAX_PATH, temp_dir)
534 && GetTempFileName(temp_dir, "qem", 0, filename)
535 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000536#else
bellardea2384d2004-08-01 21:59:26 +0000537 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000538 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000539 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530540 if (!tmpdir) {
541 tmpdir = "/var/tmp";
542 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200543 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
544 return -EOVERFLOW;
545 }
bellardea2384d2004-08-01 21:59:26 +0000546 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800547 if (fd < 0) {
548 return -errno;
549 }
550 if (close(fd) != 0) {
551 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200552 return -errno;
553 }
554 return 0;
bellardd5249392004-08-03 21:14:23 +0000555#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200556}
bellardea2384d2004-08-01 21:59:26 +0000557
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200558/*
559 * Detect host devices. By convention, /dev/cdrom[N] is always
560 * recognized as a host CDROM.
561 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200562static BlockDriver *find_hdev_driver(const char *filename)
563{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200564 int score_max = 0, score;
565 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200566
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100567 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200568 if (d->bdrv_probe_device) {
569 score = d->bdrv_probe_device(filename);
570 if (score > score_max) {
571 score_max = score;
572 drv = d;
573 }
574 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200575 }
576
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200577 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200578}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200579
Marc Mari88d88792016-08-12 09:27:03 -0400580static BlockDriver *bdrv_do_find_protocol(const char *protocol)
581{
582 BlockDriver *drv1;
583
584 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
585 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
586 return drv1;
587 }
588 }
589
590 return NULL;
591}
592
Kevin Wolf98289622013-07-10 15:47:39 +0200593BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500594 bool allow_protocol_prefix,
595 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200596{
597 BlockDriver *drv1;
598 char protocol[128];
599 int len;
600 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400601 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200602
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200603 /* TODO Drivers without bdrv_file_open must be specified explicitly */
604
Christoph Hellwig39508e72010-06-23 12:25:17 +0200605 /*
606 * XXX(hch): we really should not let host device detection
607 * override an explicit protocol specification, but moving this
608 * later breaks access to device names with colons in them.
609 * Thanks to the brain-dead persistent naming schemes on udev-
610 * based Linux systems those actually are quite common.
611 */
612 drv1 = find_hdev_driver(filename);
613 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200614 return drv1;
615 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200616
Kevin Wolf98289622013-07-10 15:47:39 +0200617 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100618 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200619 }
Kevin Wolf98289622013-07-10 15:47:39 +0200620
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000621 p = strchr(filename, ':');
622 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200623 len = p - filename;
624 if (len > sizeof(protocol) - 1)
625 len = sizeof(protocol) - 1;
626 memcpy(protocol, filename, len);
627 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400628
629 drv1 = bdrv_do_find_protocol(protocol);
630 if (drv1) {
631 return drv1;
632 }
633
634 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
635 if (block_driver_modules[i].protocol_name &&
636 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
637 block_module_load_one(block_driver_modules[i].library_name);
638 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200639 }
640 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500641
Marc Mari88d88792016-08-12 09:27:03 -0400642 drv1 = bdrv_do_find_protocol(protocol);
643 if (!drv1) {
644 error_setg(errp, "Unknown protocol '%s'", protocol);
645 }
646 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200647}
648
Markus Armbrusterc6684242014-11-20 16:27:10 +0100649/*
650 * Guess image format by probing its contents.
651 * This is not a good idea when your image is raw (CVE-2008-2004), but
652 * we do it anyway for backward compatibility.
653 *
654 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100655 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
656 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100657 * @filename is its filename.
658 *
659 * For all block drivers, call the bdrv_probe() method to get its
660 * probing score.
661 * Return the first block driver with the highest probing score.
662 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100663BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
664 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100665{
666 int score_max = 0, score;
667 BlockDriver *drv = NULL, *d;
668
669 QLIST_FOREACH(d, &bdrv_drivers, list) {
670 if (d->bdrv_probe) {
671 score = d->bdrv_probe(buf, buf_size, filename);
672 if (score > score_max) {
673 score_max = score;
674 drv = d;
675 }
676 }
677 }
678
679 return drv;
680}
681
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100682static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200683 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000684{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100685 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100686 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100687 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700688
Kevin Wolf08a00552010-06-01 18:37:31 +0200689 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100690 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100691 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200692 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700693 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700694
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100695 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +0000696 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200697 error_setg_errno(errp, -ret, "Could not read image for determining its "
698 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +0200699 *pdrv = NULL;
700 return ret;
bellard83f64092006-08-01 16:21:11 +0000701 }
702
Markus Armbrusterc6684242014-11-20 16:27:10 +0100703 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +0200704 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200705 error_setg(errp, "Could not determine image format: No compatible "
706 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +0200707 ret = -ENOENT;
708 }
709 *pdrv = drv;
710 return ret;
bellardea2384d2004-08-01 21:59:26 +0000711}
712
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100713/**
714 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +0200715 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100716 */
717static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
718{
719 BlockDriver *drv = bs->drv;
720
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700721 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +0300722 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700723 return 0;
724
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100725 /* query actual device if possible, otherwise just trust the hint */
726 if (drv->bdrv_getlength) {
727 int64_t length = drv->bdrv_getlength(bs);
728 if (length < 0) {
729 return length;
730 }
Fam Zheng7e382002013-11-06 19:48:06 +0800731 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100732 }
733
734 bs->total_sectors = hint;
735 return 0;
736}
737
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100738/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +0100739 * Combines a QDict of new block driver @options with any missing options taken
740 * from @old_options, so that leaving out an option defaults to its old value.
741 */
742static void bdrv_join_options(BlockDriverState *bs, QDict *options,
743 QDict *old_options)
744{
745 if (bs->drv && bs->drv->bdrv_join_options) {
746 bs->drv->bdrv_join_options(options, old_options);
747 } else {
748 qdict_join(options, old_options, false);
749 }
750}
751
752/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +0100753 * Set open flags for a given discard mode
754 *
755 * Return 0 on success, -1 if the discard mode was invalid.
756 */
757int bdrv_parse_discard_flags(const char *mode, int *flags)
758{
759 *flags &= ~BDRV_O_UNMAP;
760
761 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
762 /* do nothing */
763 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
764 *flags |= BDRV_O_UNMAP;
765 } else {
766 return -1;
767 }
768
769 return 0;
770}
771
772/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100773 * Set open flags for a given cache mode
774 *
775 * Return 0 on success, -1 if the cache mode was invalid.
776 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100777int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100778{
779 *flags &= ~BDRV_O_CACHE_MASK;
780
781 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100782 *writethrough = false;
783 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100784 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100785 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100786 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100787 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100788 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100789 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100790 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100791 *flags |= BDRV_O_NO_FLUSH;
792 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100793 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100794 } else {
795 return -1;
796 }
797
798 return 0;
799}
800
Kevin Wolfb5411552017-01-17 15:56:16 +0100801static char *bdrv_child_get_parent_desc(BdrvChild *c)
802{
803 BlockDriverState *parent = c->opaque;
804 return g_strdup(bdrv_get_device_or_node_name(parent));
805}
806
Kevin Wolf20018e12016-05-23 18:46:59 +0200807static void bdrv_child_cb_drained_begin(BdrvChild *child)
808{
809 BlockDriverState *bs = child->opaque;
810 bdrv_drained_begin(bs);
811}
812
813static void bdrv_child_cb_drained_end(BdrvChild *child)
814{
815 BlockDriverState *bs = child->opaque;
816 bdrv_drained_end(bs);
817}
818
Kevin Wolf38701b62017-05-04 18:52:39 +0200819static int bdrv_child_cb_inactivate(BdrvChild *child)
820{
821 BlockDriverState *bs = child->opaque;
822 assert(bs->open_flags & BDRV_O_INACTIVE);
823 return 0;
824}
825
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200826/*
Kevin Wolf73176be2016-03-07 13:02:15 +0100827 * Returns the options and flags that a temporary snapshot should get, based on
828 * the originally requested flags (the originally requested image will have
829 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +0200830 */
Kevin Wolf73176be2016-03-07 13:02:15 +0100831static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
832 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +0200833{
Kevin Wolf73176be2016-03-07 13:02:15 +0100834 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
835
836 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +0100837 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
838 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +0200839
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300840 /* Copy the read-only option from the parent */
841 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
842
Kevin Wolf41869042016-06-16 12:59:30 +0200843 /* aio=native doesn't work for cache.direct=off, so disable it for the
844 * temporary snapshot */
845 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +0200846}
847
848/*
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200849 * Returns the options and flags that bs->file should get if a protocol driver
850 * is expected, based on the given options and flags for the parent BDS
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200851 */
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200852static void bdrv_inherited_options(int *child_flags, QDict *child_options,
853 int parent_flags, QDict *parent_options)
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200854{
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200855 int flags = parent_flags;
856
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200857 /* Enable protocol handling, disable format probing for bs->file */
858 flags |= BDRV_O_PROTOCOL;
859
Kevin Wolf91a097e2015-05-08 17:49:53 +0200860 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
861 * the parent. */
862 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
863 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
Fam Zheng5a9347c2017-05-03 00:35:37 +0800864 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
Kevin Wolf91a097e2015-05-08 17:49:53 +0200865
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300866 /* Inherit the read-only option from the parent if it's not set */
867 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
868
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200869 /* Our block drivers take care to send flushes and respect unmap policy,
Kevin Wolf91a097e2015-05-08 17:49:53 +0200870 * so we can default to enable both on lower layers regardless of the
871 * corresponding parent options. */
Kevin Wolf818584a2016-09-12 18:03:18 +0200872 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200873
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200874 /* Clear flags that only apply to the top layer */
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000875 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
876 BDRV_O_NO_IO);
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200877
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200878 *child_flags = flags;
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200879}
880
Kevin Wolff3930ed2015-04-08 13:43:47 +0200881const BdrvChildRole child_file = {
Kevin Wolfb5411552017-01-17 15:56:16 +0100882 .get_parent_desc = bdrv_child_get_parent_desc,
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200883 .inherit_options = bdrv_inherited_options,
Kevin Wolf20018e12016-05-23 18:46:59 +0200884 .drained_begin = bdrv_child_cb_drained_begin,
885 .drained_end = bdrv_child_cb_drained_end,
Kevin Wolf38701b62017-05-04 18:52:39 +0200886 .inactivate = bdrv_child_cb_inactivate,
Kevin Wolff3930ed2015-04-08 13:43:47 +0200887};
888
889/*
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200890 * Returns the options and flags that bs->file should get if the use of formats
891 * (and not only protocols) is permitted for it, based on the given options and
892 * flags for the parent BDS
Kevin Wolff3930ed2015-04-08 13:43:47 +0200893 */
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200894static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
895 int parent_flags, QDict *parent_options)
Kevin Wolff3930ed2015-04-08 13:43:47 +0200896{
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200897 child_file.inherit_options(child_flags, child_options,
898 parent_flags, parent_options);
899
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000900 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
Kevin Wolff3930ed2015-04-08 13:43:47 +0200901}
902
903const BdrvChildRole child_format = {
Kevin Wolfb5411552017-01-17 15:56:16 +0100904 .get_parent_desc = bdrv_child_get_parent_desc,
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200905 .inherit_options = bdrv_inherited_fmt_options,
Kevin Wolf20018e12016-05-23 18:46:59 +0200906 .drained_begin = bdrv_child_cb_drained_begin,
907 .drained_end = bdrv_child_cb_drained_end,
Kevin Wolf38701b62017-05-04 18:52:39 +0200908 .inactivate = bdrv_child_cb_inactivate,
Kevin Wolff3930ed2015-04-08 13:43:47 +0200909};
910
Kevin Wolfdb95dbb2017-02-08 11:28:52 +0100911static void bdrv_backing_attach(BdrvChild *c)
912{
913 BlockDriverState *parent = c->opaque;
914 BlockDriverState *backing_hd = c->bs;
915
916 assert(!parent->backing_blocker);
917 error_setg(&parent->backing_blocker,
918 "node is used as backing hd of '%s'",
919 bdrv_get_device_or_node_name(parent));
920
921 parent->open_flags &= ~BDRV_O_NO_BACKING;
922 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
923 backing_hd->filename);
924 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
925 backing_hd->drv ? backing_hd->drv->format_name : "");
926
927 bdrv_op_block_all(backing_hd, parent->backing_blocker);
928 /* Otherwise we won't be able to commit or stream */
929 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
930 parent->backing_blocker);
931 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
932 parent->backing_blocker);
933 /*
934 * We do backup in 3 ways:
935 * 1. drive backup
936 * The target bs is new opened, and the source is top BDS
937 * 2. blockdev backup
938 * Both the source and the target are top BDSes.
939 * 3. internal backup(used for block replication)
940 * Both the source and the target are backing file
941 *
942 * In case 1 and 2, neither the source nor the target is the backing file.
943 * In case 3, we will block the top BDS, so there is only one block job
944 * for the top BDS and its backing chain.
945 */
946 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
947 parent->backing_blocker);
948 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
949 parent->backing_blocker);
950}
951
952static void bdrv_backing_detach(BdrvChild *c)
953{
954 BlockDriverState *parent = c->opaque;
955
956 assert(parent->backing_blocker);
957 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
958 error_free(parent->backing_blocker);
959 parent->backing_blocker = NULL;
960}
961
Kevin Wolf317fc442014-04-25 13:27:34 +0200962/*
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200963 * Returns the options and flags that bs->backing should get, based on the
964 * given options and flags for the parent BDS
Kevin Wolf317fc442014-04-25 13:27:34 +0200965 */
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200966static void bdrv_backing_options(int *child_flags, QDict *child_options,
967 int parent_flags, QDict *parent_options)
Kevin Wolf317fc442014-04-25 13:27:34 +0200968{
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200969 int flags = parent_flags;
970
Kevin Wolfb8816a42016-03-04 14:52:32 +0100971 /* The cache mode is inherited unmodified for backing files; except WCE,
972 * which is only applied on the top level (BlockBackend) */
Kevin Wolf91a097e2015-05-08 17:49:53 +0200973 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
974 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
Fam Zheng5a9347c2017-05-03 00:35:37 +0800975 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
Kevin Wolf91a097e2015-05-08 17:49:53 +0200976
Kevin Wolf317fc442014-04-25 13:27:34 +0200977 /* backing files always opened read-only */
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300978 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
979 flags &= ~BDRV_O_COPY_ON_READ;
Kevin Wolf317fc442014-04-25 13:27:34 +0200980
981 /* snapshot=on is handled on the top layer */
Kevin Wolf8bfea152014-04-11 19:16:36 +0200982 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
Kevin Wolf317fc442014-04-25 13:27:34 +0200983
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200984 *child_flags = flags;
Kevin Wolf317fc442014-04-25 13:27:34 +0200985}
986
Kevin Wolf91ef3822016-12-20 16:23:46 +0100987const BdrvChildRole child_backing = {
Kevin Wolfb5411552017-01-17 15:56:16 +0100988 .get_parent_desc = bdrv_child_get_parent_desc,
Kevin Wolfdb95dbb2017-02-08 11:28:52 +0100989 .attach = bdrv_backing_attach,
990 .detach = bdrv_backing_detach,
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200991 .inherit_options = bdrv_backing_options,
Kevin Wolf20018e12016-05-23 18:46:59 +0200992 .drained_begin = bdrv_child_cb_drained_begin,
993 .drained_end = bdrv_child_cb_drained_end,
Kevin Wolf38701b62017-05-04 18:52:39 +0200994 .inactivate = bdrv_child_cb_inactivate,
Kevin Wolff3930ed2015-04-08 13:43:47 +0200995};
996
Kevin Wolf7b272452012-11-12 17:05:39 +0100997static int bdrv_open_flags(BlockDriverState *bs, int flags)
998{
Kevin Wolf61de4c62016-03-18 17:46:45 +0100999 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +01001000
1001 /*
1002 * Clear flags that are internal to the block layer before opening the
1003 * image.
1004 */
Kevin Wolf20cca272014-06-04 14:33:27 +02001005 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +01001006
1007 /*
1008 * Snapshots should be writable.
1009 */
Kevin Wolf8bfea152014-04-11 19:16:36 +02001010 if (flags & BDRV_O_TEMPORARY) {
Kevin Wolf7b272452012-11-12 17:05:39 +01001011 open_flags |= BDRV_O_RDWR;
1012 }
1013
1014 return open_flags;
1015}
1016
Kevin Wolf91a097e2015-05-08 17:49:53 +02001017static void update_flags_from_options(int *flags, QemuOpts *opts)
1018{
1019 *flags &= ~BDRV_O_CACHE_MASK;
1020
Kevin Wolf91a097e2015-05-08 17:49:53 +02001021 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
1022 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1023 *flags |= BDRV_O_NO_FLUSH;
1024 }
1025
1026 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
1027 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1028 *flags |= BDRV_O_NOCACHE;
1029 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001030
1031 *flags &= ~BDRV_O_RDWR;
1032
1033 assert(qemu_opt_find(opts, BDRV_OPT_READ_ONLY));
1034 if (!qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false)) {
1035 *flags |= BDRV_O_RDWR;
1036 }
1037
Kevin Wolf91a097e2015-05-08 17:49:53 +02001038}
1039
1040static void update_options_from_flags(QDict *options, int flags)
1041{
Kevin Wolf91a097e2015-05-08 17:49:53 +02001042 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001043 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001044 }
1045 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001046 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1047 flags & BDRV_O_NO_FLUSH);
Kevin Wolf91a097e2015-05-08 17:49:53 +02001048 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001049 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001050 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001051 }
Kevin Wolf91a097e2015-05-08 17:49:53 +02001052}
1053
Kevin Wolf636ea372014-01-24 14:11:52 +01001054static void bdrv_assign_node_name(BlockDriverState *bs,
1055 const char *node_name,
1056 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +01001057{
Jeff Cody15489c72015-10-12 19:36:50 -04001058 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001059
Jeff Cody15489c72015-10-12 19:36:50 -04001060 if (!node_name) {
1061 node_name = gen_node_name = id_generate(ID_BLOCK);
1062 } else if (!id_wellformed(node_name)) {
1063 /*
1064 * Check for empty string or invalid characters, but not if it is
1065 * generated (generated names use characters not available to the user)
1066 */
Kevin Wolf9aebf3b2014-09-25 09:54:02 +02001067 error_setg(errp, "Invalid node name");
Kevin Wolf636ea372014-01-24 14:11:52 +01001068 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001069 }
1070
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001071 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +02001072 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001073 error_setg(errp, "node-name=%s is conflicting with a device id",
1074 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -04001075 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +01001076 }
1077
Benoît Canet6913c0c2014-01-23 21:31:33 +01001078 /* takes care of avoiding duplicates node names */
1079 if (bdrv_find_node(node_name)) {
1080 error_setg(errp, "Duplicate node name");
Jeff Cody15489c72015-10-12 19:36:50 -04001081 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001082 }
1083
1084 /* copy node name into the bs and insert it into the graph list */
1085 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1086 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -04001087out:
1088 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001089}
1090
Kevin Wolf01a56502017-01-18 15:51:56 +01001091static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1092 const char *node_name, QDict *options,
1093 int open_flags, Error **errp)
1094{
1095 Error *local_err = NULL;
1096 int ret;
1097
1098 bdrv_assign_node_name(bs, node_name, &local_err);
1099 if (local_err) {
1100 error_propagate(errp, local_err);
1101 return -EINVAL;
1102 }
1103
1104 bs->drv = drv;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001105 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Kevin Wolf01a56502017-01-18 15:51:56 +01001106 bs->opaque = g_malloc0(drv->instance_size);
1107
1108 if (drv->bdrv_file_open) {
1109 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1110 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001111 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001112 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001113 } else {
1114 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001115 }
1116
1117 if (ret < 0) {
1118 if (local_err) {
1119 error_propagate(errp, local_err);
1120 } else if (bs->filename[0]) {
1121 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1122 } else {
1123 error_setg_errno(errp, -ret, "Could not open image");
1124 }
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001125 goto open_failed;
Kevin Wolf01a56502017-01-18 15:51:56 +01001126 }
1127
1128 ret = refresh_total_sectors(bs, bs->total_sectors);
1129 if (ret < 0) {
1130 error_setg_errno(errp, -ret, "Could not refresh total sector count");
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001131 return ret;
Kevin Wolf01a56502017-01-18 15:51:56 +01001132 }
1133
1134 bdrv_refresh_limits(bs, &local_err);
1135 if (local_err) {
1136 error_propagate(errp, local_err);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001137 return -EINVAL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001138 }
1139
1140 assert(bdrv_opt_mem_align(bs) != 0);
1141 assert(bdrv_min_mem_align(bs) != 0);
1142 assert(is_power_of_2(bs->bl.request_alignment));
1143
1144 return 0;
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001145open_failed:
1146 bs->drv = NULL;
1147 if (bs->file != NULL) {
1148 bdrv_unref_child(bs, bs->file);
1149 bs->file = NULL;
1150 }
Kevin Wolf01a56502017-01-18 15:51:56 +01001151 g_free(bs->opaque);
1152 bs->opaque = NULL;
Kevin Wolf01a56502017-01-18 15:51:56 +01001153 return ret;
1154}
1155
Kevin Wolf680c7f92017-01-18 17:16:41 +01001156BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1157 int flags, Error **errp)
1158{
1159 BlockDriverState *bs;
1160 int ret;
1161
1162 bs = bdrv_new();
1163 bs->open_flags = flags;
1164 bs->explicit_options = qdict_new();
1165 bs->options = qdict_new();
1166 bs->opaque = NULL;
1167
1168 update_options_from_flags(bs->options, flags);
1169
1170 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1171 if (ret < 0) {
1172 QDECREF(bs->explicit_options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001173 bs->explicit_options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001174 QDECREF(bs->options);
Manos Pitsidianakis180ca192017-07-14 17:35:48 +03001175 bs->options = NULL;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001176 bdrv_unref(bs);
1177 return NULL;
1178 }
1179
1180 return bs;
1181}
1182
Kevin Wolfc5f30142016-10-06 11:33:17 +02001183QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001184 .name = "bdrv_common",
1185 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1186 .desc = {
1187 {
1188 .name = "node-name",
1189 .type = QEMU_OPT_STRING,
1190 .help = "Node name of the block device node",
1191 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001192 {
1193 .name = "driver",
1194 .type = QEMU_OPT_STRING,
1195 .help = "Block driver to use for the node",
1196 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001197 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001198 .name = BDRV_OPT_CACHE_DIRECT,
1199 .type = QEMU_OPT_BOOL,
1200 .help = "Bypass software writeback cache on the host",
1201 },
1202 {
1203 .name = BDRV_OPT_CACHE_NO_FLUSH,
1204 .type = QEMU_OPT_BOOL,
1205 .help = "Ignore flush requests",
1206 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001207 {
1208 .name = BDRV_OPT_READ_ONLY,
1209 .type = QEMU_OPT_BOOL,
1210 .help = "Node is opened in read-only mode",
1211 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001212 {
1213 .name = "detect-zeroes",
1214 .type = QEMU_OPT_STRING,
1215 .help = "try to optimize zero writes (off, on, unmap)",
1216 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001217 {
1218 .name = "discard",
1219 .type = QEMU_OPT_STRING,
1220 .help = "discard operation (ignore/off, unmap/on)",
1221 },
Fam Zheng5a9347c2017-05-03 00:35:37 +08001222 {
1223 .name = BDRV_OPT_FORCE_SHARE,
1224 .type = QEMU_OPT_BOOL,
1225 .help = "always accept other writers (default: off)",
1226 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001227 { /* end of list */ }
1228 },
1229};
1230
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001231/*
Kevin Wolf57915332010-04-14 15:24:50 +02001232 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001233 *
1234 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001235 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001236static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001237 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001238{
1239 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001240 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001241 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001242 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001243 const char *discard;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001244 const char *detect_zeroes;
Kevin Wolf18edf282015-04-07 17:12:56 +02001245 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001246 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001247 Error *local_err = NULL;
Kevin Wolf57915332010-04-14 15:24:50 +02001248
Paolo Bonzini64058752012-05-08 16:51:49 +02001249 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001250 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001251
Kevin Wolf62392eb2015-04-24 16:38:02 +02001252 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1253 qemu_opts_absorb_qdict(opts, options, &local_err);
1254 if (local_err) {
1255 error_propagate(errp, local_err);
1256 ret = -EINVAL;
1257 goto fail_opts;
1258 }
1259
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001260 update_flags_from_options(&bs->open_flags, opts);
1261
Kevin Wolf62392eb2015-04-24 16:38:02 +02001262 driver_name = qemu_opt_get(opts, "driver");
1263 drv = bdrv_find_format(driver_name);
1264 assert(drv != NULL);
1265
Fam Zheng5a9347c2017-05-03 00:35:37 +08001266 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1267
1268 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1269 error_setg(errp,
1270 BDRV_OPT_FORCE_SHARE
1271 "=on can only be used with read-only images");
1272 ret = -EINVAL;
1273 goto fail_opts;
1274 }
1275
Kevin Wolf45673672013-04-22 17:48:40 +02001276 if (file != NULL) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001277 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001278 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001279 /*
1280 * Caution: while qdict_get_try_str() is fine, getting
1281 * non-string types would require more care. When @options
1282 * come from -blockdev or blockdev_add, its members are typed
1283 * according to the QAPI schema, but when they come from
1284 * -drive, they're all QString.
1285 */
Kevin Wolf45673672013-04-22 17:48:40 +02001286 filename = qdict_get_try_str(options, "filename");
1287 }
1288
Max Reitz4a008242017-04-13 18:06:24 +02001289 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
Kevin Wolf765003d2014-02-03 14:49:42 +01001290 error_setg(errp, "The '%s' block driver requires a file name",
1291 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001292 ret = -EINVAL;
1293 goto fail_opts;
1294 }
1295
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001296 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1297 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001298
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001299 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001300
1301 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
Kevin Wolf8f94a6e2013-10-10 11:45:55 +02001302 error_setg(errp,
1303 !bs->read_only && bdrv_is_whitelisted(drv, true)
1304 ? "Driver '%s' can only be used for read-only devices"
1305 : "Driver '%s' is not whitelisted",
1306 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001307 ret = -ENOTSUP;
1308 goto fail_opts;
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001309 }
Kevin Wolf57915332010-04-14 15:24:50 +02001310
Paolo Bonzinid3faa132017-06-05 14:38:50 +02001311 /* bdrv_new() and bdrv_close() make it so */
1312 assert(atomic_read(&bs->copy_on_read) == 0);
1313
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001314 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001315 if (!bs->read_only) {
1316 bdrv_enable_copy_on_read(bs);
1317 } else {
1318 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001319 ret = -EINVAL;
1320 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001321 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001322 }
1323
Kevin Wolf818584a2016-09-12 18:03:18 +02001324 discard = qemu_opt_get(opts, "discard");
1325 if (discard != NULL) {
1326 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1327 error_setg(errp, "Invalid discard option");
1328 ret = -EINVAL;
1329 goto fail_opts;
1330 }
1331 }
1332
Kevin Wolf692e01a2016-09-12 21:00:41 +02001333 detect_zeroes = qemu_opt_get(opts, "detect-zeroes");
1334 if (detect_zeroes) {
1335 BlockdevDetectZeroesOptions value =
1336 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
1337 detect_zeroes,
1338 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
1339 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
1340 &local_err);
1341 if (local_err) {
1342 error_propagate(errp, local_err);
1343 ret = -EINVAL;
1344 goto fail_opts;
1345 }
1346
1347 if (value == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1348 !(bs->open_flags & BDRV_O_UNMAP))
1349 {
1350 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1351 "without setting discard operation to unmap");
1352 ret = -EINVAL;
1353 goto fail_opts;
1354 }
1355
1356 bs->detect_zeroes = value;
1357 }
1358
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001359 if (filename != NULL) {
1360 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1361 } else {
1362 bs->filename[0] = '\0';
1363 }
Max Reitz91af7012014-07-18 20:24:56 +02001364 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001365
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001366 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001367 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001368 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001369
Kevin Wolf01a56502017-01-18 15:51:56 +01001370 assert(!drv->bdrv_file_open || file == NULL);
1371 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001372 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001373 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001374 }
1375
Kevin Wolf18edf282015-04-07 17:12:56 +02001376 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001377 return 0;
1378
Kevin Wolf18edf282015-04-07 17:12:56 +02001379fail_opts:
1380 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001381 return ret;
1382}
1383
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001384static QDict *parse_json_filename(const char *filename, Error **errp)
1385{
1386 QObject *options_obj;
1387 QDict *options;
1388 int ret;
1389
1390 ret = strstart(filename, "json:", &filename);
1391 assert(ret);
1392
Markus Armbruster5577fff2017-02-28 22:26:59 +01001393 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001394 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001395 /* Work around qobject_from_json() lossage TODO fix that */
1396 if (errp && !*errp) {
1397 error_setg(errp, "Could not parse the JSON options");
1398 return NULL;
1399 }
1400 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001401 return NULL;
1402 }
1403
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001404 options = qobject_to_qdict(options_obj);
1405 if (!options) {
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001406 qobject_decref(options_obj);
1407 error_setg(errp, "Invalid JSON object given");
1408 return NULL;
1409 }
1410
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001411 qdict_flatten(options);
1412
1413 return options;
1414}
1415
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001416static void parse_json_protocol(QDict *options, const char **pfilename,
1417 Error **errp)
1418{
1419 QDict *json_options;
1420 Error *local_err = NULL;
1421
1422 /* Parse json: pseudo-protocol */
1423 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1424 return;
1425 }
1426
1427 json_options = parse_json_filename(*pfilename, &local_err);
1428 if (local_err) {
1429 error_propagate(errp, local_err);
1430 return;
1431 }
1432
1433 /* Options given in the filename have lower priority than options
1434 * specified directly */
1435 qdict_join(options, json_options, false);
1436 QDECREF(json_options);
1437 *pfilename = NULL;
1438}
1439
Kevin Wolf57915332010-04-14 15:24:50 +02001440/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001441 * Fills in default options for opening images and converts the legacy
1442 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001443 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1444 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001445 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001446static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001447 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001448{
1449 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001450 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001451 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001452 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001453 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001454
Markus Armbruster129c7d12017-03-30 19:43:12 +02001455 /*
1456 * Caution: while qdict_get_try_str() is fine, getting non-string
1457 * types would require more care. When @options come from
1458 * -blockdev or blockdev_add, its members are typed according to
1459 * the QAPI schema, but when they come from -drive, they're all
1460 * QString.
1461 */
Max Reitz53a29512015-03-19 14:53:16 -04001462 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001463 if (drvname) {
1464 drv = bdrv_find_format(drvname);
1465 if (!drv) {
1466 error_setg(errp, "Unknown driver '%s'", drvname);
1467 return -ENOENT;
1468 }
1469 /* If the user has explicitly specified the driver, this choice should
1470 * override the BDRV_O_PROTOCOL flag */
1471 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001472 }
1473
1474 if (protocol) {
1475 *flags |= BDRV_O_PROTOCOL;
1476 } else {
1477 *flags &= ~BDRV_O_PROTOCOL;
1478 }
1479
Kevin Wolf91a097e2015-05-08 17:49:53 +02001480 /* Translate cache options from flags into options */
1481 update_options_from_flags(*options, *flags);
1482
Kevin Wolff54120f2014-05-26 11:09:59 +02001483 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001484 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001485 if (!qdict_haskey(*options, "filename")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05001486 qdict_put_str(*options, "filename", filename);
Kevin Wolff54120f2014-05-26 11:09:59 +02001487 parse_filename = true;
1488 } else {
1489 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1490 "the same time");
1491 return -EINVAL;
1492 }
1493 }
1494
1495 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001496 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001497 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001498
Max Reitz053e1572015-08-26 19:47:51 +02001499 if (!drvname && protocol) {
1500 if (filename) {
1501 drv = bdrv_find_protocol(filename, parse_filename, errp);
1502 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001503 return -EINVAL;
1504 }
Max Reitz053e1572015-08-26 19:47:51 +02001505
1506 drvname = drv->format_name;
Eric Blake46f5ac22017-04-27 16:58:17 -05001507 qdict_put_str(*options, "driver", drvname);
Max Reitz053e1572015-08-26 19:47:51 +02001508 } else {
1509 error_setg(errp, "Must specify either driver or file");
1510 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001511 }
1512 }
1513
Kevin Wolf17b005f2014-05-27 10:50:29 +02001514 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001515
1516 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001517 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001518 drv->bdrv_parse_filename(filename, *options, &local_err);
1519 if (local_err) {
1520 error_propagate(errp, local_err);
1521 return -EINVAL;
1522 }
1523
1524 if (!drv->bdrv_needs_filename) {
1525 qdict_del(*options, "filename");
1526 }
1527 }
1528
1529 return 0;
1530}
1531
Fam Zhengc1cef672017-03-14 10:30:50 +08001532static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1533 GSList *ignore_children, Error **errp);
1534static void bdrv_child_abort_perm_update(BdrvChild *c);
1535static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1536
Fam Zhengffd1a5a2017-05-03 00:35:38 +08001537static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
1538 BdrvChild *c,
1539 const BdrvChildRole *role,
1540 uint64_t parent_perm, uint64_t parent_shared,
1541 uint64_t *nperm, uint64_t *nshared)
1542{
1543 if (bs->drv && bs->drv->bdrv_child_perm) {
1544 bs->drv->bdrv_child_perm(bs, c, role,
1545 parent_perm, parent_shared,
1546 nperm, nshared);
1547 }
1548 if (child_bs && child_bs->force_share) {
1549 *nshared = BLK_PERM_ALL;
1550 }
1551}
1552
Kevin Wolf33a610c2016-12-15 13:04:20 +01001553/*
1554 * Check whether permissions on this node can be changed in a way that
1555 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1556 * permissions of all its parents. This involves checking whether all necessary
1557 * permission changes to child nodes can be performed.
1558 *
1559 * A call to this function must always be followed by a call to bdrv_set_perm()
1560 * or bdrv_abort_perm_update().
1561 */
1562static int bdrv_check_perm(BlockDriverState *bs, uint64_t cumulative_perms,
Kevin Wolf46181122017-03-06 15:00:13 +01001563 uint64_t cumulative_shared_perms,
1564 GSList *ignore_children, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001565{
1566 BlockDriver *drv = bs->drv;
1567 BdrvChild *c;
1568 int ret;
1569
1570 /* Write permissions never work with read-only images */
1571 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
Kevin Wolf9c5e6592017-05-04 18:52:40 +02001572 !bdrv_is_writable(bs))
Kevin Wolf33a610c2016-12-15 13:04:20 +01001573 {
1574 error_setg(errp, "Block node is read-only");
1575 return -EPERM;
1576 }
1577
1578 /* Check this node */
1579 if (!drv) {
1580 return 0;
1581 }
1582
1583 if (drv->bdrv_check_perm) {
1584 return drv->bdrv_check_perm(bs, cumulative_perms,
1585 cumulative_shared_perms, errp);
1586 }
1587
Kevin Wolf78e421c2016-12-20 23:25:12 +01001588 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01001589 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01001590 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01001591 return 0;
1592 }
1593
1594 /* Check all children */
1595 QLIST_FOREACH(c, &bs->children, next) {
1596 uint64_t cur_perm, cur_shared;
Fam Zhengffd1a5a2017-05-03 00:35:38 +08001597 bdrv_child_perm(bs, c->bs, c, c->role,
1598 cumulative_perms, cumulative_shared_perms,
1599 &cur_perm, &cur_shared);
Kevin Wolf46181122017-03-06 15:00:13 +01001600 ret = bdrv_child_check_perm(c, cur_perm, cur_shared, ignore_children,
1601 errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01001602 if (ret < 0) {
1603 return ret;
1604 }
1605 }
1606
1607 return 0;
1608}
1609
1610/*
1611 * Notifies drivers that after a previous bdrv_check_perm() call, the
1612 * permission update is not performed and any preparations made for it (e.g.
1613 * taken file locks) need to be undone.
1614 *
1615 * This function recursively notifies all child nodes.
1616 */
1617static void bdrv_abort_perm_update(BlockDriverState *bs)
1618{
1619 BlockDriver *drv = bs->drv;
1620 BdrvChild *c;
1621
1622 if (!drv) {
1623 return;
1624 }
1625
1626 if (drv->bdrv_abort_perm_update) {
1627 drv->bdrv_abort_perm_update(bs);
1628 }
1629
1630 QLIST_FOREACH(c, &bs->children, next) {
1631 bdrv_child_abort_perm_update(c);
1632 }
1633}
1634
1635static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1636 uint64_t cumulative_shared_perms)
1637{
1638 BlockDriver *drv = bs->drv;
1639 BdrvChild *c;
1640
1641 if (!drv) {
1642 return;
1643 }
1644
1645 /* Update this node */
1646 if (drv->bdrv_set_perm) {
1647 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1648 }
1649
Kevin Wolf78e421c2016-12-20 23:25:12 +01001650 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01001651 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01001652 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01001653 return;
1654 }
1655
1656 /* Update all children */
1657 QLIST_FOREACH(c, &bs->children, next) {
1658 uint64_t cur_perm, cur_shared;
Fam Zhengffd1a5a2017-05-03 00:35:38 +08001659 bdrv_child_perm(bs, c->bs, c, c->role,
1660 cumulative_perms, cumulative_shared_perms,
1661 &cur_perm, &cur_shared);
Kevin Wolf33a610c2016-12-15 13:04:20 +01001662 bdrv_child_set_perm(c, cur_perm, cur_shared);
1663 }
1664}
1665
1666static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1667 uint64_t *shared_perm)
1668{
1669 BdrvChild *c;
1670 uint64_t cumulative_perms = 0;
1671 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1672
1673 QLIST_FOREACH(c, &bs->parents, next_parent) {
1674 cumulative_perms |= c->perm;
1675 cumulative_shared_perms &= c->shared_perm;
1676 }
1677
1678 *perm = cumulative_perms;
1679 *shared_perm = cumulative_shared_perms;
1680}
1681
Kevin Wolfd0833192017-01-16 18:26:20 +01001682static char *bdrv_child_user_desc(BdrvChild *c)
1683{
1684 if (c->role->get_parent_desc) {
1685 return c->role->get_parent_desc(c);
1686 }
1687
1688 return g_strdup("another user");
1689}
1690
Fam Zheng51761962017-05-03 00:35:36 +08001691char *bdrv_perm_names(uint64_t perm)
Kevin Wolfd0833192017-01-16 18:26:20 +01001692{
1693 struct perm_name {
1694 uint64_t perm;
1695 const char *name;
1696 } permissions[] = {
1697 { BLK_PERM_CONSISTENT_READ, "consistent read" },
1698 { BLK_PERM_WRITE, "write" },
1699 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1700 { BLK_PERM_RESIZE, "resize" },
1701 { BLK_PERM_GRAPH_MOD, "change children" },
1702 { 0, NULL }
1703 };
1704
1705 char *result = g_strdup("");
1706 struct perm_name *p;
1707
1708 for (p = permissions; p->name; p++) {
1709 if (perm & p->perm) {
1710 char *old = result;
1711 result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
1712 g_free(old);
1713 }
1714 }
1715
1716 return result;
1717}
1718
Kevin Wolf33a610c2016-12-15 13:04:20 +01001719/*
1720 * Checks whether a new reference to @bs can be added if the new user requires
Kevin Wolf46181122017-03-06 15:00:13 +01001721 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
1722 * set, the BdrvChild objects in this list are ignored in the calculations;
1723 * this allows checking permission updates for an existing reference.
Kevin Wolf33a610c2016-12-15 13:04:20 +01001724 *
1725 * Needs to be followed by a call to either bdrv_set_perm() or
1726 * bdrv_abort_perm_update(). */
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001727static int bdrv_check_update_perm(BlockDriverState *bs, uint64_t new_used_perm,
1728 uint64_t new_shared_perm,
Kevin Wolf46181122017-03-06 15:00:13 +01001729 GSList *ignore_children, Error **errp)
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001730{
1731 BdrvChild *c;
Kevin Wolf33a610c2016-12-15 13:04:20 +01001732 uint64_t cumulative_perms = new_used_perm;
1733 uint64_t cumulative_shared_perms = new_shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001734
1735 /* There is no reason why anyone couldn't tolerate write_unchanged */
1736 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
1737
1738 QLIST_FOREACH(c, &bs->parents, next_parent) {
Kevin Wolf46181122017-03-06 15:00:13 +01001739 if (g_slist_find(ignore_children, c)) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001740 continue;
1741 }
1742
Kevin Wolfd0833192017-01-16 18:26:20 +01001743 if ((new_used_perm & c->shared_perm) != new_used_perm) {
1744 char *user = bdrv_child_user_desc(c);
1745 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
1746 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
1747 "allow '%s' on %s",
1748 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1749 g_free(user);
1750 g_free(perm_names);
1751 return -EPERM;
1752 }
1753
1754 if ((c->perm & new_shared_perm) != c->perm) {
1755 char *user = bdrv_child_user_desc(c);
1756 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
1757 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
1758 "'%s' on %s",
1759 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1760 g_free(user);
1761 g_free(perm_names);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001762 return -EPERM;
1763 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01001764
1765 cumulative_perms |= c->perm;
1766 cumulative_shared_perms &= c->shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001767 }
1768
Kevin Wolf46181122017-03-06 15:00:13 +01001769 return bdrv_check_perm(bs, cumulative_perms, cumulative_shared_perms,
1770 ignore_children, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01001771}
1772
1773/* Needs to be followed by a call to either bdrv_child_set_perm() or
1774 * bdrv_child_abort_perm_update(). */
Fam Zhengc1cef672017-03-14 10:30:50 +08001775static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1776 GSList *ignore_children, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001777{
Kevin Wolf46181122017-03-06 15:00:13 +01001778 int ret;
1779
1780 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
1781 ret = bdrv_check_update_perm(c->bs, perm, shared, ignore_children, errp);
1782 g_slist_free(ignore_children);
1783
1784 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01001785}
1786
Fam Zhengc1cef672017-03-14 10:30:50 +08001787static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001788{
1789 uint64_t cumulative_perms, cumulative_shared_perms;
1790
1791 c->perm = perm;
1792 c->shared_perm = shared;
1793
1794 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
1795 &cumulative_shared_perms);
1796 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
1797}
1798
Fam Zhengc1cef672017-03-14 10:30:50 +08001799static void bdrv_child_abort_perm_update(BdrvChild *c)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001800{
1801 bdrv_abort_perm_update(c->bs);
1802}
1803
1804int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1805 Error **errp)
1806{
1807 int ret;
1808
Kevin Wolf46181122017-03-06 15:00:13 +01001809 ret = bdrv_child_check_perm(c, perm, shared, NULL, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01001810 if (ret < 0) {
1811 bdrv_child_abort_perm_update(c);
1812 return ret;
1813 }
1814
1815 bdrv_child_set_perm(c, perm, shared);
1816
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001817 return 0;
1818}
1819
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01001820#define DEFAULT_PERM_PASSTHROUGH (BLK_PERM_CONSISTENT_READ \
1821 | BLK_PERM_WRITE \
1822 | BLK_PERM_WRITE_UNCHANGED \
1823 | BLK_PERM_RESIZE)
1824#define DEFAULT_PERM_UNCHANGED (BLK_PERM_ALL & ~DEFAULT_PERM_PASSTHROUGH)
1825
1826void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
1827 const BdrvChildRole *role,
1828 uint64_t perm, uint64_t shared,
1829 uint64_t *nperm, uint64_t *nshared)
1830{
1831 if (c == NULL) {
1832 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
1833 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
1834 return;
1835 }
1836
1837 *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
1838 (c->perm & DEFAULT_PERM_UNCHANGED);
1839 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
1840 (c->shared_perm & DEFAULT_PERM_UNCHANGED);
1841}
1842
Kevin Wolf6b1a0442016-12-19 15:21:48 +01001843void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
1844 const BdrvChildRole *role,
1845 uint64_t perm, uint64_t shared,
1846 uint64_t *nperm, uint64_t *nshared)
1847{
1848 bool backing = (role == &child_backing);
1849 assert(role == &child_backing || role == &child_file);
1850
1851 if (!backing) {
1852 /* Apart from the modifications below, the same permissions are
1853 * forwarded and left alone as for filters */
1854 bdrv_filter_default_perms(bs, c, role, perm, shared, &perm, &shared);
1855
1856 /* Format drivers may touch metadata even if the guest doesn't write */
Kevin Wolf9c5e6592017-05-04 18:52:40 +02001857 if (bdrv_is_writable(bs)) {
Kevin Wolf6b1a0442016-12-19 15:21:48 +01001858 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
1859 }
1860
1861 /* bs->file always needs to be consistent because of the metadata. We
1862 * can never allow other users to resize or write to it. */
1863 perm |= BLK_PERM_CONSISTENT_READ;
1864 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
1865 } else {
1866 /* We want consistent read from backing files if the parent needs it.
1867 * No other operations are performed on backing files. */
1868 perm &= BLK_PERM_CONSISTENT_READ;
1869
1870 /* If the parent can deal with changing data, we're okay with a
1871 * writable and resizable backing file. */
1872 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
1873 if (shared & BLK_PERM_WRITE) {
1874 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
1875 } else {
1876 shared = 0;
1877 }
1878
1879 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
1880 BLK_PERM_WRITE_UNCHANGED;
1881 }
1882
Kevin Wolf9c5e6592017-05-04 18:52:40 +02001883 if (bs->open_flags & BDRV_O_INACTIVE) {
1884 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
1885 }
1886
Kevin Wolf6b1a0442016-12-19 15:21:48 +01001887 *nperm = perm;
1888 *nshared = shared;
1889}
1890
Kevin Wolf8ee03992017-03-06 13:45:28 +01001891static void bdrv_replace_child_noperm(BdrvChild *child,
1892 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001893{
1894 BlockDriverState *old_bs = child->bs;
1895
Fam Zhengbb2614e2017-04-07 14:54:10 +08001896 if (old_bs && new_bs) {
1897 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
1898 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001899 if (old_bs) {
Kevin Wolf36fe1332016-05-17 14:51:55 +02001900 if (old_bs->quiesce_counter && child->role->drained_end) {
1901 child->role->drained_end(child);
1902 }
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001903 if (child->role->detach) {
1904 child->role->detach(child);
1905 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001906 QLIST_REMOVE(child, next_parent);
1907 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001908
1909 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02001910
1911 if (new_bs) {
1912 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
1913 if (new_bs->quiesce_counter && child->role->drained_begin) {
1914 child->role->drained_begin(child);
1915 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01001916
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001917 if (child->role->attach) {
1918 child->role->attach(child);
1919 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02001920 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001921}
1922
Kevin Wolf466787f2017-03-08 14:44:07 +01001923/*
1924 * Updates @child to change its reference to point to @new_bs, including
1925 * checking and applying the necessary permisson updates both to the old node
1926 * and to @new_bs.
1927 *
1928 * NULL is passed as @new_bs for removing the reference before freeing @child.
1929 *
1930 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
1931 * function uses bdrv_set_perm() to update the permissions according to the new
1932 * reference that @new_bs gets.
1933 */
1934static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
Kevin Wolf8ee03992017-03-06 13:45:28 +01001935{
1936 BlockDriverState *old_bs = child->bs;
1937 uint64_t perm, shared_perm;
1938
Kevin Wolf8aecf1d2017-08-03 17:02:57 +02001939 bdrv_replace_child_noperm(child, new_bs);
1940
Kevin Wolf8ee03992017-03-06 13:45:28 +01001941 if (old_bs) {
1942 /* Update permissions for old node. This is guaranteed to succeed
1943 * because we're just taking a parent away, so we're loosening
1944 * restrictions. */
1945 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
Kevin Wolf46181122017-03-06 15:00:13 +01001946 bdrv_check_perm(old_bs, perm, shared_perm, NULL, &error_abort);
Kevin Wolf8ee03992017-03-06 13:45:28 +01001947 bdrv_set_perm(old_bs, perm, shared_perm);
1948 }
1949
Kevin Wolf8ee03992017-03-06 13:45:28 +01001950 if (new_bs) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001951 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
Kevin Wolff54120f2014-05-26 11:09:59 +02001952 bdrv_set_perm(new_bs, perm, shared_perm);
Kevin Wolff54120f2014-05-26 11:09:59 +02001953 }
1954}
1955
Kevin Wolff21d96d2016-03-08 13:47:46 +01001956BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1957 const char *child_name,
Kevin Wolf36fe1332016-05-17 14:51:55 +02001958 const BdrvChildRole *child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001959 uint64_t perm, uint64_t shared_perm,
1960 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02001961{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001962 BdrvChild *child;
1963 int ret;
1964
1965 ret = bdrv_check_update_perm(child_bs, perm, shared_perm, NULL, errp);
1966 if (ret < 0) {
Kevin Wolf33a610c2016-12-15 13:04:20 +01001967 bdrv_abort_perm_update(child_bs);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001968 return NULL;
1969 }
1970
1971 child = g_new(BdrvChild, 1);
Kevin Wolfdf581792015-06-15 11:53:47 +02001972 *child = (BdrvChild) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001973 .bs = NULL,
1974 .name = g_strdup(child_name),
1975 .role = child_role,
1976 .perm = perm,
1977 .shared_perm = shared_perm,
1978 .opaque = opaque,
Kevin Wolfdf581792015-06-15 11:53:47 +02001979 };
1980
Kevin Wolf33a610c2016-12-15 13:04:20 +01001981 /* This performs the matching bdrv_set_perm() for the above check. */
Kevin Wolf466787f2017-03-08 14:44:07 +01001982 bdrv_replace_child(child, child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02001983
1984 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02001985}
1986
Wen Congyang98292c62016-05-10 15:36:38 +08001987BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1988 BlockDriverState *child_bs,
1989 const char *child_name,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01001990 const BdrvChildRole *child_role,
1991 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01001992{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001993 BdrvChild *child;
Kevin Wolff68c5982016-12-20 15:51:12 +01001994 uint64_t perm, shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001995
Kevin Wolff68c5982016-12-20 15:51:12 +01001996 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
1997
1998 assert(parent_bs->drv);
Fam Zhengbb2614e2017-04-07 14:54:10 +08001999 assert(bdrv_get_aio_context(parent_bs) == bdrv_get_aio_context(child_bs));
Fam Zhengffd1a5a2017-05-03 00:35:38 +08002000 bdrv_child_perm(parent_bs, child_bs, NULL, child_role,
2001 perm, shared_perm, &perm, &shared_perm);
Kevin Wolff68c5982016-12-20 15:51:12 +01002002
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002003 child = bdrv_root_attach_child(child_bs, child_name, child_role,
Kevin Wolff68c5982016-12-20 15:51:12 +01002004 perm, shared_perm, parent_bs, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01002005 if (child == NULL) {
2006 return NULL;
2007 }
2008
Kevin Wolff21d96d2016-03-08 13:47:46 +01002009 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2010 return child;
2011}
2012
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02002013static void bdrv_detach_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02002014{
Kevin Wolff21d96d2016-03-08 13:47:46 +01002015 if (child->next.le_prev) {
2016 QLIST_REMOVE(child, next);
2017 child->next.le_prev = NULL;
2018 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002019
Kevin Wolf466787f2017-03-08 14:44:07 +01002020 bdrv_replace_child(child, NULL);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02002021
Kevin Wolf260fecf2015-04-27 13:46:22 +02002022 g_free(child->name);
Kevin Wolf33a60402015-06-15 13:51:04 +02002023 g_free(child);
2024}
2025
Kevin Wolff21d96d2016-03-08 13:47:46 +01002026void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02002027{
Kevin Wolf779020c2015-10-13 14:09:44 +02002028 BlockDriverState *child_bs;
2029
Kevin Wolff21d96d2016-03-08 13:47:46 +01002030 child_bs = child->bs;
2031 bdrv_detach_child(child);
2032 bdrv_unref(child_bs);
2033}
2034
2035void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2036{
Kevin Wolf779020c2015-10-13 14:09:44 +02002037 if (child == NULL) {
2038 return;
2039 }
Kevin Wolf33a60402015-06-15 13:51:04 +02002040
2041 if (child->bs->inherits_from == parent) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002042 BdrvChild *c;
2043
2044 /* Remove inherits_from only when the last reference between parent and
2045 * child->bs goes away. */
2046 QLIST_FOREACH(c, &parent->children, next) {
2047 if (c != child && c->bs == child->bs) {
2048 break;
2049 }
2050 }
2051 if (c == NULL) {
2052 child->bs->inherits_from = NULL;
2053 }
Kevin Wolf33a60402015-06-15 13:51:04 +02002054 }
2055
Kevin Wolff21d96d2016-03-08 13:47:46 +01002056 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02002057}
2058
Kevin Wolf5c8cab42016-02-24 15:13:35 +01002059
2060static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2061{
2062 BdrvChild *c;
2063 QLIST_FOREACH(c, &bs->parents, next_parent) {
2064 if (c->role->change_media) {
2065 c->role->change_media(c, load);
2066 }
2067 }
2068}
2069
2070static void bdrv_parent_cb_resize(BlockDriverState *bs)
2071{
2072 BdrvChild *c;
2073 QLIST_FOREACH(c, &bs->parents, next_parent) {
2074 if (c->role->resize) {
2075 c->role->resize(c);
2076 }
2077 }
2078}
2079
Kevin Wolf5db15a52015-09-14 15:33:33 +02002080/*
2081 * Sets the backing file link of a BDS. A new reference is created; callers
2082 * which don't need their own reference any more must call bdrv_unref().
2083 */
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002084void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2085 Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08002086{
Kevin Wolf5db15a52015-09-14 15:33:33 +02002087 if (backing_hd) {
2088 bdrv_ref(backing_hd);
2089 }
Fam Zheng8d24cce2014-05-23 21:29:45 +08002090
Kevin Wolf760e0062015-06-17 14:55:21 +02002091 if (bs->backing) {
Kevin Wolf5db15a52015-09-14 15:33:33 +02002092 bdrv_unref_child(bs, bs->backing);
Fam Zheng826b6ca2014-05-23 21:29:47 +08002093 }
2094
Fam Zheng8d24cce2014-05-23 21:29:45 +08002095 if (!backing_hd) {
Kevin Wolf760e0062015-06-17 14:55:21 +02002096 bs->backing = NULL;
Fam Zheng8d24cce2014-05-23 21:29:45 +08002097 goto out;
2098 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002099
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002100 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002101 errp);
2102 if (!bs->backing) {
2103 bdrv_unref(backing_hd);
2104 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08002105
Kevin Wolf9e7e9402017-03-09 11:45:39 +01002106 bdrv_refresh_filename(bs);
2107
Fam Zheng8d24cce2014-05-23 21:29:45 +08002108out:
Kevin Wolf3baca892014-07-16 17:48:16 +02002109 bdrv_refresh_limits(bs, NULL);
Fam Zheng8d24cce2014-05-23 21:29:45 +08002110}
2111
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002112/*
2113 * Opens the backing file for a BlockDriverState if not yet open
2114 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002115 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2116 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2117 * itself, all options starting with "${bdref_key}." are considered part of the
2118 * BlockdevRef.
2119 *
2120 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002121 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002122int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2123 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02002124{
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002125 char *backing_filename = g_malloc0(PATH_MAX);
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002126 char *bdref_key_dot;
2127 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02002128 int ret = 0;
Fam Zheng8d24cce2014-05-23 21:29:45 +08002129 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002130 QDict *options;
2131 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002132 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002133
Kevin Wolf760e0062015-06-17 14:55:21 +02002134 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002135 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002136 }
2137
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002138 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002139 if (parent_options == NULL) {
2140 tmp_parent_options = qdict_new();
2141 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002142 }
2143
Paolo Bonzini9156df12012-10-18 16:49:17 +02002144 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002145
2146 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2147 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2148 g_free(bdref_key_dot);
2149
Markus Armbruster129c7d12017-03-30 19:43:12 +02002150 /*
2151 * Caution: while qdict_get_try_str() is fine, getting non-string
2152 * types would require more care. When @parent_options come from
2153 * -blockdev or blockdev_add, its members are typed according to
2154 * the QAPI schema, but when they come from -drive, they're all
2155 * QString.
2156 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002157 reference = qdict_get_try_str(parent_options, bdref_key);
2158 if (reference || qdict_haskey(options, "file.filename")) {
Kevin Wolf1cb6f502013-04-12 20:27:07 +02002159 backing_filename[0] = '\0';
2160 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002161 QDECREF(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002162 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08002163 } else {
Max Reitz9f074292014-11-26 17:20:26 +01002164 bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
2165 &local_err);
2166 if (local_err) {
2167 ret = -EINVAL;
2168 error_propagate(errp, local_err);
2169 QDECREF(options);
2170 goto free_exit;
2171 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02002172 }
2173
Kevin Wolf8ee79e72014-06-04 15:09:35 +02002174 if (!bs->drv || !bs->drv->supports_backing) {
2175 ret = -EINVAL;
2176 error_setg(errp, "Driver doesn't support backing files");
2177 QDECREF(options);
2178 goto free_exit;
2179 }
2180
Kevin Wolfc5f6e492014-11-25 18:12:42 +01002181 if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002182 qdict_put_str(options, "driver", bs->backing_format);
Paolo Bonzini9156df12012-10-18 16:49:17 +02002183 }
2184
Max Reitz5b363932016-05-17 16:41:31 +02002185 backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
2186 reference, options, 0, bs, &child_backing,
2187 errp);
2188 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02002189 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01002190 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02002191 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002192 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002193 }
sochin.jiang5ce6bfe2017-06-26 19:04:24 +08002194 bdrv_set_aio_context(backing_hd, bdrv_get_aio_context(bs));
Kevin Wolfdf581792015-06-15 11:53:47 +02002195
Kevin Wolf5db15a52015-09-14 15:33:33 +02002196 /* Hook up the backing file link; drop our reference, bs owns the
2197 * backing_hd reference now */
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002198 bdrv_set_backing_hd(bs, backing_hd, &local_err);
Kevin Wolf5db15a52015-09-14 15:33:33 +02002199 bdrv_unref(backing_hd);
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002200 if (local_err) {
Fam Zheng8cd1a3e2017-03-17 09:56:30 +08002201 error_propagate(errp, local_err);
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002202 ret = -EINVAL;
2203 goto free_exit;
2204 }
Peter Feinerd80ac652014-01-08 19:43:25 +00002205
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002206 qdict_del(parent_options, bdref_key);
2207
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002208free_exit:
2209 g_free(backing_filename);
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002210 QDECREF(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002211 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002212}
2213
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002214static BlockDriverState *
2215bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2216 BlockDriverState *parent, const BdrvChildRole *child_role,
2217 bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01002218{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002219 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01002220 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01002221 char *bdref_key_dot;
2222 const char *reference;
2223
Kevin Wolfdf581792015-06-15 11:53:47 +02002224 assert(child_role != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01002225
Max Reitzda557aa2013-12-20 19:28:11 +01002226 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2227 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2228 g_free(bdref_key_dot);
2229
Markus Armbruster129c7d12017-03-30 19:43:12 +02002230 /*
2231 * Caution: while qdict_get_try_str() is fine, getting non-string
2232 * types would require more care. When @options come from
2233 * -blockdev or blockdev_add, its members are typed according to
2234 * the QAPI schema, but when they come from -drive, they're all
2235 * QString.
2236 */
Max Reitzda557aa2013-12-20 19:28:11 +01002237 reference = qdict_get_try_str(options, bdref_key);
2238 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02002239 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01002240 error_setg(errp, "A block device must be specified for \"%s\"",
2241 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01002242 }
Markus Armbrusterb20e61e2014-05-28 11:16:57 +02002243 QDECREF(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01002244 goto done;
2245 }
2246
Max Reitz5b363932016-05-17 16:41:31 +02002247 bs = bdrv_open_inherit(filename, reference, image_options, 0,
2248 parent, child_role, errp);
2249 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02002250 goto done;
2251 }
2252
Max Reitzda557aa2013-12-20 19:28:11 +01002253done:
2254 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002255 return bs;
2256}
2257
2258/*
2259 * Opens a disk image whose options are given as BlockdevRef in another block
2260 * device's options.
2261 *
2262 * If allow_none is true, no image will be opened if filename is false and no
2263 * BlockdevRef is given. NULL will be returned, but errp remains unset.
2264 *
2265 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2266 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2267 * itself, all options starting with "${bdref_key}." are considered part of the
2268 * BlockdevRef.
2269 *
2270 * The BlockdevRef will be removed from the options QDict.
2271 */
2272BdrvChild *bdrv_open_child(const char *filename,
2273 QDict *options, const char *bdref_key,
2274 BlockDriverState *parent,
2275 const BdrvChildRole *child_role,
2276 bool allow_none, Error **errp)
2277{
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002278 BdrvChild *c;
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002279 BlockDriverState *bs;
2280
2281 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2282 allow_none, errp);
2283 if (bs == NULL) {
2284 return NULL;
2285 }
2286
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002287 c = bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
2288 if (!c) {
2289 bdrv_unref(bs);
2290 return NULL;
2291 }
2292
2293 return c;
Kevin Wolfb4b059f2015-06-15 13:24:19 +02002294}
2295
Max Reitz66836182016-05-17 16:41:27 +02002296static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2297 int flags,
2298 QDict *snapshot_options,
2299 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02002300{
2301 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002302 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02002303 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08002304 QemuOpts *opts = NULL;
Eric Blakeff6ed712017-04-27 16:58:18 -05002305 BlockDriverState *bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01002306 Error *local_err = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02002307 int ret;
2308
2309 /* if snapshot, we create a temporary backing file and open it
2310 instead of opening 'filename' directly */
2311
2312 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02002313 total_size = bdrv_getlength(bs);
2314 if (total_size < 0) {
2315 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002316 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02002317 }
Kevin Wolfb9988752014-04-03 12:09:34 +02002318
2319 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002320 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02002321 if (ret < 0) {
2322 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002323 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02002324 }
2325
Max Reitzef810432014-12-02 18:32:42 +01002326 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002327 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01002328 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01002329 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08002330 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02002331 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01002332 error_prepend(errp, "Could not create temporary overlay '%s': ",
2333 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002334 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02002335 }
2336
Kevin Wolf73176be2016-03-07 13:02:15 +01002337 /* Prepare options QDict for the temporary file */
Eric Blake46f5ac22017-04-27 16:58:17 -05002338 qdict_put_str(snapshot_options, "file.driver", "file");
2339 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
2340 qdict_put_str(snapshot_options, "driver", "qcow2");
Kevin Wolfb9988752014-04-03 12:09:34 +02002341
Max Reitz5b363932016-05-17 16:41:31 +02002342 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01002343 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02002344 if (!bs_snapshot) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002345 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02002346 }
2347
Eric Blakeff6ed712017-04-27 16:58:18 -05002348 /* bdrv_append() consumes a strong reference to bs_snapshot
2349 * (i.e. it will call bdrv_unref() on it) even on error, so in
2350 * order to be able to return one, we have to increase
2351 * bs_snapshot's refcount here */
Max Reitz66836182016-05-17 16:41:27 +02002352 bdrv_ref(bs_snapshot);
Kevin Wolfb2c28322017-02-20 12:46:42 +01002353 bdrv_append(bs_snapshot, bs, &local_err);
2354 if (local_err) {
2355 error_propagate(errp, local_err);
Eric Blakeff6ed712017-04-27 16:58:18 -05002356 bs_snapshot = NULL;
Kevin Wolfb2c28322017-02-20 12:46:42 +01002357 goto out;
2358 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002359
2360out:
Kevin Wolf73176be2016-03-07 13:02:15 +01002361 QDECREF(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002362 g_free(tmp_filename);
Eric Blakeff6ed712017-04-27 16:58:18 -05002363 return bs_snapshot;
Kevin Wolfb9988752014-04-03 12:09:34 +02002364}
2365
Max Reitzda557aa2013-12-20 19:28:11 +01002366/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002367 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002368 *
2369 * options is a QDict of options to pass to the block drivers, or NULL for an
2370 * empty set of options. The reference to the QDict belongs to the block layer
2371 * after the call (even on failure), so if the caller intends to reuse the
2372 * dictionary, it needs to use QINCREF() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01002373 *
2374 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2375 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01002376 *
2377 * The reference parameter may be used to specify an existing block device which
2378 * should be opened. If specified, neither options nor a filename may be given,
2379 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002380 */
Max Reitz5b363932016-05-17 16:41:31 +02002381static BlockDriverState *bdrv_open_inherit(const char *filename,
2382 const char *reference,
2383 QDict *options, int flags,
2384 BlockDriverState *parent,
2385 const BdrvChildRole *child_role,
2386 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00002387{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002388 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002389 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02002390 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02002391 BlockDriver *drv = NULL;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02002392 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02002393 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002394 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01002395 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02002396 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00002397
Kevin Wolff3930ed2015-04-08 13:43:47 +02002398 assert(!child_role || !flags);
2399 assert(!child_role == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01002400
Max Reitzddf56362014-02-18 18:33:06 +01002401 if (reference) {
2402 bool options_non_empty = options ? qdict_size(options) : false;
2403 QDECREF(options);
2404
Max Reitzddf56362014-02-18 18:33:06 +01002405 if (filename || options_non_empty) {
2406 error_setg(errp, "Cannot reference an existing block device with "
2407 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02002408 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01002409 }
2410
2411 bs = bdrv_lookup_bs(reference, reference, errp);
2412 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02002413 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01002414 }
Kevin Wolf76b22322016-04-04 17:11:13 +02002415
Max Reitzddf56362014-02-18 18:33:06 +01002416 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02002417 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01002418 }
2419
Max Reitz5b363932016-05-17 16:41:31 +02002420 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01002421
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002422 /* NULL means an empty set of options */
2423 if (options == NULL) {
2424 options = qdict_new();
2425 }
2426
Kevin Wolf145f5982015-05-08 16:15:03 +02002427 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002428 parse_json_protocol(options, &filename, &local_err);
2429 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002430 goto fail;
2431 }
2432
Kevin Wolf145f5982015-05-08 16:15:03 +02002433 bs->explicit_options = qdict_clone_shallow(options);
2434
Kevin Wolff3930ed2015-04-08 13:43:47 +02002435 if (child_role) {
Kevin Wolfbddcec32015-04-09 18:47:50 +02002436 bs->inherits_from = parent;
Kevin Wolf8e2160e2015-04-29 17:29:39 +02002437 child_role->inherit_options(&flags, options,
2438 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02002439 }
2440
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002441 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Kevin Wolf462f5bc2014-05-26 11:39:55 +02002442 if (local_err) {
2443 goto fail;
2444 }
2445
Markus Armbruster129c7d12017-03-30 19:43:12 +02002446 /*
2447 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
2448 * Caution: getting a boolean member of @options requires care.
2449 * When @options come from -blockdev or blockdev_add, members are
2450 * typed according to the QAPI schema, but when they come from
2451 * -drive, they're all QString.
2452 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03002453 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
2454 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
2455 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
2456 } else {
2457 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03002458 }
2459
2460 if (flags & BDRV_O_SNAPSHOT) {
2461 snapshot_options = qdict_new();
2462 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
2463 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03002464 /* Let bdrv_backing_options() override "read-only" */
2465 qdict_del(options, BDRV_OPT_READ_ONLY);
Alberto Garcia14499ea2016-09-15 17:53:00 +03002466 bdrv_backing_options(&flags, options, flags, options);
2467 }
2468
Kevin Wolf62392eb2015-04-24 16:38:02 +02002469 bs->open_flags = flags;
2470 bs->options = options;
2471 options = qdict_clone_shallow(options);
2472
Kevin Wolf76c591b2014-06-04 14:19:44 +02002473 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02002474 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02002475 drvname = qdict_get_try_str(options, "driver");
2476 if (drvname) {
2477 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02002478 if (!drv) {
2479 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02002480 goto fail;
2481 }
2482 }
2483
2484 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02002485
Markus Armbruster129c7d12017-03-30 19:43:12 +02002486 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02002487 backing = qdict_get_try_str(options, "backing");
2488 if (backing && *backing == '\0') {
2489 flags |= BDRV_O_NO_BACKING;
2490 qdict_del(options, "backing");
2491 }
2492
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002493 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002494 * probing, the block drivers will do their own bdrv_open_child() for the
2495 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02002496 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002497 BlockDriverState *file_bs;
2498
2499 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
2500 &child_file, true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02002501 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01002502 goto fail;
2503 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002504 if (file_bs != NULL) {
Kevin Wolf6d0eb642017-01-20 17:07:26 +01002505 file = blk_new(BLK_PERM_CONSISTENT_READ, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01002506 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002507 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01002508 if (local_err) {
2509 goto fail;
2510 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002511
Eric Blake46f5ac22017-04-27 16:58:17 -05002512 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002513 }
Max Reitz5469a2a2014-02-18 18:33:10 +01002514 }
2515
Kevin Wolf76c591b2014-06-04 14:19:44 +02002516 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01002517 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02002518 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02002519 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02002520 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02002521 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01002522 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02002523 /*
2524 * This option update would logically belong in bdrv_fill_options(),
2525 * but we first need to open bs->file for the probing to work, while
2526 * opening bs->file already requires the (mostly) final set of options
2527 * so that cache mode etc. can be inherited.
2528 *
2529 * Adding the driver later is somewhat ugly, but it's not an option
2530 * that would ever be inherited, so it's correct. We just need to make
2531 * sure to update both bs->options (which has the full effective
2532 * options for bs) and options (which has file.* already removed).
2533 */
Eric Blake46f5ac22017-04-27 16:58:17 -05002534 qdict_put_str(bs->options, "driver", drv->format_name);
2535 qdict_put_str(options, "driver", drv->format_name);
Kevin Wolf76c591b2014-06-04 14:19:44 +02002536 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02002537 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02002538 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01002539 }
2540
Max Reitz53a29512015-03-19 14:53:16 -04002541 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
2542 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
2543 /* file must be NULL if a protocol BDS is about to be created
2544 * (the inverse results in an error message from bdrv_open_common()) */
2545 assert(!(flags & BDRV_O_PROTOCOL) || !file);
2546
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002547 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01002548 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002549 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02002550 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01002551 }
2552
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002553 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002554 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01002555 file = NULL;
2556 }
2557
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002558 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02002559 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002560 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002561 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002562 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002563 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002564 }
2565
Max Reitz91af7012014-07-18 20:24:56 +02002566 bdrv_refresh_filename(bs);
2567
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002568 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01002569 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002570 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01002571 if (flags & BDRV_O_PROTOCOL) {
2572 error_setg(errp, "Block protocol '%s' doesn't support the option "
2573 "'%s'", drv->format_name, entry->key);
2574 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01002575 error_setg(errp,
2576 "Block format '%s' does not support the option '%s'",
2577 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01002578 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002579
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002580 goto close_and_fail;
2581 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002582
Daniel P. Berrangec01c2142017-06-23 17:24:16 +01002583 bdrv_parent_cb_change_media(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002584
Markus Armbrusterc3adb582014-03-14 09:22:48 +01002585 QDECREF(options);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02002586
2587 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
2588 * temporary snapshot afterwards. */
2589 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02002590 BlockDriverState *snapshot_bs;
2591 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
2592 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01002593 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02002594 if (local_err) {
2595 goto close_and_fail;
2596 }
Max Reitz5b363932016-05-17 16:41:31 +02002597 /* We are not going to return bs but the overlay on top of it
2598 * (snapshot_bs); thus, we have to drop the strong reference to bs
2599 * (which we obtained by calling bdrv_new()). bs will not be deleted,
2600 * though, because the overlay still has a reference to it. */
2601 bdrv_unref(bs);
2602 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02002603 }
2604
Max Reitz5b363932016-05-17 16:41:31 +02002605 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002606
Kevin Wolf8bfea152014-04-11 19:16:36 +02002607fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002608 blk_unref(file);
Kevin Wolf73176be2016-03-07 13:02:15 +01002609 QDECREF(snapshot_options);
Kevin Wolf145f5982015-05-08 16:15:03 +02002610 QDECREF(bs->explicit_options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002611 QDECREF(bs->options);
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002612 QDECREF(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002613 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03002614 bs->explicit_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02002615 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03002616 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02002617 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002618
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002619close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02002620 bdrv_unref(bs);
Kevin Wolf73176be2016-03-07 13:02:15 +01002621 QDECREF(snapshot_options);
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002622 QDECREF(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03002623 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02002624 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002625}
2626
Max Reitz5b363932016-05-17 16:41:31 +02002627BlockDriverState *bdrv_open(const char *filename, const char *reference,
2628 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02002629{
Max Reitz5b363932016-05-17 16:41:31 +02002630 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitzce343772015-08-26 19:47:50 +02002631 NULL, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02002632}
2633
Jeff Codye971aa12012-09-20 15:13:19 -04002634typedef struct BlockReopenQueueEntry {
2635 bool prepared;
2636 BDRVReopenState state;
2637 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
2638} BlockReopenQueueEntry;
2639
2640/*
2641 * Adds a BlockDriverState to a simple queue for an atomic, transactional
2642 * reopen of multiple devices.
2643 *
2644 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
2645 * already performed, or alternatively may be NULL a new BlockReopenQueue will
2646 * be created and initialized. This newly created BlockReopenQueue should be
2647 * passed back in for subsequent calls that are intended to be of the same
2648 * atomic 'set'.
2649 *
2650 * bs is the BlockDriverState to add to the reopen queue.
2651 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002652 * options contains the changed options for the associated bs
2653 * (the BlockReopenQueue takes ownership)
2654 *
Jeff Codye971aa12012-09-20 15:13:19 -04002655 * flags contains the open flags for the associated bs
2656 *
2657 * returns a pointer to bs_queue, which is either the newly allocated
2658 * bs_queue, or the existing bs_queue being used.
2659 *
2660 */
Kevin Wolf28518102015-05-08 17:07:31 +02002661static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
2662 BlockDriverState *bs,
2663 QDict *options,
2664 int flags,
2665 const BdrvChildRole *role,
2666 QDict *parent_options,
2667 int parent_flags)
Jeff Codye971aa12012-09-20 15:13:19 -04002668{
2669 assert(bs != NULL);
2670
2671 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02002672 BdrvChild *child;
Kevin Wolf145f5982015-05-08 16:15:03 +02002673 QDict *old_options, *explicit_options;
Kevin Wolf67251a32015-04-09 18:54:04 +02002674
Jeff Codye971aa12012-09-20 15:13:19 -04002675 if (bs_queue == NULL) {
2676 bs_queue = g_new0(BlockReopenQueue, 1);
2677 QSIMPLEQ_INIT(bs_queue);
2678 }
2679
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002680 if (!options) {
2681 options = qdict_new();
2682 }
2683
Alberto Garcia5b7ba052016-09-15 17:53:03 +03002684 /* Check if this BlockDriverState is already in the queue */
2685 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2686 if (bs == bs_entry->state.bs) {
2687 break;
2688 }
2689 }
2690
Kevin Wolf28518102015-05-08 17:07:31 +02002691 /*
2692 * Precedence of options:
2693 * 1. Explicitly passed in options (highest)
Kevin Wolf91a097e2015-05-08 17:49:53 +02002694 * 2. Set in flags (only for top level)
Kevin Wolf145f5982015-05-08 16:15:03 +02002695 * 3. Retained from explicitly set options of bs
Kevin Wolf8e2160e2015-04-29 17:29:39 +02002696 * 4. Inherited from parent node
Kevin Wolf28518102015-05-08 17:07:31 +02002697 * 5. Retained from effective options of bs
2698 */
2699
Kevin Wolf91a097e2015-05-08 17:49:53 +02002700 if (!parent_options) {
2701 /*
2702 * Any setting represented by flags is always updated. If the
2703 * corresponding QDict option is set, it takes precedence. Otherwise
2704 * the flag is translated into a QDict option. The old setting of bs is
2705 * not considered.
2706 */
2707 update_options_from_flags(options, flags);
2708 }
2709
Kevin Wolf145f5982015-05-08 16:15:03 +02002710 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia5b7ba052016-09-15 17:53:03 +03002711 if (bs_entry) {
2712 old_options = qdict_clone_shallow(bs_entry->state.explicit_options);
2713 } else {
2714 old_options = qdict_clone_shallow(bs->explicit_options);
2715 }
Kevin Wolf145f5982015-05-08 16:15:03 +02002716 bdrv_join_options(bs, options, old_options);
2717 QDECREF(old_options);
2718
2719 explicit_options = qdict_clone_shallow(options);
2720
Kevin Wolf28518102015-05-08 17:07:31 +02002721 /* Inherit from parent node */
2722 if (parent_options) {
2723 assert(!flags);
Kevin Wolf8e2160e2015-04-29 17:29:39 +02002724 role->inherit_options(&flags, options, parent_flags, parent_options);
Kevin Wolf28518102015-05-08 17:07:31 +02002725 }
2726
2727 /* Old values are used for options that aren't set yet */
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002728 old_options = qdict_clone_shallow(bs->options);
Kevin Wolfcddff5b2015-11-16 16:43:27 +01002729 bdrv_join_options(bs, options, old_options);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002730 QDECREF(old_options);
2731
Kevin Wolff1f25a22014-04-25 19:04:55 +02002732 /* bdrv_open() masks this flag out */
2733 flags &= ~BDRV_O_PROTOCOL;
2734
Kevin Wolf67251a32015-04-09 18:54:04 +02002735 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02002736 QDict *new_child_options;
2737 char *child_key_dot;
Kevin Wolf67251a32015-04-09 18:54:04 +02002738
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02002739 /* reopen can only change the options of block devices that were
2740 * implicitly created and inherited options. For other (referenced)
2741 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02002742 if (child->bs->inherits_from != bs) {
2743 continue;
2744 }
2745
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02002746 child_key_dot = g_strdup_printf("%s.", child->name);
2747 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
2748 g_free(child_key_dot);
2749
Kevin Wolf28518102015-05-08 17:07:31 +02002750 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
2751 child->role, options, flags);
Jeff Codye971aa12012-09-20 15:13:19 -04002752 }
2753
Alberto Garcia5b7ba052016-09-15 17:53:03 +03002754 if (!bs_entry) {
2755 bs_entry = g_new0(BlockReopenQueueEntry, 1);
2756 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
2757 } else {
2758 QDECREF(bs_entry->state.options);
2759 QDECREF(bs_entry->state.explicit_options);
2760 }
Jeff Codye971aa12012-09-20 15:13:19 -04002761
2762 bs_entry->state.bs = bs;
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002763 bs_entry->state.options = options;
Kevin Wolf145f5982015-05-08 16:15:03 +02002764 bs_entry->state.explicit_options = explicit_options;
Jeff Codye971aa12012-09-20 15:13:19 -04002765 bs_entry->state.flags = flags;
2766
2767 return bs_queue;
2768}
2769
Kevin Wolf28518102015-05-08 17:07:31 +02002770BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
2771 BlockDriverState *bs,
2772 QDict *options, int flags)
2773{
2774 return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
2775 NULL, NULL, 0);
2776}
2777
Jeff Codye971aa12012-09-20 15:13:19 -04002778/*
2779 * Reopen multiple BlockDriverStates atomically & transactionally.
2780 *
2781 * The queue passed in (bs_queue) must have been built up previous
2782 * via bdrv_reopen_queue().
2783 *
2784 * Reopens all BDS specified in the queue, with the appropriate
2785 * flags. All devices are prepared for reopen, and failure of any
2786 * device will cause all device changes to be abandonded, and intermediate
2787 * data cleaned up.
2788 *
2789 * If all devices prepare successfully, then the changes are committed
2790 * to all devices.
2791 *
2792 */
Paolo Bonzini720150f2016-10-27 12:49:02 +02002793int bdrv_reopen_multiple(AioContext *ctx, BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04002794{
2795 int ret = -1;
2796 BlockReopenQueueEntry *bs_entry, *next;
2797 Error *local_err = NULL;
2798
2799 assert(bs_queue != NULL);
2800
Paolo Bonzinic9d1a562016-10-27 12:49:05 +02002801 aio_context_release(ctx);
Alberto Garcia40840e42016-10-28 10:08:03 +03002802 bdrv_drain_all_begin();
Paolo Bonzinic9d1a562016-10-27 12:49:05 +02002803 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04002804
2805 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2806 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
2807 error_propagate(errp, local_err);
2808 goto cleanup;
2809 }
2810 bs_entry->prepared = true;
2811 }
2812
2813 /* If we reach this point, we have success and just need to apply the
2814 * changes
2815 */
2816 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2817 bdrv_reopen_commit(&bs_entry->state);
2818 }
2819
2820 ret = 0;
2821
2822cleanup:
2823 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
2824 if (ret && bs_entry->prepared) {
2825 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf145f5982015-05-08 16:15:03 +02002826 } else if (ret) {
2827 QDECREF(bs_entry->state.explicit_options);
Jeff Codye971aa12012-09-20 15:13:19 -04002828 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002829 QDECREF(bs_entry->state.options);
Jeff Codye971aa12012-09-20 15:13:19 -04002830 g_free(bs_entry);
2831 }
2832 g_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03002833
2834 bdrv_drain_all_end();
2835
Jeff Codye971aa12012-09-20 15:13:19 -04002836 return ret;
2837}
2838
2839
2840/* Reopen a single BlockDriverState with the specified flags. */
2841int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
2842{
2843 int ret = -1;
2844 Error *local_err = NULL;
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002845 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
Jeff Codye971aa12012-09-20 15:13:19 -04002846
Paolo Bonzini720150f2016-10-27 12:49:02 +02002847 ret = bdrv_reopen_multiple(bdrv_get_aio_context(bs), queue, &local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04002848 if (local_err != NULL) {
2849 error_propagate(errp, local_err);
2850 }
2851 return ret;
2852}
2853
2854
2855/*
2856 * Prepares a BlockDriverState for reopen. All changes are staged in the
2857 * 'opaque' field of the BDRVReopenState, which is used and allocated by
2858 * the block driver layer .bdrv_reopen_prepare()
2859 *
2860 * bs is the BlockDriverState to reopen
2861 * flags are the new open flags
2862 * queue is the reopen queue
2863 *
2864 * Returns 0 on success, non-zero on error. On error errp will be set
2865 * as well.
2866 *
2867 * On failure, bdrv_reopen_abort() will be called to clean up any data.
2868 * It is the responsibility of the caller to then call the abort() or
2869 * commit() for any other BDS that have been left in a prepare() state
2870 *
2871 */
2872int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
2873 Error **errp)
2874{
2875 int ret = -1;
2876 Error *local_err = NULL;
2877 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002878 QemuOpts *opts;
2879 const char *value;
Jeff Cody3d8ce172017-04-07 16:55:30 -04002880 bool read_only;
Jeff Codye971aa12012-09-20 15:13:19 -04002881
2882 assert(reopen_state != NULL);
2883 assert(reopen_state->bs->drv != NULL);
2884 drv = reopen_state->bs->drv;
2885
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002886 /* Process generic block layer options */
2887 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2888 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2889 if (local_err) {
2890 error_propagate(errp, local_err);
2891 ret = -EINVAL;
2892 goto error;
2893 }
2894
Kevin Wolf91a097e2015-05-08 17:49:53 +02002895 update_flags_from_options(&reopen_state->flags, opts);
2896
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002897 /* node-name and driver must be unchanged. Put them back into the QDict, so
2898 * that they are checked at the end of this function. */
2899 value = qemu_opt_get(opts, "node-name");
2900 if (value) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002901 qdict_put_str(reopen_state->options, "node-name", value);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002902 }
2903
2904 value = qemu_opt_get(opts, "driver");
2905 if (value) {
Eric Blake46f5ac22017-04-27 16:58:17 -05002906 qdict_put_str(reopen_state->options, "driver", value);
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002907 }
2908
Jeff Cody3d8ce172017-04-07 16:55:30 -04002909 /* If we are to stay read-only, do not allow permission change
2910 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
2911 * not set, or if the BDS still has copy_on_read enabled */
2912 read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf54a32bf2017-08-03 17:02:58 +02002913 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
Jeff Cody3d8ce172017-04-07 16:55:30 -04002914 if (local_err) {
2915 error_propagate(errp, local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04002916 goto error;
2917 }
2918
2919
2920 ret = bdrv_flush(reopen_state->bs);
2921 if (ret) {
Eric Blake455b0fd2015-11-10 23:51:20 -07002922 error_setg_errno(errp, -ret, "Error flushing drive");
Jeff Codye971aa12012-09-20 15:13:19 -04002923 goto error;
2924 }
2925
2926 if (drv->bdrv_reopen_prepare) {
2927 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2928 if (ret) {
2929 if (local_err != NULL) {
2930 error_propagate(errp, local_err);
2931 } else {
Luiz Capitulinod8b68952013-06-10 11:29:27 -04002932 error_setg(errp, "failed while preparing to reopen image '%s'",
2933 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04002934 }
2935 goto error;
2936 }
2937 } else {
2938 /* It is currently mandatory to have a bdrv_reopen_prepare()
2939 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03002940 error_setg(errp, "Block format '%s' used by node '%s' "
2941 "does not support reopening files", drv->format_name,
2942 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04002943 ret = -1;
2944 goto error;
2945 }
2946
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002947 /* Options that are not handled are only okay if they are unchanged
2948 * compared to the old state. It is expected that some options are only
2949 * used for the initial open, but not reopen (e.g. filename) */
2950 if (qdict_size(reopen_state->options)) {
2951 const QDictEntry *entry = qdict_first(reopen_state->options);
2952
2953 do {
2954 QString *new_obj = qobject_to_qstring(entry->value);
2955 const char *new = qstring_get_str(new_obj);
Markus Armbruster129c7d12017-03-30 19:43:12 +02002956 /*
2957 * Caution: while qdict_get_try_str() is fine, getting
2958 * non-string types would require more care. When
2959 * bs->options come from -blockdev or blockdev_add, its
2960 * members are typed according to the QAPI schema, but
2961 * when they come from -drive, they're all QString.
2962 */
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002963 const char *old = qdict_get_try_str(reopen_state->bs->options,
2964 entry->key);
2965
2966 if (!old || strcmp(new, old)) {
2967 error_setg(errp, "Cannot change the option '%s'", entry->key);
2968 ret = -EINVAL;
2969 goto error;
2970 }
2971 } while ((entry = qdict_next(reopen_state->options, entry)));
2972 }
2973
Jeff Codye971aa12012-09-20 15:13:19 -04002974 ret = 0;
2975
2976error:
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002977 qemu_opts_del(opts);
Jeff Codye971aa12012-09-20 15:13:19 -04002978 return ret;
2979}
2980
2981/*
2982 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2983 * makes them final by swapping the staging BlockDriverState contents into
2984 * the active BlockDriverState contents.
2985 */
2986void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2987{
2988 BlockDriver *drv;
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03002989 BlockDriverState *bs;
Vladimir Sementsov-Ogievskiycb9ff6c2017-06-28 15:05:13 +03002990 bool old_can_write, new_can_write;
Jeff Codye971aa12012-09-20 15:13:19 -04002991
2992 assert(reopen_state != NULL);
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03002993 bs = reopen_state->bs;
2994 drv = bs->drv;
Jeff Codye971aa12012-09-20 15:13:19 -04002995 assert(drv != NULL);
2996
Vladimir Sementsov-Ogievskiycb9ff6c2017-06-28 15:05:13 +03002997 old_can_write =
2998 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
2999
Jeff Codye971aa12012-09-20 15:13:19 -04003000 /* If there are any driver level actions to take */
3001 if (drv->bdrv_reopen_commit) {
3002 drv->bdrv_reopen_commit(reopen_state);
3003 }
3004
3005 /* set BDS specific flags now */
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03003006 QDECREF(bs->explicit_options);
Kevin Wolf145f5982015-05-08 16:15:03 +02003007
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03003008 bs->explicit_options = reopen_state->explicit_options;
3009 bs->open_flags = reopen_state->flags;
3010 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf355ef4a2013-12-11 20:14:09 +01003011
Vladimir Sementsov-Ogievskiy50bf65b2017-06-28 15:05:12 +03003012 bdrv_refresh_limits(bs, NULL);
Vladimir Sementsov-Ogievskiycb9ff6c2017-06-28 15:05:13 +03003013
3014 new_can_write =
3015 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
3016 if (!old_can_write && new_can_write && drv->bdrv_reopen_bitmaps_rw) {
3017 Error *local_err = NULL;
3018 if (drv->bdrv_reopen_bitmaps_rw(bs, &local_err) < 0) {
3019 /* This is not fatal, bitmaps just left read-only, so all following
3020 * writes will fail. User can remove read-only bitmaps to unblock
3021 * writes.
3022 */
3023 error_reportf_err(local_err,
3024 "%s: Failed to make dirty bitmaps writable: ",
3025 bdrv_get_node_name(bs));
3026 }
3027 }
Jeff Codye971aa12012-09-20 15:13:19 -04003028}
3029
3030/*
3031 * Abort the reopen, and delete and free the staged changes in
3032 * reopen_state
3033 */
3034void bdrv_reopen_abort(BDRVReopenState *reopen_state)
3035{
3036 BlockDriver *drv;
3037
3038 assert(reopen_state != NULL);
3039 drv = reopen_state->bs->drv;
3040 assert(drv != NULL);
3041
3042 if (drv->bdrv_reopen_abort) {
3043 drv->bdrv_reopen_abort(reopen_state);
3044 }
Kevin Wolf145f5982015-05-08 16:15:03 +02003045
3046 QDECREF(reopen_state->explicit_options);
Jeff Codye971aa12012-09-20 15:13:19 -04003047}
3048
3049
Max Reitz64dff522016-01-29 16:36:10 +01003050static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00003051{
Max Reitz33384422014-06-20 21:57:33 +02003052 BdrvAioNotifier *ban, *ban_next;
3053
Max Reitzca9bd242016-01-29 16:36:14 +01003054 assert(!bs->job);
Max Reitz30f55fb2016-05-17 16:41:32 +02003055 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03003056
Paolo Bonzinifc272912015-12-23 11:48:24 +01003057 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02003058 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08003059 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01003060
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02003061 if (bs->drv) {
Kevin Wolf6e93e7c2015-04-08 13:49:41 +02003062 BdrvChild *child, *next;
3063
Kevin Wolf9a7dedb2015-06-16 10:58:20 +02003064 bs->drv->bdrv_close(bs);
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003065 bs->drv = NULL;
Kevin Wolf9a7dedb2015-06-16 10:58:20 +02003066
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003067 bdrv_set_backing_hd(bs, NULL, &error_abort);
Kevin Wolf9a7dedb2015-06-16 10:58:20 +02003068
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003069 if (bs->file != NULL) {
3070 bdrv_unref_child(bs, bs->file);
3071 bs->file = NULL;
3072 }
3073
Kevin Wolf6e93e7c2015-04-08 13:49:41 +02003074 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Kevin Wolf33a60402015-06-15 13:51:04 +02003075 /* TODO Remove bdrv_unref() from drivers' close function and use
3076 * bdrv_unref_child() here */
Kevin Wolfbddcec32015-04-09 18:47:50 +02003077 if (child->bs->inherits_from == bs) {
3078 child->bs->inherits_from = NULL;
3079 }
Kevin Wolf33a60402015-06-15 13:51:04 +02003080 bdrv_detach_child(child);
Kevin Wolf6e93e7c2015-04-08 13:49:41 +02003081 }
3082
Anthony Liguori7267c092011-08-20 22:09:37 -05003083 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +00003084 bs->opaque = NULL;
Paolo Bonzinid3faa132017-06-05 14:38:50 +02003085 atomic_set(&bs->copy_on_read, 0);
Paolo Bonzinia275fa42012-05-08 16:51:43 +02003086 bs->backing_file[0] = '\0';
3087 bs->backing_format[0] = '\0';
Paolo Bonzini64058752012-05-08 16:51:49 +02003088 bs->total_sectors = 0;
Eric Blake54115412016-06-23 16:37:26 -06003089 bs->encrypted = false;
Eric Blake54115412016-06-23 16:37:26 -06003090 bs->sg = false;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003091 QDECREF(bs->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02003092 QDECREF(bs->explicit_options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01003093 bs->options = NULL;
Manos Pitsidianakis998cbd62017-07-14 17:35:47 +03003094 bs->explicit_options = NULL;
Max Reitz91af7012014-07-18 20:24:56 +02003095 QDECREF(bs->full_open_options);
3096 bs->full_open_options = NULL;
bellardb3380822004-03-14 21:38:54 +00003097 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08003098
Vladimir Sementsov-Ogievskiycca43ae2017-06-28 15:05:16 +03003099 bdrv_release_named_dirty_bitmaps(bs);
3100 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
3101
Max Reitz33384422014-06-20 21:57:33 +02003102 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
3103 g_free(ban);
3104 }
3105 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01003106 bdrv_drained_end(bs);
bellardb3380822004-03-14 21:38:54 +00003107}
3108
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09003109void bdrv_close_all(void)
3110{
Kevin Wolfa1a2af02016-04-08 18:26:37 +02003111 block_job_cancel_sync_all();
Kevin Wolfcd7fca92016-07-06 11:22:39 +02003112 nbd_export_close_all();
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09003113
Max Reitzca9bd242016-01-29 16:36:14 +01003114 /* Drop references from requests still in flight, such as canceled block
3115 * jobs whose AIO context has not been polled yet */
3116 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02003117
Max Reitzca9bd242016-01-29 16:36:14 +01003118 blk_remove_all_bs();
3119 blockdev_close_all_bdrv_states();
3120
Kevin Wolfa1a2af02016-04-08 18:26:37 +02003121 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09003122}
3123
Kevin Wolfd0ac0382017-03-01 17:30:41 +01003124static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003125{
Kevin Wolfd0ac0382017-03-01 17:30:41 +01003126 BdrvChild *to_c;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003127
Kevin Wolfd0ac0382017-03-01 17:30:41 +01003128 if (c->role->stay_at_node) {
3129 return false;
3130 }
3131
3132 if (c->role == &child_backing) {
3133 /* If @from is a backing file of @to, ignore the child to avoid
3134 * creating a loop. We only want to change the pointer of other
3135 * parents. */
3136 QLIST_FOREACH(to_c, &to->children, next) {
3137 if (to_c == c) {
3138 break;
3139 }
3140 }
3141 if (to_c) {
3142 return false;
3143 }
3144 }
3145
3146 return true;
3147}
3148
Kevin Wolf5fe31c22017-03-06 16:20:51 +01003149void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
3150 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003151{
Kevin Wolfd0ac0382017-03-01 17:30:41 +01003152 BdrvChild *c, *next;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003153 GSList *list = NULL, *p;
3154 uint64_t old_perm, old_shared;
3155 uint64_t perm = 0, shared = BLK_PERM_ALL;
3156 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003157
Kevin Wolf5fe31c22017-03-06 16:20:51 +01003158 assert(!atomic_read(&from->in_flight));
3159 assert(!atomic_read(&to->in_flight));
3160
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003161 /* Make sure that @from doesn't go away until we have successfully attached
3162 * all of its parents to @to. */
3163 bdrv_ref(from);
3164
3165 /* Put all parents into @list and calculate their cumulative permissions */
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003166 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01003167 if (!should_update_child(c, to)) {
Kevin Wolf26de9432017-01-17 13:39:34 +01003168 continue;
3169 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003170 list = g_slist_prepend(list, c);
3171 perm |= c->perm;
3172 shared &= c->shared_perm;
3173 }
3174
3175 /* Check whether the required permissions can be granted on @to, ignoring
3176 * all BdrvChild in @list so that they can't block themselves. */
3177 ret = bdrv_check_update_perm(to, perm, shared, list, errp);
3178 if (ret < 0) {
3179 bdrv_abort_perm_update(to);
3180 goto out;
3181 }
3182
3183 /* Now actually perform the change. We performed the permission check for
3184 * all elements of @list at once, so set the permissions all at once at the
3185 * very end. */
3186 for (p = list; p != NULL; p = p->next) {
3187 c = p->data;
Max Reitz9bd910e2016-06-10 20:57:46 +02003188
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003189 bdrv_ref(to);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003190 bdrv_replace_child_noperm(c, to);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003191 bdrv_unref(from);
3192 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003193
3194 bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
3195 bdrv_set_perm(to, old_perm | perm, old_shared | shared);
3196
3197out:
3198 g_slist_free(list);
3199 bdrv_unref(from);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003200}
3201
Jeff Cody8802d1f2012-02-28 15:54:06 -05003202/*
3203 * Add new bs contents at the top of an image chain while the chain is
3204 * live, while keeping required fields on the top layer.
3205 *
3206 * This will modify the BlockDriverState fields, and swap contents
3207 * between bs_new and bs_top. Both bs_new and bs_top are modified.
3208 *
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02003209 * bs_new must not be attached to a BlockBackend.
Jeff Codyf6801b82012-03-27 16:30:19 -04003210 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05003211 * This function does not create any image files.
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003212 *
3213 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
3214 * that's what the callers commonly need. bs_new will be referenced by the old
3215 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
3216 * reference of its own, it must call bdrv_ref().
Jeff Cody8802d1f2012-02-28 15:54:06 -05003217 */
Kevin Wolfb2c28322017-02-20 12:46:42 +01003218void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
3219 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05003220{
Kevin Wolfb2c28322017-02-20 12:46:42 +01003221 Error *local_err = NULL;
3222
Kevin Wolfb2c28322017-02-20 12:46:42 +01003223 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
3224 if (local_err) {
3225 error_propagate(errp, local_err);
3226 goto out;
3227 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003228
Kevin Wolf5fe31c22017-03-06 16:20:51 +01003229 bdrv_replace_node(bs_top, bs_new, &local_err);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003230 if (local_err) {
3231 error_propagate(errp, local_err);
3232 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
3233 goto out;
3234 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003235
3236 /* bs_new is now referenced by its new parents, we don't need the
3237 * additional reference any more. */
Kevin Wolfb2c28322017-02-20 12:46:42 +01003238out:
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003239 bdrv_unref(bs_new);
Jeff Cody8802d1f2012-02-28 15:54:06 -05003240}
3241
Fam Zheng4f6fd342013-08-23 09:14:47 +08003242static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00003243{
Paolo Bonzini3e914652012-03-30 13:17:11 +02003244 assert(!bs->job);
Fam Zheng3718d8a2014-05-23 21:29:43 +08003245 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08003246 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02003247
Stefan Hajnoczie1b5c522013-06-27 15:32:26 +02003248 bdrv_close(bs);
3249
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01003250 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01003251 if (bs->node_name[0] != '\0') {
3252 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
3253 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01003254 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
3255
Anthony Liguori7267c092011-08-20 22:09:37 -05003256 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00003257}
3258
aliguorie97fc192009-04-21 23:11:50 +00003259/*
3260 * Run consistency checks on an image
3261 *
Kevin Wolfe076f332010-06-29 11:43:13 +02003262 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02003263 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02003264 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00003265 */
Kevin Wolf4534ff52012-05-11 16:07:02 +02003266int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00003267{
Max Reitz908bcd52014-08-07 22:47:55 +02003268 if (bs->drv == NULL) {
3269 return -ENOMEDIUM;
3270 }
aliguorie97fc192009-04-21 23:11:50 +00003271 if (bs->drv->bdrv_check == NULL) {
3272 return -ENOTSUP;
3273 }
3274
Kevin Wolfe076f332010-06-29 11:43:13 +02003275 memset(res, 0, sizeof(*res));
Kevin Wolf4534ff52012-05-11 16:07:02 +02003276 return bs->drv->bdrv_check(bs, res, fix);
aliguorie97fc192009-04-21 23:11:50 +00003277}
3278
Kevin Wolf756e6732010-01-12 12:55:17 +01003279/*
3280 * Return values:
3281 * 0 - success
3282 * -EINVAL - backing format specified, but no file
3283 * -ENOSPC - can't update the backing file because no space is left in the
3284 * image file header
3285 * -ENOTSUP - format driver doesn't support changing the backing file
3286 */
3287int bdrv_change_backing_file(BlockDriverState *bs,
3288 const char *backing_file, const char *backing_fmt)
3289{
3290 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02003291 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01003292
Paolo Bonzini5f377792012-04-12 14:01:01 +02003293 /* Backing file format doesn't make sense without a backing file */
3294 if (backing_fmt && !backing_file) {
3295 return -EINVAL;
3296 }
3297
Kevin Wolf756e6732010-01-12 12:55:17 +01003298 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02003299 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01003300 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02003301 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01003302 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02003303
3304 if (ret == 0) {
3305 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3306 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3307 }
3308 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01003309}
3310
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003311/*
3312 * Finds the image layer in the chain that has 'bs' as its backing file.
3313 *
3314 * active is the current topmost image.
3315 *
3316 * Returns NULL if bs is not found in active's image chain,
3317 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04003318 *
3319 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003320 */
3321BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
3322 BlockDriverState *bs)
3323{
Kevin Wolf760e0062015-06-17 14:55:21 +02003324 while (active && bs != backing_bs(active)) {
3325 active = backing_bs(active);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003326 }
3327
Jeff Cody4caf0fc2014-06-25 15:35:26 -04003328 return active;
3329}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003330
Jeff Cody4caf0fc2014-06-25 15:35:26 -04003331/* Given a BDS, searches for the base layer. */
3332BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3333{
3334 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003335}
3336
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003337/*
3338 * Drops images above 'base' up to and including 'top', and sets the image
3339 * above 'top' to have base as its backing file.
3340 *
3341 * Requires that the overlay to 'top' is opened r/w, so that the backing file
3342 * information in 'bs' can be properly updated.
3343 *
3344 * E.g., this will convert the following chain:
3345 * bottom <- base <- intermediate <- top <- active
3346 *
3347 * to
3348 *
3349 * bottom <- base <- active
3350 *
3351 * It is allowed for bottom==base, in which case it converts:
3352 *
3353 * base <- intermediate <- top <- active
3354 *
3355 * to
3356 *
3357 * base <- active
3358 *
Jeff Cody54e26902014-06-25 15:40:10 -04003359 * If backing_file_str is non-NULL, it will be used when modifying top's
3360 * overlay image metadata.
3361 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003362 * Error conditions:
3363 * if active == top, that is considered an error
3364 *
3365 */
3366int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
Jeff Cody54e26902014-06-25 15:40:10 -04003367 BlockDriverState *base, const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003368{
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003369 BlockDriverState *new_top_bs = NULL;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003370 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003371 int ret = -EIO;
3372
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003373 if (!top->drv || !base->drv) {
3374 goto exit;
3375 }
3376
3377 new_top_bs = bdrv_find_overlay(active, top);
3378
3379 if (new_top_bs == NULL) {
3380 /* we could not find the image above 'top', this is an error */
3381 goto exit;
3382 }
3383
Kevin Wolf760e0062015-06-17 14:55:21 +02003384 /* special case of new_top_bs->backing->bs already pointing to base - nothing
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003385 * to do, no intermediate images */
Kevin Wolf760e0062015-06-17 14:55:21 +02003386 if (backing_bs(new_top_bs) == base) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003387 ret = 0;
3388 goto exit;
3389 }
3390
Kevin Wolf5db15a52015-09-14 15:33:33 +02003391 /* Make sure that base is in the backing chain of top */
3392 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003393 goto exit;
3394 }
3395
3396 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolf5db15a52015-09-14 15:33:33 +02003397 backing_file_str = backing_file_str ? backing_file_str : base->filename;
Jeff Cody54e26902014-06-25 15:40:10 -04003398 ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
Kevin Wolf5db15a52015-09-14 15:33:33 +02003399 base->drv ? base->drv->format_name : "");
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003400 if (ret) {
3401 goto exit;
3402 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003403
3404 bdrv_set_backing_hd(new_top_bs, base, &local_err);
3405 if (local_err) {
3406 ret = -EPERM;
3407 error_report_err(local_err);
3408 goto exit;
3409 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003410
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003411 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003412exit:
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003413 return ret;
3414}
3415
bellard83f64092006-08-01 16:21:11 +00003416/**
bellard83f64092006-08-01 16:21:11 +00003417 * Truncate file to 'offset' bytes (needed only for file protocols)
3418 */
Max Reitz7ea37c32017-06-13 22:20:53 +02003419int bdrv_truncate(BdrvChild *child, int64_t offset, PreallocMode prealloc,
3420 Error **errp)
bellard83f64092006-08-01 16:21:11 +00003421{
Kevin Wolf52cdbc52017-02-16 18:39:03 +01003422 BlockDriverState *bs = child->bs;
bellard83f64092006-08-01 16:21:11 +00003423 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003424 int ret;
Kevin Wolfc8f6d582017-02-17 14:52:00 +01003425
Max Reitz362b3782017-04-11 17:52:26 +02003426 assert(child->perm & BLK_PERM_RESIZE);
Kevin Wolfc8f6d582017-02-17 14:52:00 +01003427
Max Reitzed3d2ec2017-03-28 22:51:27 +02003428 if (!drv) {
3429 error_setg(errp, "No medium inserted");
bellard19cb3732006-08-19 11:45:59 +00003430 return -ENOMEDIUM;
Max Reitzed3d2ec2017-03-28 22:51:27 +02003431 }
3432 if (!drv->bdrv_truncate) {
3433 error_setg(errp, "Image format driver does not support resize");
bellard83f64092006-08-01 16:21:11 +00003434 return -ENOTSUP;
Max Reitzed3d2ec2017-03-28 22:51:27 +02003435 }
3436 if (bs->read_only) {
3437 error_setg(errp, "Image is read-only");
Naphtali Sprei59f26892009-10-26 16:25:16 +02003438 return -EACCES;
Max Reitzed3d2ec2017-03-28 22:51:27 +02003439 }
Jeff Cody9c75e162014-06-25 16:55:30 -04003440
Denis V. Lunev504c2052017-04-05 18:18:25 +03003441 assert(!(bs->open_flags & BDRV_O_INACTIVE));
3442
Max Reitz7ea37c32017-06-13 22:20:53 +02003443 ret = drv->bdrv_truncate(bs, offset, prealloc, errp);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003444 if (ret == 0) {
3445 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
John Snowce1ffea2015-04-17 19:50:03 -04003446 bdrv_dirty_bitmap_truncate(bs);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003447 bdrv_parent_cb_resize(bs);
Paolo Bonzini47fec592017-06-05 14:39:01 +02003448 atomic_inc(&bs->write_gen);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003449 }
3450 return ret;
bellard83f64092006-08-01 16:21:11 +00003451}
3452
3453/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08003454 * Length of a allocated file in bytes. Sparse files are counted by actual
3455 * allocated space. Return < 0 if error or unknown.
3456 */
3457int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
3458{
3459 BlockDriver *drv = bs->drv;
3460 if (!drv) {
3461 return -ENOMEDIUM;
3462 }
3463 if (drv->bdrv_get_allocated_file_size) {
3464 return drv->bdrv_get_allocated_file_size(bs);
3465 }
3466 if (bs->file) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003467 return bdrv_get_allocated_file_size(bs->file->bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08003468 }
3469 return -ENOTSUP;
3470}
3471
Stefan Hajnoczi90880ff2017-07-05 13:57:30 +01003472/*
3473 * bdrv_measure:
3474 * @drv: Format driver
3475 * @opts: Creation options for new image
3476 * @in_bs: Existing image containing data for new image (may be NULL)
3477 * @errp: Error object
3478 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
3479 * or NULL on error
3480 *
3481 * Calculate file size required to create a new image.
3482 *
3483 * If @in_bs is given then space for allocated clusters and zero clusters
3484 * from that image are included in the calculation. If @opts contains a
3485 * backing file that is shared by @in_bs then backing clusters may be omitted
3486 * from the calculation.
3487 *
3488 * If @in_bs is NULL then the calculation includes no allocated clusters
3489 * unless a preallocation option is given in @opts.
3490 *
3491 * Note that @in_bs may use a different BlockDriver from @drv.
3492 *
3493 * If an error occurs the @errp pointer is set.
3494 */
3495BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
3496 BlockDriverState *in_bs, Error **errp)
3497{
3498 if (!drv->bdrv_measure) {
3499 error_setg(errp, "Block driver '%s' does not support size measurement",
3500 drv->format_name);
3501 return NULL;
3502 }
3503
3504 return drv->bdrv_measure(opts, in_bs, errp);
3505}
3506
Fam Zheng4a1d5e12011-07-12 19:56:39 +08003507/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003508 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00003509 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003510int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00003511{
3512 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003513
bellard83f64092006-08-01 16:21:11 +00003514 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003515 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003516
Kevin Wolfb94a2612013-10-29 12:18:58 +01003517 if (drv->has_variable_length) {
3518 int ret = refresh_total_sectors(bs, bs->total_sectors);
3519 if (ret < 0) {
3520 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01003521 }
bellard83f64092006-08-01 16:21:11 +00003522 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003523 return bs->total_sectors;
3524}
3525
3526/**
3527 * Return length in bytes on success, -errno on error.
3528 * The length is always a multiple of BDRV_SECTOR_SIZE.
3529 */
3530int64_t bdrv_getlength(BlockDriverState *bs)
3531{
3532 int64_t ret = bdrv_nb_sectors(bs);
3533
Fam Zheng4a9c9ea2015-05-15 16:36:05 +08003534 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003535 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00003536}
3537
bellard19cb3732006-08-19 11:45:59 +00003538/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00003539void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00003540{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003541 int64_t nb_sectors = bdrv_nb_sectors(bs);
3542
3543 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00003544}
bellardcf989512004-02-16 21:56:36 +00003545
Eric Blake54115412016-06-23 16:37:26 -06003546bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00003547{
3548 return bs->sg;
3549}
3550
Eric Blake54115412016-06-23 16:37:26 -06003551bool bdrv_is_encrypted(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00003552{
Kevin Wolf760e0062015-06-17 14:55:21 +02003553 if (bs->backing && bs->backing->bs->encrypted) {
Eric Blake54115412016-06-23 16:37:26 -06003554 return true;
Kevin Wolf760e0062015-06-17 14:55:21 +02003555 }
bellardea2384d2004-08-01 21:59:26 +00003556 return bs->encrypted;
3557}
3558
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02003559const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00003560{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02003561 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00003562}
3563
Stefan Hajnocziada42402014-08-27 12:08:55 +01003564static int qsort_strcmp(const void *a, const void *b)
3565{
Max Reitzceff5bd2016-10-12 22:49:05 +02003566 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01003567}
3568
ths5fafdf22007-09-16 21:08:06 +00003569void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00003570 void *opaque)
3571{
3572 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04003573 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01003574 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04003575 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00003576
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01003577 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04003578 if (drv->format_name) {
3579 bool found = false;
3580 int i = count;
3581 while (formats && i && !found) {
3582 found = !strcmp(formats[--i], drv->format_name);
3583 }
3584
3585 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02003586 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04003587 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04003588 }
3589 }
bellardea2384d2004-08-01 21:59:26 +00003590 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01003591
Max Reitzeb0df692016-10-12 22:49:06 +02003592 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
3593 const char *format_name = block_driver_modules[i].format_name;
3594
3595 if (format_name) {
3596 bool found = false;
3597 int j = count;
3598
3599 while (formats && j && !found) {
3600 found = !strcmp(formats[--j], format_name);
3601 }
3602
3603 if (!found) {
3604 formats = g_renew(const char *, formats, count + 1);
3605 formats[count++] = format_name;
3606 }
3607 }
3608 }
3609
Stefan Hajnocziada42402014-08-27 12:08:55 +01003610 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
3611
3612 for (i = 0; i < count; i++) {
3613 it(opaque, formats[i]);
3614 }
3615
Jeff Codye855e4f2014-04-28 18:29:54 -04003616 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00003617}
3618
Benoît Canetdc364f42014-01-23 21:31:32 +01003619/* This function is to find a node in the bs graph */
3620BlockDriverState *bdrv_find_node(const char *node_name)
3621{
3622 BlockDriverState *bs;
3623
3624 assert(node_name);
3625
3626 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3627 if (!strcmp(node_name, bs->node_name)) {
3628 return bs;
3629 }
3630 }
3631 return NULL;
3632}
3633
Benoît Canetc13163f2014-01-23 21:31:34 +01003634/* Put this QMP function here so it can access the static graph_bdrv_states. */
Alberto Garciad5a8ee62015-04-17 14:52:43 +03003635BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01003636{
3637 BlockDeviceInfoList *list, *entry;
3638 BlockDriverState *bs;
3639
3640 list = NULL;
3641 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Kevin Wolfc83f9fb2016-03-03 11:37:48 +01003642 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03003643 if (!info) {
3644 qapi_free_BlockDeviceInfoList(list);
3645 return NULL;
3646 }
Benoît Canetc13163f2014-01-23 21:31:34 +01003647 entry = g_malloc0(sizeof(*entry));
Alberto Garciad5a8ee62015-04-17 14:52:43 +03003648 entry->value = info;
Benoît Canetc13163f2014-01-23 21:31:34 +01003649 entry->next = list;
3650 list = entry;
3651 }
3652
3653 return list;
3654}
3655
Benoît Canet12d3ba82014-01-23 21:31:35 +01003656BlockDriverState *bdrv_lookup_bs(const char *device,
3657 const char *node_name,
3658 Error **errp)
3659{
Markus Armbruster7f06d472014-10-07 13:59:12 +02003660 BlockBackend *blk;
3661 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01003662
Benoît Canet12d3ba82014-01-23 21:31:35 +01003663 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02003664 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01003665
Markus Armbruster7f06d472014-10-07 13:59:12 +02003666 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02003667 bs = blk_bs(blk);
3668 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02003669 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02003670 }
3671
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02003672 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01003673 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01003674 }
3675
Benoît Canetdd67fa52014-02-12 17:15:06 +01003676 if (node_name) {
3677 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01003678
Benoît Canetdd67fa52014-02-12 17:15:06 +01003679 if (bs) {
3680 return bs;
3681 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01003682 }
3683
Benoît Canetdd67fa52014-02-12 17:15:06 +01003684 error_setg(errp, "Cannot find device=%s nor node_name=%s",
3685 device ? device : "",
3686 node_name ? node_name : "");
3687 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01003688}
3689
Jeff Cody5a6684d2014-06-25 15:40:09 -04003690/* If 'base' is in the same chain as 'top', return true. Otherwise,
3691 * return false. If either argument is NULL, return false. */
3692bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
3693{
3694 while (top && top != base) {
Kevin Wolf760e0062015-06-17 14:55:21 +02003695 top = backing_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04003696 }
3697
3698 return top != NULL;
3699}
3700
Fam Zheng04df7652014-10-31 11:32:54 +08003701BlockDriverState *bdrv_next_node(BlockDriverState *bs)
3702{
3703 if (!bs) {
3704 return QTAILQ_FIRST(&graph_bdrv_states);
3705 }
3706 return QTAILQ_NEXT(bs, node_list);
3707}
3708
Fam Zheng20a9e772014-10-31 11:32:55 +08003709const char *bdrv_get_node_name(const BlockDriverState *bs)
3710{
3711 return bs->node_name;
3712}
3713
Kevin Wolf1f0c4612016-03-22 18:38:44 +01003714const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01003715{
3716 BdrvChild *c;
3717 const char *name;
3718
3719 /* If multiple parents have a name, just pick the first one. */
3720 QLIST_FOREACH(c, &bs->parents, next_parent) {
3721 if (c->role->get_name) {
3722 name = c->role->get_name(c);
3723 if (name && *name) {
3724 return name;
3725 }
3726 }
3727 }
3728
3729 return NULL;
3730}
3731
Markus Armbruster7f06d472014-10-07 13:59:12 +02003732/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02003733const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00003734{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01003735 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00003736}
3737
Alberto Garcia9b2aa842015-04-08 12:29:18 +03003738/* This can be used to identify nodes that might not have a device
3739 * name associated. Since node and device names live in the same
3740 * namespace, the result is unambiguous. The exception is if both are
3741 * absent, then this returns an empty (non-null) string. */
3742const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
3743{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01003744 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03003745}
3746
Markus Armbrusterc8433282012-06-05 16:49:24 +02003747int bdrv_get_flags(BlockDriverState *bs)
3748{
3749 return bs->open_flags;
3750}
3751
Peter Lieven3ac21622013-06-28 12:47:42 +02003752int bdrv_has_zero_init_1(BlockDriverState *bs)
3753{
3754 return 1;
3755}
3756
Kevin Wolff2feebb2010-04-14 17:30:35 +02003757int bdrv_has_zero_init(BlockDriverState *bs)
3758{
3759 assert(bs->drv);
3760
Paolo Bonzini11212d82013-09-04 19:00:27 +02003761 /* If BS is a copy on write image, it is initialized to
3762 the contents of the base image, which may not be zeroes. */
Kevin Wolf760e0062015-06-17 14:55:21 +02003763 if (bs->backing) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02003764 return 0;
3765 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02003766 if (bs->drv->bdrv_has_zero_init) {
3767 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02003768 }
3769
Peter Lieven3ac21622013-06-28 12:47:42 +02003770 /* safe default */
3771 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02003772}
3773
Peter Lieven4ce78692013-10-24 12:06:54 +02003774bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
3775{
3776 BlockDriverInfo bdi;
3777
Kevin Wolf760e0062015-06-17 14:55:21 +02003778 if (bs->backing) {
Peter Lieven4ce78692013-10-24 12:06:54 +02003779 return false;
3780 }
3781
3782 if (bdrv_get_info(bs, &bdi) == 0) {
3783 return bdi.unallocated_blocks_are_zero;
3784 }
3785
3786 return false;
3787}
3788
3789bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
3790{
3791 BlockDriverInfo bdi;
3792
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03003793 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02003794 return false;
3795 }
3796
3797 if (bdrv_get_info(bs, &bdi) == 0) {
3798 return bdi.can_write_zeroes_with_unmap;
3799 }
3800
3801 return false;
3802}
3803
aliguori045df332009-03-05 23:00:48 +00003804const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3805{
Kevin Wolf760e0062015-06-17 14:55:21 +02003806 if (bs->backing && bs->backing->bs->encrypted)
aliguori045df332009-03-05 23:00:48 +00003807 return bs->backing_file;
3808 else if (bs->encrypted)
3809 return bs->filename;
3810 else
3811 return NULL;
3812}
3813
ths5fafdf22007-09-16 21:08:06 +00003814void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00003815 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00003816{
Kevin Wolf3574c602011-10-26 11:02:11 +02003817 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00003818}
3819
bellardfaea38e2006-08-05 21:31:00 +00003820int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3821{
3822 BlockDriver *drv = bs->drv;
3823 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003824 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00003825 if (!drv->bdrv_get_info)
3826 return -ENOTSUP;
3827 memset(bdi, 0, sizeof(*bdi));
3828 return drv->bdrv_get_info(bs, bdi);
3829}
3830
Max Reitzeae041f2013-10-09 10:46:16 +02003831ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3832{
3833 BlockDriver *drv = bs->drv;
3834 if (drv && drv->bdrv_get_specific_info) {
3835 return drv->bdrv_get_specific_info(bs);
3836 }
3837 return NULL;
3838}
3839
Eric Blakea31939e2015-11-18 01:52:54 -07003840void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003841{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02003842 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003843 return;
3844 }
3845
Kevin Wolfbf736fe2013-06-05 15:17:55 +02003846 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01003847}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003848
Kevin Wolf41c695c2012-12-06 14:32:58 +01003849int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3850 const char *tag)
3851{
3852 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003853 bs = bs->file ? bs->file->bs : NULL;
Kevin Wolf41c695c2012-12-06 14:32:58 +01003854 }
3855
3856 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3857 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3858 }
3859
3860 return -ENOTSUP;
3861}
3862
Fam Zheng4cc70e92013-11-20 10:01:54 +08003863int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
3864{
3865 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003866 bs = bs->file ? bs->file->bs : NULL;
Fam Zheng4cc70e92013-11-20 10:01:54 +08003867 }
3868
3869 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
3870 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
3871 }
3872
3873 return -ENOTSUP;
3874}
3875
Kevin Wolf41c695c2012-12-06 14:32:58 +01003876int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3877{
Max Reitz938789e2014-03-10 23:44:08 +01003878 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003879 bs = bs->file ? bs->file->bs : NULL;
Kevin Wolf41c695c2012-12-06 14:32:58 +01003880 }
3881
3882 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3883 return bs->drv->bdrv_debug_resume(bs, tag);
3884 }
3885
3886 return -ENOTSUP;
3887}
3888
3889bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3890{
3891 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003892 bs = bs->file ? bs->file->bs : NULL;
Kevin Wolf41c695c2012-12-06 14:32:58 +01003893 }
3894
3895 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3896 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3897 }
3898
3899 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003900}
3901
Jeff Codyb1b1d782012-10-16 15:49:09 -04003902/* backing_file can either be relative, or absolute, or a protocol. If it is
3903 * relative, it must be relative to the chain. So, passing in bs->filename
3904 * from a BDS as backing_file should not be done, as that may be relative to
3905 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003906BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3907 const char *backing_file)
3908{
Jeff Codyb1b1d782012-10-16 15:49:09 -04003909 char *filename_full = NULL;
3910 char *backing_file_full = NULL;
3911 char *filename_tmp = NULL;
3912 int is_protocol = 0;
3913 BlockDriverState *curr_bs = NULL;
3914 BlockDriverState *retval = NULL;
Jeff Cody418661e2017-01-25 20:08:20 -05003915 Error *local_error = NULL;
Jeff Codyb1b1d782012-10-16 15:49:09 -04003916
3917 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003918 return NULL;
3919 }
3920
Jeff Codyb1b1d782012-10-16 15:49:09 -04003921 filename_full = g_malloc(PATH_MAX);
3922 backing_file_full = g_malloc(PATH_MAX);
3923 filename_tmp = g_malloc(PATH_MAX);
3924
3925 is_protocol = path_has_protocol(backing_file);
3926
Kevin Wolf760e0062015-06-17 14:55:21 +02003927 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
Jeff Codyb1b1d782012-10-16 15:49:09 -04003928
3929 /* If either of the filename paths is actually a protocol, then
3930 * compare unmodified paths; otherwise make paths relative */
3931 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3932 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Kevin Wolf760e0062015-06-17 14:55:21 +02003933 retval = curr_bs->backing->bs;
Jeff Codyb1b1d782012-10-16 15:49:09 -04003934 break;
3935 }
Jeff Cody418661e2017-01-25 20:08:20 -05003936 /* Also check against the full backing filename for the image */
3937 bdrv_get_full_backing_filename(curr_bs, backing_file_full, PATH_MAX,
3938 &local_error);
3939 if (local_error == NULL) {
3940 if (strcmp(backing_file, backing_file_full) == 0) {
3941 retval = curr_bs->backing->bs;
3942 break;
3943 }
3944 } else {
3945 error_free(local_error);
3946 local_error = NULL;
3947 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003948 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04003949 /* If not an absolute filename path, make it relative to the current
3950 * image's filename path */
3951 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3952 backing_file);
3953
3954 /* We are going to compare absolute pathnames */
3955 if (!realpath(filename_tmp, filename_full)) {
3956 continue;
3957 }
3958
3959 /* We need to make sure the backing filename we are comparing against
3960 * is relative to the current image filename (or absolute) */
3961 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3962 curr_bs->backing_file);
3963
3964 if (!realpath(filename_tmp, backing_file_full)) {
3965 continue;
3966 }
3967
3968 if (strcmp(backing_file_full, filename_full) == 0) {
Kevin Wolf760e0062015-06-17 14:55:21 +02003969 retval = curr_bs->backing->bs;
Jeff Codyb1b1d782012-10-16 15:49:09 -04003970 break;
3971 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003972 }
3973 }
3974
Jeff Codyb1b1d782012-10-16 15:49:09 -04003975 g_free(filename_full);
3976 g_free(backing_file_full);
3977 g_free(filename_tmp);
3978 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003979}
3980
bellardea2384d2004-08-01 21:59:26 +00003981void bdrv_init(void)
3982{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05003983 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00003984}
pbrookce1a14d2006-08-07 02:38:06 +00003985
Markus Armbrustereb852012009-10-27 18:41:44 +01003986void bdrv_init_with_whitelist(void)
3987{
3988 use_bdrv_whitelist = 1;
3989 bdrv_init();
3990}
3991
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003992void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06003993{
Kevin Wolf4417ab72017-05-04 18:52:37 +02003994 BdrvChild *child, *parent;
Kevin Wolf9c5e6592017-05-04 18:52:40 +02003995 uint64_t perm, shared_perm;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003996 Error *local_err = NULL;
3997 int ret;
3998
Kevin Wolf3456a8d2014-03-11 10:58:39 +01003999 if (!bs->drv) {
4000 return;
Anthony Liguori0f154232011-11-14 15:09:45 -06004001 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01004002
Kevin Wolf04c01a52016-01-13 15:56:06 +01004003 if (!(bs->open_flags & BDRV_O_INACTIVE)) {
Alexey Kardashevskiy7ea2d262014-10-09 13:50:46 +11004004 return;
4005 }
Alexey Kardashevskiy7ea2d262014-10-09 13:50:46 +11004006
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03004007 QLIST_FOREACH(child, &bs->children, next) {
4008 bdrv_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08004009 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08004010 error_propagate(errp, local_err);
4011 return;
4012 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01004013 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08004014
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03004015 bs->open_flags &= ~BDRV_O_INACTIVE;
4016 if (bs->drv->bdrv_invalidate_cache) {
4017 bs->drv->bdrv_invalidate_cache(bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08004018 if (local_err) {
4019 bs->open_flags |= BDRV_O_INACTIVE;
4020 error_propagate(errp, local_err);
4021 return;
4022 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01004023 }
4024
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01004025 ret = refresh_total_sectors(bs, bs->total_sectors);
4026 if (ret < 0) {
Kevin Wolf04c01a52016-01-13 15:56:06 +01004027 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01004028 error_setg_errno(errp, -ret, "Could not refresh total sector count");
4029 return;
4030 }
Kevin Wolf4417ab72017-05-04 18:52:37 +02004031
Kevin Wolf9c5e6592017-05-04 18:52:40 +02004032 /* Update permissions, they may differ for inactive nodes */
4033 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
4034 ret = bdrv_check_perm(bs, perm, shared_perm, NULL, &local_err);
4035 if (ret < 0) {
4036 bs->open_flags |= BDRV_O_INACTIVE;
4037 error_propagate(errp, local_err);
4038 return;
4039 }
4040 bdrv_set_perm(bs, perm, shared_perm);
4041
Kevin Wolf4417ab72017-05-04 18:52:37 +02004042 QLIST_FOREACH(parent, &bs->parents, next_parent) {
4043 if (parent->role->activate) {
4044 parent->role->activate(parent, &local_err);
4045 if (local_err) {
4046 error_propagate(errp, local_err);
4047 return;
4048 }
4049 }
4050 }
Anthony Liguori0f154232011-11-14 15:09:45 -06004051}
4052
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01004053void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06004054{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01004055 BlockDriverState *bs;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01004056 Error *local_err = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02004057 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06004058
Kevin Wolf88be7b42016-05-20 18:49:07 +02004059 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004060 AioContext *aio_context = bdrv_get_aio_context(bs);
4061
4062 aio_context_acquire(aio_context);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01004063 bdrv_invalidate_cache(bs, &local_err);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02004064 aio_context_release(aio_context);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01004065 if (local_err) {
4066 error_propagate(errp, local_err);
4067 return;
4068 }
Anthony Liguori0f154232011-11-14 15:09:45 -06004069 }
4070}
4071
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004072static int bdrv_inactivate_recurse(BlockDriverState *bs,
4073 bool setting_flag)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004074{
Kevin Wolfcfa1a572017-05-04 18:52:38 +02004075 BdrvChild *child, *parent;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004076 int ret;
4077
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004078 if (!setting_flag && bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004079 ret = bs->drv->bdrv_inactivate(bs);
4080 if (ret < 0) {
4081 return ret;
4082 }
4083 }
4084
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004085 if (setting_flag) {
Kevin Wolf9c5e6592017-05-04 18:52:40 +02004086 uint64_t perm, shared_perm;
4087
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004088 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolfcfa1a572017-05-04 18:52:38 +02004089
4090 QLIST_FOREACH(parent, &bs->parents, next_parent) {
4091 if (parent->role->inactivate) {
4092 ret = parent->role->inactivate(parent);
4093 if (ret < 0) {
4094 bs->open_flags &= ~BDRV_O_INACTIVE;
4095 return ret;
4096 }
4097 }
4098 }
Kevin Wolf9c5e6592017-05-04 18:52:40 +02004099
4100 /* Update permissions, they may differ for inactive nodes */
4101 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
4102 bdrv_check_perm(bs, perm, shared_perm, NULL, &error_abort);
4103 bdrv_set_perm(bs, perm, shared_perm);
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004104 }
Kevin Wolf38701b62017-05-04 18:52:39 +02004105
4106 QLIST_FOREACH(child, &bs->children, next) {
4107 ret = bdrv_inactivate_recurse(child->bs, setting_flag);
4108 if (ret < 0) {
4109 return ret;
4110 }
4111 }
4112
Vladimir Sementsov-Ogievskiy615b5dc2017-06-28 15:05:30 +03004113 /* At this point persistent bitmaps should be already stored by the format
4114 * driver */
4115 bdrv_release_persistent_dirty_bitmaps(bs);
4116
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004117 return 0;
4118}
4119
4120int bdrv_inactivate_all(void)
4121{
Max Reitz79720af2016-03-16 19:54:44 +01004122 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02004123 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004124 int ret = 0;
4125 int pass;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004126
Kevin Wolf88be7b42016-05-20 18:49:07 +02004127 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004128 aio_context_acquire(bdrv_get_aio_context(bs));
4129 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004130
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004131 /* We do two passes of inactivation. The first pass calls to drivers'
4132 * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
4133 * the second pass sets the BDRV_O_INACTIVE flag so that no further write
4134 * is allowed. */
4135 for (pass = 0; pass < 2; pass++) {
Kevin Wolf88be7b42016-05-20 18:49:07 +02004136 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004137 ret = bdrv_inactivate_recurse(bs, pass);
4138 if (ret < 0) {
4139 goto out;
4140 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004141 }
4142 }
4143
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004144out:
Kevin Wolf88be7b42016-05-20 18:49:07 +02004145 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004146 aio_context_release(bdrv_get_aio_context(bs));
4147 }
4148
4149 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004150}
4151
Kevin Wolff9f05dc2011-07-15 13:50:26 +02004152/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00004153/* removable device support */
4154
4155/**
4156 * Return TRUE if the media is present
4157 */
Max Reitze031f752015-10-19 17:53:11 +02004158bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00004159{
4160 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02004161 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02004162
Max Reitze031f752015-10-19 17:53:11 +02004163 if (!drv) {
4164 return false;
4165 }
Max Reitz28d7a782015-10-19 17:53:13 +02004166 if (drv->bdrv_is_inserted) {
4167 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02004168 }
Max Reitz28d7a782015-10-19 17:53:13 +02004169 QLIST_FOREACH(child, &bs->children, next) {
4170 if (!bdrv_is_inserted(child->bs)) {
4171 return false;
4172 }
4173 }
4174 return true;
bellard19cb3732006-08-19 11:45:59 +00004175}
4176
4177/**
Markus Armbruster8e49ca42011-08-03 15:08:08 +02004178 * Return whether the media changed since the last call to this
4179 * function, or -ENOTSUP if we don't know. Most drivers don't know.
bellard19cb3732006-08-19 11:45:59 +00004180 */
4181int bdrv_media_changed(BlockDriverState *bs)
4182{
4183 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00004184
Markus Armbruster8e49ca42011-08-03 15:08:08 +02004185 if (drv && drv->bdrv_media_changed) {
4186 return drv->bdrv_media_changed(bs);
4187 }
4188 return -ENOTSUP;
bellard19cb3732006-08-19 11:45:59 +00004189}
4190
4191/**
4192 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4193 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02004194void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00004195{
4196 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00004197
Markus Armbruster822e1cd2011-07-20 18:23:42 +02004198 if (drv && drv->bdrv_eject) {
4199 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00004200 }
bellard19cb3732006-08-19 11:45:59 +00004201}
4202
bellard19cb3732006-08-19 11:45:59 +00004203/**
4204 * Lock or unlock the media (if it is locked, the user won't be able
4205 * to eject it manually).
4206 */
Markus Armbruster025e8492011-09-06 18:58:47 +02004207void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00004208{
4209 BlockDriver *drv = bs->drv;
4210
Markus Armbruster025e8492011-09-06 18:58:47 +02004211 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01004212
Markus Armbruster025e8492011-09-06 18:58:47 +02004213 if (drv && drv->bdrv_lock_medium) {
4214 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00004215 }
4216}
ths985a03b2007-12-24 16:10:43 +00004217
Fam Zheng9fcb0252013-08-23 09:14:46 +08004218/* Get a reference to bs */
4219void bdrv_ref(BlockDriverState *bs)
4220{
4221 bs->refcnt++;
4222}
4223
4224/* Release a previously grabbed reference to bs.
4225 * If after releasing, reference count is zero, the BlockDriverState is
4226 * deleted. */
4227void bdrv_unref(BlockDriverState *bs)
4228{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04004229 if (!bs) {
4230 return;
4231 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08004232 assert(bs->refcnt > 0);
4233 if (--bs->refcnt == 0) {
4234 bdrv_delete(bs);
4235 }
4236}
4237
Fam Zhengfbe40ff2014-05-23 21:29:42 +08004238struct BdrvOpBlocker {
4239 Error *reason;
4240 QLIST_ENTRY(BdrvOpBlocker) list;
4241};
4242
4243bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
4244{
4245 BdrvOpBlocker *blocker;
4246 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4247 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
4248 blocker = QLIST_FIRST(&bs->op_blockers[op]);
Eduardo Habkost57ef3f12017-06-08 10:39:03 -03004249 error_propagate(errp, error_copy(blocker->reason));
4250 error_prepend(errp, "Node '%s' is busy: ",
4251 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08004252 return true;
4253 }
4254 return false;
4255}
4256
4257void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
4258{
4259 BdrvOpBlocker *blocker;
4260 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4261
Markus Armbruster5839e532014-08-19 10:31:08 +02004262 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08004263 blocker->reason = reason;
4264 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
4265}
4266
4267void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
4268{
4269 BdrvOpBlocker *blocker, *next;
4270 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4271 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
4272 if (blocker->reason == reason) {
4273 QLIST_REMOVE(blocker, list);
4274 g_free(blocker);
4275 }
4276 }
4277}
4278
4279void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
4280{
4281 int i;
4282 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4283 bdrv_op_block(bs, i, reason);
4284 }
4285}
4286
4287void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
4288{
4289 int i;
4290 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4291 bdrv_op_unblock(bs, i, reason);
4292 }
4293}
4294
4295bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
4296{
4297 int i;
4298
4299 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4300 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
4301 return false;
4302 }
4303 }
4304 return true;
4305}
4306
Luiz Capitulinod92ada22012-11-30 10:52:09 -02004307void bdrv_img_create(const char *filename, const char *fmt,
4308 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08004309 char *options, uint64_t img_size, int flags, bool quiet,
4310 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004311{
Chunyan Liu83d05212014-06-05 17:20:51 +08004312 QemuOptsList *create_opts = NULL;
4313 QemuOpts *opts = NULL;
4314 const char *backing_fmt, *backing_file;
4315 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004316 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02004317 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004318 int ret = 0;
4319
4320 /* Find driver and parse its options */
4321 drv = bdrv_find_format(fmt);
4322 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004323 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02004324 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004325 }
4326
Max Reitzb65a5e12015-02-05 13:58:12 -05004327 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004328 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02004329 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004330 }
4331
Max Reitzc6149722014-12-02 18:32:45 +01004332 if (!drv->create_opts) {
4333 error_setg(errp, "Format driver '%s' does not support image creation",
4334 drv->format_name);
4335 return;
4336 }
4337
4338 if (!proto_drv->create_opts) {
4339 error_setg(errp, "Protocol driver '%s' does not support image creation",
4340 proto_drv->format_name);
4341 return;
4342 }
4343
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004344 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4345 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004346
4347 /* Create parameter list with default values */
Chunyan Liu83d05212014-06-05 17:20:51 +08004348 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01004349 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004350
4351 /* Parse -o options */
4352 if (options) {
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004353 qemu_opts_do_parse(opts, options, NULL, &local_err);
4354 if (local_err) {
4355 error_report_err(local_err);
4356 local_err = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004357 error_setg(errp, "Invalid options for file format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004358 goto out;
4359 }
4360 }
4361
4362 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01004363 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
Markus Armbruster6be41942015-02-12 17:49:02 +01004364 if (local_err) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004365 error_setg(errp, "Backing file not supported for file format '%s'",
4366 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004367 goto out;
4368 }
4369 }
4370
4371 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01004372 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
Markus Armbruster6be41942015-02-12 17:49:02 +01004373 if (local_err) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004374 error_setg(errp, "Backing file format not supported for file "
4375 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004376 goto out;
4377 }
4378 }
4379
Chunyan Liu83d05212014-06-05 17:20:51 +08004380 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4381 if (backing_file) {
4382 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004383 error_setg(errp, "Error: Trying to create an image with the "
4384 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01004385 goto out;
4386 }
4387 }
4388
Chunyan Liu83d05212014-06-05 17:20:51 +08004389 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004390
John Snow6e6e55f2017-07-17 20:34:22 -04004391 /* The size for the image must always be specified, unless we have a backing
4392 * file and we have not been forbidden from opening it. */
Chunyan Liu83d05212014-06-05 17:20:51 +08004393 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
John Snow6e6e55f2017-07-17 20:34:22 -04004394 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
4395 BlockDriverState *bs;
4396 char *full_backing = g_new0(char, PATH_MAX);
4397 int back_flags;
4398 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02004399
John Snow6e6e55f2017-07-17 20:34:22 -04004400 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
4401 full_backing, PATH_MAX,
4402 &local_err);
4403 if (local_err) {
Max Reitz29168012014-11-26 17:20:27 +01004404 g_free(full_backing);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004405 goto out;
4406 }
John Snow6e6e55f2017-07-17 20:34:22 -04004407
4408 /* backing files always opened read-only */
4409 back_flags = flags;
4410 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4411
4412 if (backing_fmt) {
4413 backing_options = qdict_new();
4414 qdict_put_str(backing_options, "driver", backing_fmt);
4415 }
4416
4417 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
4418 &local_err);
4419 g_free(full_backing);
4420 if (!bs && size != -1) {
4421 /* Couldn't open BS, but we have a size, so it's nonfatal */
4422 warn_reportf_err(local_err,
4423 "Could not verify backing image. "
4424 "This may become an error in future versions.\n");
4425 local_err = NULL;
4426 } else if (!bs) {
4427 /* Couldn't open bs, do not have size */
4428 error_append_hint(&local_err,
4429 "Could not open backing image to determine size.\n");
4430 goto out;
4431 } else {
4432 if (size == -1) {
4433 /* Opened BS, have no size */
4434 size = bdrv_getlength(bs);
4435 if (size < 0) {
4436 error_setg_errno(errp, -size, "Could not get size of '%s'",
4437 backing_file);
4438 bdrv_unref(bs);
4439 goto out;
4440 }
4441 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
4442 }
4443 bdrv_unref(bs);
4444 }
4445 } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
4446
4447 if (size == -1) {
4448 error_setg(errp, "Image creation needs a size parameter");
4449 goto out;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004450 }
4451
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01004452 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02004453 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08004454 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01004455 puts("");
4456 }
Chunyan Liu83d05212014-06-05 17:20:51 +08004457
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004458 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08004459
Max Reitzcc84d902013-09-06 17:14:26 +02004460 if (ret == -EFBIG) {
4461 /* This is generally a better message than whatever the driver would
4462 * deliver (especially because of the cluster_size_hint), since that
4463 * is most probably not much different from "image too large". */
4464 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08004465 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02004466 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004467 }
Max Reitzcc84d902013-09-06 17:14:26 +02004468 error_setg(errp, "The image size is too large for file format '%s'"
4469 "%s", fmt, cluster_size_hint);
4470 error_free(local_err);
4471 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004472 }
4473
4474out:
Chunyan Liu83d05212014-06-05 17:20:51 +08004475 qemu_opts_del(opts);
4476 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004477 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004478}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01004479
4480AioContext *bdrv_get_aio_context(BlockDriverState *bs)
4481{
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004482 return bs->aio_context;
4483}
4484
Fam Zheng052a7572017-04-10 20:09:25 +08004485void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
4486{
4487 aio_co_enter(bdrv_get_aio_context(bs), co);
4488}
4489
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004490static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
4491{
4492 QLIST_REMOVE(ban, list);
4493 g_free(ban);
4494}
4495
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004496void bdrv_detach_aio_context(BlockDriverState *bs)
4497{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004498 BdrvAioNotifier *baf, *baf_tmp;
Max Reitzb97511c2016-05-17 13:38:04 +02004499 BdrvChild *child;
Max Reitz33384422014-06-20 21:57:33 +02004500
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004501 if (!bs->drv) {
4502 return;
4503 }
4504
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004505 assert(!bs->walking_aio_notifiers);
4506 bs->walking_aio_notifiers = true;
4507 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
4508 if (baf->deleted) {
4509 bdrv_do_remove_aio_context_notifier(baf);
4510 } else {
4511 baf->detach_aio_context(baf->opaque);
4512 }
Max Reitz33384422014-06-20 21:57:33 +02004513 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004514 /* Never mind iterating again to check for ->deleted. bdrv_close() will
4515 * remove remaining aio notifiers if we aren't called again.
4516 */
4517 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02004518
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004519 if (bs->drv->bdrv_detach_aio_context) {
4520 bs->drv->bdrv_detach_aio_context(bs);
4521 }
Max Reitzb97511c2016-05-17 13:38:04 +02004522 QLIST_FOREACH(child, &bs->children, next) {
4523 bdrv_detach_aio_context(child->bs);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004524 }
4525
4526 bs->aio_context = NULL;
4527}
4528
4529void bdrv_attach_aio_context(BlockDriverState *bs,
4530 AioContext *new_context)
4531{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004532 BdrvAioNotifier *ban, *ban_tmp;
Max Reitzb97511c2016-05-17 13:38:04 +02004533 BdrvChild *child;
Max Reitz33384422014-06-20 21:57:33 +02004534
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004535 if (!bs->drv) {
4536 return;
4537 }
4538
4539 bs->aio_context = new_context;
4540
Max Reitzb97511c2016-05-17 13:38:04 +02004541 QLIST_FOREACH(child, &bs->children, next) {
4542 bdrv_attach_aio_context(child->bs, new_context);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004543 }
4544 if (bs->drv->bdrv_attach_aio_context) {
4545 bs->drv->bdrv_attach_aio_context(bs, new_context);
4546 }
Max Reitz33384422014-06-20 21:57:33 +02004547
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004548 assert(!bs->walking_aio_notifiers);
4549 bs->walking_aio_notifiers = true;
4550 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
4551 if (ban->deleted) {
4552 bdrv_do_remove_aio_context_notifier(ban);
4553 } else {
4554 ban->attached_aio_context(new_context, ban->opaque);
4555 }
Max Reitz33384422014-06-20 21:57:33 +02004556 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004557 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004558}
4559
4560void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
4561{
Fam Zhengaabf5912017-04-05 14:44:24 +08004562 AioContext *ctx = bdrv_get_aio_context(bs);
Paolo Bonzinic2b64282017-03-14 12:11:57 +01004563
Fam Zhengaabf5912017-04-05 14:44:24 +08004564 aio_disable_external(ctx);
4565 bdrv_parent_drained_begin(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004566 bdrv_drain(bs); /* ensure there are no in-flight requests */
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004567
Paolo Bonzinic2b64282017-03-14 12:11:57 +01004568 while (aio_poll(ctx, false)) {
4569 /* wait for all bottom halves to execute */
4570 }
4571
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004572 bdrv_detach_aio_context(bs);
4573
4574 /* This function executes in the old AioContext so acquire the new one in
4575 * case it runs in a different thread.
4576 */
4577 aio_context_acquire(new_context);
4578 bdrv_attach_aio_context(bs, new_context);
Fam Zhengaabf5912017-04-05 14:44:24 +08004579 bdrv_parent_drained_end(bs);
4580 aio_enable_external(ctx);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004581 aio_context_release(new_context);
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01004582}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02004583
Max Reitz33384422014-06-20 21:57:33 +02004584void bdrv_add_aio_context_notifier(BlockDriverState *bs,
4585 void (*attached_aio_context)(AioContext *new_context, void *opaque),
4586 void (*detach_aio_context)(void *opaque), void *opaque)
4587{
4588 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
4589 *ban = (BdrvAioNotifier){
4590 .attached_aio_context = attached_aio_context,
4591 .detach_aio_context = detach_aio_context,
4592 .opaque = opaque
4593 };
4594
4595 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
4596}
4597
4598void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
4599 void (*attached_aio_context)(AioContext *,
4600 void *),
4601 void (*detach_aio_context)(void *),
4602 void *opaque)
4603{
4604 BdrvAioNotifier *ban, *ban_next;
4605
4606 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4607 if (ban->attached_aio_context == attached_aio_context &&
4608 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004609 ban->opaque == opaque &&
4610 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02004611 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004612 if (bs->walking_aio_notifiers) {
4613 ban->deleted = true;
4614 } else {
4615 bdrv_do_remove_aio_context_notifier(ban);
4616 }
Max Reitz33384422014-06-20 21:57:33 +02004617 return;
4618 }
4619 }
4620
4621 abort();
4622}
4623
Max Reitz77485432014-10-27 11:12:50 +01004624int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitz8b139762015-07-27 17:51:32 +02004625 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
Max Reitz6f176b42013-09-03 10:09:50 +02004626{
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004627 if (!bs->drv->bdrv_amend_options) {
Max Reitz6f176b42013-09-03 10:09:50 +02004628 return -ENOTSUP;
4629 }
Max Reitz8b139762015-07-27 17:51:32 +02004630 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
Max Reitz6f176b42013-09-03 10:09:50 +02004631}
Benoît Canetf6186f42013-10-02 14:33:48 +02004632
Benoît Canetb5042a32014-03-03 19:11:34 +01004633/* This function will be called by the bdrv_recurse_is_first_non_filter method
4634 * of block filter and by bdrv_is_first_non_filter.
4635 * It is used to test if the given bs is the candidate or recurse more in the
4636 * node graph.
Benoît Canet212a5a82014-01-23 21:31:36 +01004637 */
Benoît Canet212a5a82014-01-23 21:31:36 +01004638bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
4639 BlockDriverState *candidate)
Benoît Canetf6186f42013-10-02 14:33:48 +02004640{
Benoît Canetb5042a32014-03-03 19:11:34 +01004641 /* return false if basic checks fails */
4642 if (!bs || !bs->drv) {
4643 return false;
4644 }
4645
4646 /* the code reached a non block filter driver -> check if the bs is
4647 * the same as the candidate. It's the recursion termination condition.
4648 */
4649 if (!bs->drv->is_filter) {
4650 return bs == candidate;
4651 }
4652 /* Down this path the driver is a block filter driver */
4653
4654 /* If the block filter recursion method is defined use it to recurse down
4655 * the node graph.
4656 */
4657 if (bs->drv->bdrv_recurse_is_first_non_filter) {
Benoît Canet212a5a82014-01-23 21:31:36 +01004658 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
4659 }
4660
Benoît Canetb5042a32014-03-03 19:11:34 +01004661 /* the driver is a block filter but don't allow to recurse -> return false
4662 */
4663 return false;
Benoît Canet212a5a82014-01-23 21:31:36 +01004664}
4665
4666/* This function checks if the candidate is the first non filter bs down it's
4667 * bs chain. Since we don't have pointers to parents it explore all bs chains
4668 * from the top. Some filters can choose not to pass down the recursion.
4669 */
4670bool bdrv_is_first_non_filter(BlockDriverState *candidate)
4671{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01004672 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02004673 BdrvNextIterator it;
Benoît Canet212a5a82014-01-23 21:31:36 +01004674
4675 /* walk down the bs forest recursively */
Kevin Wolf88be7b42016-05-20 18:49:07 +02004676 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Benoît Canet212a5a82014-01-23 21:31:36 +01004677 bool perm;
4678
Benoît Canetb5042a32014-03-03 19:11:34 +01004679 /* try to recurse in this top level bs */
Kevin Wolfe6dc8a12014-02-04 11:45:31 +01004680 perm = bdrv_recurse_is_first_non_filter(bs, candidate);
Benoît Canet212a5a82014-01-23 21:31:36 +01004681
4682 /* candidate is the first non filter */
4683 if (perm) {
4684 return true;
4685 }
4686 }
4687
4688 return false;
Benoît Canetf6186f42013-10-02 14:33:48 +02004689}
Benoît Canet09158f02014-06-27 18:25:25 +02004690
Wen Congyange12f3782015-07-17 10:12:22 +08004691BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
4692 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02004693{
4694 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004695 AioContext *aio_context;
4696
Benoît Canet09158f02014-06-27 18:25:25 +02004697 if (!to_replace_bs) {
4698 error_setg(errp, "Node name '%s' not found", node_name);
4699 return NULL;
4700 }
4701
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004702 aio_context = bdrv_get_aio_context(to_replace_bs);
4703 aio_context_acquire(aio_context);
4704
Benoît Canet09158f02014-06-27 18:25:25 +02004705 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004706 to_replace_bs = NULL;
4707 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02004708 }
4709
4710 /* We don't want arbitrary node of the BDS chain to be replaced only the top
4711 * most non filter in order to prevent data corruption.
4712 * Another benefit is that this tests exclude backing files which are
4713 * blocked by the backing blockers.
4714 */
Wen Congyange12f3782015-07-17 10:12:22 +08004715 if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
Benoît Canet09158f02014-06-27 18:25:25 +02004716 error_setg(errp, "Only top most non filter can be replaced");
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004717 to_replace_bs = NULL;
4718 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02004719 }
4720
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004721out:
4722 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02004723 return to_replace_bs;
4724}
Ming Lei448ad912014-07-04 18:04:33 +08004725
Max Reitz91af7012014-07-18 20:24:56 +02004726static bool append_open_options(QDict *d, BlockDriverState *bs)
4727{
4728 const QDictEntry *entry;
Kevin Wolf9e700c12015-04-24 15:20:28 +02004729 QemuOptDesc *desc;
Kevin Wolf260fecf2015-04-27 13:46:22 +02004730 BdrvChild *child;
Max Reitz91af7012014-07-18 20:24:56 +02004731 bool found_any = false;
Kevin Wolf260fecf2015-04-27 13:46:22 +02004732 const char *p;
Max Reitz91af7012014-07-18 20:24:56 +02004733
4734 for (entry = qdict_first(bs->options); entry;
4735 entry = qdict_next(bs->options, entry))
4736 {
Kevin Wolf260fecf2015-04-27 13:46:22 +02004737 /* Exclude options for children */
4738 QLIST_FOREACH(child, &bs->children, next) {
4739 if (strstart(qdict_entry_key(entry), child->name, &p)
4740 && (!*p || *p == '.'))
4741 {
4742 break;
4743 }
4744 }
4745 if (child) {
Kevin Wolf9e700c12015-04-24 15:20:28 +02004746 continue;
Max Reitz91af7012014-07-18 20:24:56 +02004747 }
Kevin Wolf9e700c12015-04-24 15:20:28 +02004748
4749 /* And exclude all non-driver-specific options */
4750 for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
4751 if (!strcmp(qdict_entry_key(entry), desc->name)) {
4752 break;
4753 }
4754 }
4755 if (desc->name) {
4756 continue;
4757 }
4758
4759 qobject_incref(qdict_entry_value(entry));
4760 qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
4761 found_any = true;
Max Reitz91af7012014-07-18 20:24:56 +02004762 }
4763
4764 return found_any;
4765}
4766
4767/* Updates the following BDS fields:
4768 * - exact_filename: A filename which may be used for opening a block device
4769 * which (mostly) equals the given BDS (even without any
4770 * other options; so reading and writing must return the same
4771 * results, but caching etc. may be different)
4772 * - full_open_options: Options which, when given when opening a block device
4773 * (without a filename), result in a BDS (mostly)
4774 * equalling the given one
4775 * - filename: If exact_filename is set, it is copied here. Otherwise,
4776 * full_open_options is converted to a JSON object, prefixed with
4777 * "json:" (for use through the JSON pseudo protocol) and put here.
4778 */
4779void bdrv_refresh_filename(BlockDriverState *bs)
4780{
4781 BlockDriver *drv = bs->drv;
4782 QDict *opts;
4783
4784 if (!drv) {
4785 return;
4786 }
4787
4788 /* This BDS's file name will most probably depend on its file's name, so
4789 * refresh that first */
4790 if (bs->file) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004791 bdrv_refresh_filename(bs->file->bs);
Max Reitz91af7012014-07-18 20:24:56 +02004792 }
4793
4794 if (drv->bdrv_refresh_filename) {
4795 /* Obsolete information is of no use here, so drop the old file name
4796 * information before refreshing it */
4797 bs->exact_filename[0] = '\0';
4798 if (bs->full_open_options) {
4799 QDECREF(bs->full_open_options);
4800 bs->full_open_options = NULL;
4801 }
4802
Kevin Wolf4cdd01d2015-04-27 13:50:54 +02004803 opts = qdict_new();
4804 append_open_options(opts, bs);
4805 drv->bdrv_refresh_filename(bs, opts);
4806 QDECREF(opts);
Max Reitz91af7012014-07-18 20:24:56 +02004807 } else if (bs->file) {
4808 /* Try to reconstruct valid information from the underlying file */
4809 bool has_open_options;
4810
4811 bs->exact_filename[0] = '\0';
4812 if (bs->full_open_options) {
4813 QDECREF(bs->full_open_options);
4814 bs->full_open_options = NULL;
4815 }
4816
4817 opts = qdict_new();
4818 has_open_options = append_open_options(opts, bs);
4819
4820 /* If no specific options have been given for this BDS, the filename of
4821 * the underlying file should suffice for this one as well */
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004822 if (bs->file->bs->exact_filename[0] && !has_open_options) {
4823 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
Max Reitz91af7012014-07-18 20:24:56 +02004824 }
4825 /* Reconstructing the full options QDict is simple for most format block
4826 * drivers, as long as the full options are known for the underlying
4827 * file BDS. The full options QDict of that file BDS should somehow
4828 * contain a representation of the filename, therefore the following
4829 * suffices without querying the (exact_)filename of this BDS. */
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004830 if (bs->file->bs->full_open_options) {
Eric Blake46f5ac22017-04-27 16:58:17 -05004831 qdict_put_str(opts, "driver", drv->format_name);
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004832 QINCREF(bs->file->bs->full_open_options);
Eric Blakede6e7952017-04-27 16:58:15 -05004833 qdict_put(opts, "file", bs->file->bs->full_open_options);
Max Reitz91af7012014-07-18 20:24:56 +02004834
4835 bs->full_open_options = opts;
4836 } else {
4837 QDECREF(opts);
4838 }
4839 } else if (!bs->full_open_options && qdict_size(bs->options)) {
4840 /* There is no underlying file BDS (at least referenced by BDS.file),
4841 * so the full options QDict should be equal to the options given
4842 * specifically for this block device when it was opened (plus the
4843 * driver specification).
4844 * Because those options don't change, there is no need to update
4845 * full_open_options when it's already set. */
4846
4847 opts = qdict_new();
4848 append_open_options(opts, bs);
Eric Blake46f5ac22017-04-27 16:58:17 -05004849 qdict_put_str(opts, "driver", drv->format_name);
Max Reitz91af7012014-07-18 20:24:56 +02004850
4851 if (bs->exact_filename[0]) {
4852 /* This may not work for all block protocol drivers (some may
4853 * require this filename to be parsed), but we have to find some
4854 * default solution here, so just include it. If some block driver
4855 * does not support pure options without any filename at all or
4856 * needs some special format of the options QDict, it needs to
4857 * implement the driver-specific bdrv_refresh_filename() function.
4858 */
Eric Blake46f5ac22017-04-27 16:58:17 -05004859 qdict_put_str(opts, "filename", bs->exact_filename);
Max Reitz91af7012014-07-18 20:24:56 +02004860 }
4861
4862 bs->full_open_options = opts;
4863 }
4864
4865 if (bs->exact_filename[0]) {
4866 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
4867 } else if (bs->full_open_options) {
4868 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
4869 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
4870 qstring_get_str(json));
4871 QDECREF(json);
4872 }
4873}
Wen Congyange06018a2016-05-10 15:36:37 +08004874
4875/*
4876 * Hot add/remove a BDS's child. So the user can take a child offline when
4877 * it is broken and take a new child online
4878 */
4879void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
4880 Error **errp)
4881{
4882
4883 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
4884 error_setg(errp, "The node %s does not support adding a child",
4885 bdrv_get_device_or_node_name(parent_bs));
4886 return;
4887 }
4888
4889 if (!QLIST_EMPTY(&child_bs->parents)) {
4890 error_setg(errp, "The node %s already has a parent",
4891 child_bs->node_name);
4892 return;
4893 }
4894
4895 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
4896}
4897
4898void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
4899{
4900 BdrvChild *tmp;
4901
4902 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
4903 error_setg(errp, "The node %s does not support removing a child",
4904 bdrv_get_device_or_node_name(parent_bs));
4905 return;
4906 }
4907
4908 QLIST_FOREACH(tmp, &parent_bs->children, next) {
4909 if (tmp == child) {
4910 break;
4911 }
4912 }
4913
4914 if (!tmp) {
4915 error_setg(errp, "The node %s does not have a child named %s",
4916 bdrv_get_device_or_node_name(parent_bs),
4917 bdrv_get_device_or_node_name(child->bs));
4918 return;
4919 }
4920
4921 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
4922}
Vladimir Sementsov-Ogievskiy67b792f2017-06-28 15:05:21 +03004923
4924bool bdrv_can_store_new_dirty_bitmap(BlockDriverState *bs, const char *name,
4925 uint32_t granularity, Error **errp)
4926{
4927 BlockDriver *drv = bs->drv;
4928
4929 if (!drv) {
4930 error_setg_errno(errp, ENOMEDIUM,
4931 "Can't store persistent bitmaps to %s",
4932 bdrv_get_device_or_node_name(bs));
4933 return false;
4934 }
4935
4936 if (!drv->bdrv_can_store_new_dirty_bitmap) {
4937 error_setg_errno(errp, ENOTSUP,
4938 "Can't store persistent bitmaps to %s",
4939 bdrv_get_device_or_node_name(bs));
4940 return false;
4941 }
4942
4943 return drv->bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp);
4944}