blob: 67ae35a47acf9b35f1559a28e08e2d9d3313cc98 [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 {
166 p = strchr(base_path, ':');
167 if (p)
168 p++;
169 else
170 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000171 p1 = strrchr(base_path, '/');
172#ifdef _WIN32
173 {
174 const char *p2;
175 p2 = strrchr(base_path, '\\');
176 if (!p1 || p2 > p1)
177 p1 = p2;
178 }
179#endif
bellard83f64092006-08-01 16:21:11 +0000180 if (p1)
181 p1++;
182 else
183 p1 = base_path;
184 if (p1 > p)
185 p = p1;
186 len = p - base_path;
187 if (len > dest_size - 1)
188 len = dest_size - 1;
189 memcpy(dest, base_path, len);
190 dest[len] = '\0';
191 pstrcat(dest, dest_size, filename);
192 }
193}
194
Jeff Codye2b82472017-04-07 16:55:26 -0400195int bdrv_set_read_only(BlockDriverState *bs, bool read_only, Error **errp)
Jeff Codyfe5241b2017-04-07 16:55:25 -0400196{
Jeff Codye2b82472017-04-07 16:55:26 -0400197 /* Do not set read_only if copy_on_read is enabled */
198 if (bs->copy_on_read && read_only) {
199 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
200 bdrv_get_device_or_node_name(bs));
201 return -EINVAL;
202 }
203
Jeff Codyfe5241b2017-04-07 16:55:25 -0400204 bs->read_only = read_only;
Jeff Codye2b82472017-04-07 16:55:26 -0400205 return 0;
Jeff Codyfe5241b2017-04-07 16:55:25 -0400206}
207
Max Reitz0a828552014-11-26 17:20:25 +0100208void bdrv_get_full_backing_filename_from_filename(const char *backed,
209 const char *backing,
Max Reitz9f074292014-11-26 17:20:26 +0100210 char *dest, size_t sz,
211 Error **errp)
Max Reitz0a828552014-11-26 17:20:25 +0100212{
Max Reitz9f074292014-11-26 17:20:26 +0100213 if (backing[0] == '\0' || path_has_protocol(backing) ||
214 path_is_absolute(backing))
215 {
Max Reitz0a828552014-11-26 17:20:25 +0100216 pstrcpy(dest, sz, backing);
Max Reitz9f074292014-11-26 17:20:26 +0100217 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
218 error_setg(errp, "Cannot use relative backing file names for '%s'",
219 backed);
Max Reitz0a828552014-11-26 17:20:25 +0100220 } else {
221 path_combine(dest, sz, backed, backing);
222 }
223}
224
Max Reitz9f074292014-11-26 17:20:26 +0100225void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
226 Error **errp)
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200227{
Max Reitz9f074292014-11-26 17:20:26 +0100228 char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
229
230 bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
231 dest, sz, errp);
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200232}
233
Stefan Hajnoczi0eb72172015-04-28 14:27:51 +0100234void bdrv_register(BlockDriver *bdrv)
235{
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100236 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000237}
bellardb3380822004-03-14 21:38:54 +0000238
Markus Armbrustere4e99862014-10-07 13:59:03 +0200239BlockDriverState *bdrv_new(void)
240{
241 BlockDriverState *bs;
242 int i;
243
Markus Armbruster5839e532014-08-19 10:31:08 +0200244 bs = g_new0(BlockDriverState, 1);
Fam Zhenge4654d22013-11-13 18:29:43 +0800245 QLIST_INIT(&bs->dirty_bitmaps);
Fam Zhengfbe40ff2014-05-23 21:29:42 +0800246 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
247 QLIST_INIT(&bs->op_blockers[i]);
248 }
Stefan Hajnoczid616b222013-06-24 17:13:10 +0200249 notifier_with_return_list_init(&bs->before_write_notifiers);
Fam Zheng9fcb0252013-08-23 09:14:46 +0800250 bs->refcnt = 1;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +0200251 bs->aio_context = qemu_get_aio_context();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200252
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +0300253 qemu_co_queue_init(&bs->flush_queue);
254
Max Reitz2c1d04e2016-01-29 16:36:11 +0100255 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
256
bellardb3380822004-03-14 21:38:54 +0000257 return bs;
258}
259
Marc Mari88d88792016-08-12 09:27:03 -0400260static BlockDriver *bdrv_do_find_format(const char *format_name)
bellardea2384d2004-08-01 21:59:26 +0000261{
262 BlockDriver *drv1;
Marc Mari88d88792016-08-12 09:27:03 -0400263
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100264 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
265 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000266 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100267 }
bellardea2384d2004-08-01 21:59:26 +0000268 }
Marc Mari88d88792016-08-12 09:27:03 -0400269
bellardea2384d2004-08-01 21:59:26 +0000270 return NULL;
271}
272
Marc Mari88d88792016-08-12 09:27:03 -0400273BlockDriver *bdrv_find_format(const char *format_name)
274{
275 BlockDriver *drv1;
276 int i;
277
278 drv1 = bdrv_do_find_format(format_name);
279 if (drv1) {
280 return drv1;
281 }
282
283 /* The driver isn't registered, maybe we need to load a module */
284 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
285 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
286 block_module_load_one(block_driver_modules[i].library_name);
287 break;
288 }
289 }
290
291 return bdrv_do_find_format(format_name);
292}
293
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800294static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
Markus Armbrustereb852012009-10-27 18:41:44 +0100295{
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800296 static const char *whitelist_rw[] = {
297 CONFIG_BDRV_RW_WHITELIST
298 };
299 static const char *whitelist_ro[] = {
300 CONFIG_BDRV_RO_WHITELIST
Markus Armbrustereb852012009-10-27 18:41:44 +0100301 };
302 const char **p;
303
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800304 if (!whitelist_rw[0] && !whitelist_ro[0]) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100305 return 1; /* no whitelist, anything goes */
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800306 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100307
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800308 for (p = whitelist_rw; *p; p++) {
Markus Armbrustereb852012009-10-27 18:41:44 +0100309 if (!strcmp(drv->format_name, *p)) {
310 return 1;
311 }
312 }
Fam Zhengb64ec4e2013-05-29 19:35:40 +0800313 if (read_only) {
314 for (p = whitelist_ro; *p; p++) {
315 if (!strcmp(drv->format_name, *p)) {
316 return 1;
317 }
318 }
319 }
Markus Armbrustereb852012009-10-27 18:41:44 +0100320 return 0;
321}
322
Daniel P. Berrangee6ff69b2016-03-21 14:11:48 +0000323bool bdrv_uses_whitelist(void)
324{
325 return use_bdrv_whitelist;
326}
327
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800328typedef struct CreateCo {
329 BlockDriver *drv;
330 char *filename;
Chunyan Liu83d05212014-06-05 17:20:51 +0800331 QemuOpts *opts;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800332 int ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200333 Error *err;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800334} CreateCo;
335
336static void coroutine_fn bdrv_create_co_entry(void *opaque)
337{
Max Reitzcc84d902013-09-06 17:14:26 +0200338 Error *local_err = NULL;
339 int ret;
340
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800341 CreateCo *cco = opaque;
342 assert(cco->drv);
343
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800344 ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300345 error_propagate(&cco->err, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200346 cco->ret = ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800347}
348
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200349int bdrv_create(BlockDriver *drv, const char* filename,
Chunyan Liu83d05212014-06-05 17:20:51 +0800350 QemuOpts *opts, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000351{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800352 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200353
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800354 Coroutine *co;
355 CreateCo cco = {
356 .drv = drv,
357 .filename = g_strdup(filename),
Chunyan Liu83d05212014-06-05 17:20:51 +0800358 .opts = opts,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800359 .ret = NOT_DONE,
Max Reitzcc84d902013-09-06 17:14:26 +0200360 .err = NULL,
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800361 };
362
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800363 if (!drv->bdrv_create) {
Max Reitzcc84d902013-09-06 17:14:26 +0200364 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300365 ret = -ENOTSUP;
366 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800367 }
368
369 if (qemu_in_coroutine()) {
370 /* Fast-path if already in coroutine context */
371 bdrv_create_co_entry(&cco);
372 } else {
Paolo Bonzini0b8b8752016-07-04 19:10:01 +0200373 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
374 qemu_coroutine_enter(co);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800375 while (cco.ret == NOT_DONE) {
Paolo Bonzinib47ec2c2014-07-07 15:18:01 +0200376 aio_poll(qemu_get_aio_context(), true);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800377 }
378 }
379
380 ret = cco.ret;
Max Reitzcc84d902013-09-06 17:14:26 +0200381 if (ret < 0) {
Markus Armbruster84d18f02014-01-30 15:07:28 +0100382 if (cco.err) {
Max Reitzcc84d902013-09-06 17:14:26 +0200383 error_propagate(errp, cco.err);
384 } else {
385 error_setg_errno(errp, -ret, "Could not create image");
386 }
387 }
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800388
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300389out:
390 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800391 return ret;
bellardea2384d2004-08-01 21:59:26 +0000392}
393
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800394int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200395{
396 BlockDriver *drv;
Max Reitzcc84d902013-09-06 17:14:26 +0200397 Error *local_err = NULL;
398 int ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200399
Max Reitzb65a5e12015-02-05 13:58:12 -0500400 drv = bdrv_find_protocol(filename, true, errp);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200401 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000402 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200403 }
404
Chunyan Liuc282e1f2014-06-05 17:21:11 +0800405 ret = bdrv_create(drv, filename, opts, &local_err);
Eduardo Habkost621ff942016-06-13 18:57:56 -0300406 error_propagate(errp, local_err);
Max Reitzcc84d902013-09-06 17:14:26 +0200407 return ret;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200408}
409
Ekaterina Tumanova892b7de2015-02-16 12:47:54 +0100410/**
411 * Try to get @bs's logical and physical block size.
412 * On success, store them in @bsz struct and return 0.
413 * On failure return -errno.
414 * @bs must not be empty.
415 */
416int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
417{
418 BlockDriver *drv = bs->drv;
419
420 if (drv && drv->bdrv_probe_blocksizes) {
421 return drv->bdrv_probe_blocksizes(bs, bsz);
422 }
423
424 return -ENOTSUP;
425}
426
427/**
428 * Try to get @bs's geometry (cyls, heads, sectors).
429 * On success, store them in @geo struct and return 0.
430 * On failure return -errno.
431 * @bs must not be empty.
432 */
433int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
434{
435 BlockDriver *drv = bs->drv;
436
437 if (drv && drv->bdrv_probe_geometry) {
438 return drv->bdrv_probe_geometry(bs, geo);
439 }
440
441 return -ENOTSUP;
442}
443
Jim Meyeringeba25052012-05-28 09:27:54 +0200444/*
445 * Create a uniquely-named empty temporary file.
446 * Return 0 upon success, otherwise a negative errno value.
447 */
448int get_tmp_filename(char *filename, int size)
449{
bellardd5249392004-08-03 21:14:23 +0000450#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000451 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200452 /* GetTempFileName requires that its output buffer (4th param)
453 have length MAX_PATH or greater. */
454 assert(size >= MAX_PATH);
455 return (GetTempPath(MAX_PATH, temp_dir)
456 && GetTempFileName(temp_dir, "qem", 0, filename)
457 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000458#else
bellardea2384d2004-08-01 21:59:26 +0000459 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000460 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000461 tmpdir = getenv("TMPDIR");
Amit Shah69bef792014-02-26 15:12:37 +0530462 if (!tmpdir) {
463 tmpdir = "/var/tmp";
464 }
Jim Meyeringeba25052012-05-28 09:27:54 +0200465 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
466 return -EOVERFLOW;
467 }
bellardea2384d2004-08-01 21:59:26 +0000468 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800469 if (fd < 0) {
470 return -errno;
471 }
472 if (close(fd) != 0) {
473 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200474 return -errno;
475 }
476 return 0;
bellardd5249392004-08-03 21:14:23 +0000477#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200478}
bellardea2384d2004-08-01 21:59:26 +0000479
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200480/*
481 * Detect host devices. By convention, /dev/cdrom[N] is always
482 * recognized as a host CDROM.
483 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200484static BlockDriver *find_hdev_driver(const char *filename)
485{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200486 int score_max = 0, score;
487 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200488
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100489 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200490 if (d->bdrv_probe_device) {
491 score = d->bdrv_probe_device(filename);
492 if (score > score_max) {
493 score_max = score;
494 drv = d;
495 }
496 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200497 }
498
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200499 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200500}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200501
Marc Mari88d88792016-08-12 09:27:03 -0400502static BlockDriver *bdrv_do_find_protocol(const char *protocol)
503{
504 BlockDriver *drv1;
505
506 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
507 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
508 return drv1;
509 }
510 }
511
512 return NULL;
513}
514
Kevin Wolf98289622013-07-10 15:47:39 +0200515BlockDriver *bdrv_find_protocol(const char *filename,
Max Reitzb65a5e12015-02-05 13:58:12 -0500516 bool allow_protocol_prefix,
517 Error **errp)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200518{
519 BlockDriver *drv1;
520 char protocol[128];
521 int len;
522 const char *p;
Marc Mari88d88792016-08-12 09:27:03 -0400523 int i;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200524
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200525 /* TODO Drivers without bdrv_file_open must be specified explicitly */
526
Christoph Hellwig39508e72010-06-23 12:25:17 +0200527 /*
528 * XXX(hch): we really should not let host device detection
529 * override an explicit protocol specification, but moving this
530 * later breaks access to device names with colons in them.
531 * Thanks to the brain-dead persistent naming schemes on udev-
532 * based Linux systems those actually are quite common.
533 */
534 drv1 = find_hdev_driver(filename);
535 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200536 return drv1;
537 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200538
Kevin Wolf98289622013-07-10 15:47:39 +0200539 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
Max Reitzef810432014-12-02 18:32:42 +0100540 return &bdrv_file;
Christoph Hellwig39508e72010-06-23 12:25:17 +0200541 }
Kevin Wolf98289622013-07-10 15:47:39 +0200542
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000543 p = strchr(filename, ':');
544 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200545 len = p - filename;
546 if (len > sizeof(protocol) - 1)
547 len = sizeof(protocol) - 1;
548 memcpy(protocol, filename, len);
549 protocol[len] = '\0';
Marc Mari88d88792016-08-12 09:27:03 -0400550
551 drv1 = bdrv_do_find_protocol(protocol);
552 if (drv1) {
553 return drv1;
554 }
555
556 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
557 if (block_driver_modules[i].protocol_name &&
558 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
559 block_module_load_one(block_driver_modules[i].library_name);
560 break;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200561 }
562 }
Max Reitzb65a5e12015-02-05 13:58:12 -0500563
Marc Mari88d88792016-08-12 09:27:03 -0400564 drv1 = bdrv_do_find_protocol(protocol);
565 if (!drv1) {
566 error_setg(errp, "Unknown protocol '%s'", protocol);
567 }
568 return drv1;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200569}
570
Markus Armbrusterc6684242014-11-20 16:27:10 +0100571/*
572 * Guess image format by probing its contents.
573 * This is not a good idea when your image is raw (CVE-2008-2004), but
574 * we do it anyway for backward compatibility.
575 *
576 * @buf contains the image's first @buf_size bytes.
Kevin Wolf7cddd372014-11-20 16:27:11 +0100577 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
578 * but can be smaller if the image file is smaller)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100579 * @filename is its filename.
580 *
581 * For all block drivers, call the bdrv_probe() method to get its
582 * probing score.
583 * Return the first block driver with the highest probing score.
584 */
Kevin Wolf38f3ef52014-11-20 16:27:12 +0100585BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
586 const char *filename)
Markus Armbrusterc6684242014-11-20 16:27:10 +0100587{
588 int score_max = 0, score;
589 BlockDriver *drv = NULL, *d;
590
591 QLIST_FOREACH(d, &bdrv_drivers, list) {
592 if (d->bdrv_probe) {
593 score = d->bdrv_probe(buf, buf_size, filename);
594 if (score > score_max) {
595 score_max = score;
596 drv = d;
597 }
598 }
599 }
600
601 return drv;
602}
603
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100604static int find_image_format(BlockBackend *file, const char *filename,
Max Reitz34b5d2c2013-09-05 14:45:29 +0200605 BlockDriver **pdrv, Error **errp)
bellardea2384d2004-08-01 21:59:26 +0000606{
Markus Armbrusterc6684242014-11-20 16:27:10 +0100607 BlockDriver *drv;
Kevin Wolf7cddd372014-11-20 16:27:11 +0100608 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
Kevin Wolff500a6d2012-11-12 17:35:27 +0100609 int ret = 0;
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700610
Kevin Wolf08a00552010-06-01 18:37:31 +0200611 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100612 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
Max Reitzef810432014-12-02 18:32:42 +0100613 *pdrv = &bdrv_raw;
Stefan Weilc98ac352010-07-21 21:51:51 +0200614 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700615 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700616
Kevin Wolf5696c6e2017-02-17 18:39:24 +0100617 ret = blk_pread(file, 0, buf, sizeof(buf));
bellard83f64092006-08-01 16:21:11 +0000618 if (ret < 0) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200619 error_setg_errno(errp, -ret, "Could not read image for determining its "
620 "format");
Stefan Weilc98ac352010-07-21 21:51:51 +0200621 *pdrv = NULL;
622 return ret;
bellard83f64092006-08-01 16:21:11 +0000623 }
624
Markus Armbrusterc6684242014-11-20 16:27:10 +0100625 drv = bdrv_probe_all(buf, ret, filename);
Stefan Weilc98ac352010-07-21 21:51:51 +0200626 if (!drv) {
Max Reitz34b5d2c2013-09-05 14:45:29 +0200627 error_setg(errp, "Could not determine image format: No compatible "
628 "driver found");
Stefan Weilc98ac352010-07-21 21:51:51 +0200629 ret = -ENOENT;
630 }
631 *pdrv = drv;
632 return ret;
bellardea2384d2004-08-01 21:59:26 +0000633}
634
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100635/**
636 * Set the current 'total_sectors' value
Markus Armbruster65a9bb22014-06-26 13:23:17 +0200637 * Return 0 on success, -errno on error.
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100638 */
639static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
640{
641 BlockDriver *drv = bs->drv;
642
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700643 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
Dimitris Aragiorgisb192af82015-06-23 13:44:56 +0300644 if (bdrv_is_sg(bs))
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700645 return 0;
646
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100647 /* query actual device if possible, otherwise just trust the hint */
648 if (drv->bdrv_getlength) {
649 int64_t length = drv->bdrv_getlength(bs);
650 if (length < 0) {
651 return length;
652 }
Fam Zheng7e382002013-11-06 19:48:06 +0800653 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100654 }
655
656 bs->total_sectors = hint;
657 return 0;
658}
659
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100660/**
Kevin Wolfcddff5b2015-11-16 16:43:27 +0100661 * Combines a QDict of new block driver @options with any missing options taken
662 * from @old_options, so that leaving out an option defaults to its old value.
663 */
664static void bdrv_join_options(BlockDriverState *bs, QDict *options,
665 QDict *old_options)
666{
667 if (bs->drv && bs->drv->bdrv_join_options) {
668 bs->drv->bdrv_join_options(options, old_options);
669 } else {
670 qdict_join(options, old_options, false);
671 }
672}
673
674/**
Paolo Bonzini9e8f1832013-02-08 14:06:11 +0100675 * Set open flags for a given discard mode
676 *
677 * Return 0 on success, -1 if the discard mode was invalid.
678 */
679int bdrv_parse_discard_flags(const char *mode, int *flags)
680{
681 *flags &= ~BDRV_O_UNMAP;
682
683 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
684 /* do nothing */
685 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
686 *flags |= BDRV_O_UNMAP;
687 } else {
688 return -1;
689 }
690
691 return 0;
692}
693
694/**
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100695 * Set open flags for a given cache mode
696 *
697 * Return 0 on success, -1 if the cache mode was invalid.
698 */
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100699int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100700{
701 *flags &= ~BDRV_O_CACHE_MASK;
702
703 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100704 *writethrough = false;
705 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100706 } else if (!strcmp(mode, "directsync")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100707 *writethrough = true;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100708 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100709 } else if (!strcmp(mode, "writeback")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100710 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100711 } else if (!strcmp(mode, "unsafe")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100712 *writethrough = false;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100713 *flags |= BDRV_O_NO_FLUSH;
714 } else if (!strcmp(mode, "writethrough")) {
Kevin Wolf53e8ae02016-03-18 15:36:58 +0100715 *writethrough = true;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100716 } else {
717 return -1;
718 }
719
720 return 0;
721}
722
Kevin Wolfb5411552017-01-17 15:56:16 +0100723static char *bdrv_child_get_parent_desc(BdrvChild *c)
724{
725 BlockDriverState *parent = c->opaque;
726 return g_strdup(bdrv_get_device_or_node_name(parent));
727}
728
Kevin Wolf20018e12016-05-23 18:46:59 +0200729static void bdrv_child_cb_drained_begin(BdrvChild *child)
730{
731 BlockDriverState *bs = child->opaque;
732 bdrv_drained_begin(bs);
733}
734
735static void bdrv_child_cb_drained_end(BdrvChild *child)
736{
737 BlockDriverState *bs = child->opaque;
738 bdrv_drained_end(bs);
739}
740
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200741/*
Kevin Wolf73176be2016-03-07 13:02:15 +0100742 * Returns the options and flags that a temporary snapshot should get, based on
743 * the originally requested flags (the originally requested image will have
744 * flags like a backing file)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +0200745 */
Kevin Wolf73176be2016-03-07 13:02:15 +0100746static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
747 int parent_flags, QDict *parent_options)
Kevin Wolfb1e6fc02014-05-06 12:11:42 +0200748{
Kevin Wolf73176be2016-03-07 13:02:15 +0100749 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
750
751 /* For temporary files, unconditional cache=unsafe is fine */
Kevin Wolf73176be2016-03-07 13:02:15 +0100752 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
753 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
Kevin Wolf41869042016-06-16 12:59:30 +0200754
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300755 /* Copy the read-only option from the parent */
756 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
757
Kevin Wolf41869042016-06-16 12:59:30 +0200758 /* aio=native doesn't work for cache.direct=off, so disable it for the
759 * temporary snapshot */
760 *child_flags &= ~BDRV_O_NATIVE_AIO;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +0200761}
762
763/*
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200764 * Returns the options and flags that bs->file should get if a protocol driver
765 * is expected, based on the given options and flags for the parent BDS
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200766 */
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200767static void bdrv_inherited_options(int *child_flags, QDict *child_options,
768 int parent_flags, QDict *parent_options)
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200769{
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200770 int flags = parent_flags;
771
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200772 /* Enable protocol handling, disable format probing for bs->file */
773 flags |= BDRV_O_PROTOCOL;
774
Kevin Wolf91a097e2015-05-08 17:49:53 +0200775 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
776 * the parent. */
777 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
778 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
779
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300780 /* Inherit the read-only option from the parent if it's not set */
781 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
782
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200783 /* Our block drivers take care to send flushes and respect unmap policy,
Kevin Wolf91a097e2015-05-08 17:49:53 +0200784 * so we can default to enable both on lower layers regardless of the
785 * corresponding parent options. */
Kevin Wolf818584a2016-09-12 18:03:18 +0200786 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200787
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200788 /* Clear flags that only apply to the top layer */
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000789 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
790 BDRV_O_NO_IO);
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200791
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200792 *child_flags = flags;
Kevin Wolf0b50cc82014-04-11 21:29:52 +0200793}
794
Kevin Wolff3930ed2015-04-08 13:43:47 +0200795const BdrvChildRole child_file = {
Kevin Wolfb5411552017-01-17 15:56:16 +0100796 .get_parent_desc = bdrv_child_get_parent_desc,
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200797 .inherit_options = bdrv_inherited_options,
Kevin Wolf20018e12016-05-23 18:46:59 +0200798 .drained_begin = bdrv_child_cb_drained_begin,
799 .drained_end = bdrv_child_cb_drained_end,
Kevin Wolff3930ed2015-04-08 13:43:47 +0200800};
801
802/*
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200803 * Returns the options and flags that bs->file should get if the use of formats
804 * (and not only protocols) is permitted for it, based on the given options and
805 * flags for the parent BDS
Kevin Wolff3930ed2015-04-08 13:43:47 +0200806 */
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200807static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
808 int parent_flags, QDict *parent_options)
Kevin Wolff3930ed2015-04-08 13:43:47 +0200809{
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200810 child_file.inherit_options(child_flags, child_options,
811 parent_flags, parent_options);
812
Daniel P. Berrangeabb06c52016-03-21 14:11:42 +0000813 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
Kevin Wolff3930ed2015-04-08 13:43:47 +0200814}
815
816const BdrvChildRole child_format = {
Kevin Wolfb5411552017-01-17 15:56:16 +0100817 .get_parent_desc = bdrv_child_get_parent_desc,
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200818 .inherit_options = bdrv_inherited_fmt_options,
Kevin Wolf20018e12016-05-23 18:46:59 +0200819 .drained_begin = bdrv_child_cb_drained_begin,
820 .drained_end = bdrv_child_cb_drained_end,
Kevin Wolff3930ed2015-04-08 13:43:47 +0200821};
822
Kevin Wolfdb95dbb2017-02-08 11:28:52 +0100823static void bdrv_backing_attach(BdrvChild *c)
824{
825 BlockDriverState *parent = c->opaque;
826 BlockDriverState *backing_hd = c->bs;
827
828 assert(!parent->backing_blocker);
829 error_setg(&parent->backing_blocker,
830 "node is used as backing hd of '%s'",
831 bdrv_get_device_or_node_name(parent));
832
833 parent->open_flags &= ~BDRV_O_NO_BACKING;
834 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
835 backing_hd->filename);
836 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
837 backing_hd->drv ? backing_hd->drv->format_name : "");
838
839 bdrv_op_block_all(backing_hd, parent->backing_blocker);
840 /* Otherwise we won't be able to commit or stream */
841 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
842 parent->backing_blocker);
843 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
844 parent->backing_blocker);
845 /*
846 * We do backup in 3 ways:
847 * 1. drive backup
848 * The target bs is new opened, and the source is top BDS
849 * 2. blockdev backup
850 * Both the source and the target are top BDSes.
851 * 3. internal backup(used for block replication)
852 * Both the source and the target are backing file
853 *
854 * In case 1 and 2, neither the source nor the target is the backing file.
855 * In case 3, we will block the top BDS, so there is only one block job
856 * for the top BDS and its backing chain.
857 */
858 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
859 parent->backing_blocker);
860 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
861 parent->backing_blocker);
862}
863
864static void bdrv_backing_detach(BdrvChild *c)
865{
866 BlockDriverState *parent = c->opaque;
867
868 assert(parent->backing_blocker);
869 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
870 error_free(parent->backing_blocker);
871 parent->backing_blocker = NULL;
872}
873
Kevin Wolf317fc442014-04-25 13:27:34 +0200874/*
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200875 * Returns the options and flags that bs->backing should get, based on the
876 * given options and flags for the parent BDS
Kevin Wolf317fc442014-04-25 13:27:34 +0200877 */
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200878static void bdrv_backing_options(int *child_flags, QDict *child_options,
879 int parent_flags, QDict *parent_options)
Kevin Wolf317fc442014-04-25 13:27:34 +0200880{
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200881 int flags = parent_flags;
882
Kevin Wolfb8816a42016-03-04 14:52:32 +0100883 /* The cache mode is inherited unmodified for backing files; except WCE,
884 * which is only applied on the top level (BlockBackend) */
Kevin Wolf91a097e2015-05-08 17:49:53 +0200885 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
886 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
887
Kevin Wolf317fc442014-04-25 13:27:34 +0200888 /* backing files always opened read-only */
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300889 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
890 flags &= ~BDRV_O_COPY_ON_READ;
Kevin Wolf317fc442014-04-25 13:27:34 +0200891
892 /* snapshot=on is handled on the top layer */
Kevin Wolf8bfea152014-04-11 19:16:36 +0200893 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
Kevin Wolf317fc442014-04-25 13:27:34 +0200894
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200895 *child_flags = flags;
Kevin Wolf317fc442014-04-25 13:27:34 +0200896}
897
Kevin Wolf91ef3822016-12-20 16:23:46 +0100898const BdrvChildRole child_backing = {
Kevin Wolfb5411552017-01-17 15:56:16 +0100899 .get_parent_desc = bdrv_child_get_parent_desc,
Kevin Wolfdb95dbb2017-02-08 11:28:52 +0100900 .attach = bdrv_backing_attach,
901 .detach = bdrv_backing_detach,
Kevin Wolf8e2160e2015-04-29 17:29:39 +0200902 .inherit_options = bdrv_backing_options,
Kevin Wolf20018e12016-05-23 18:46:59 +0200903 .drained_begin = bdrv_child_cb_drained_begin,
904 .drained_end = bdrv_child_cb_drained_end,
Kevin Wolff3930ed2015-04-08 13:43:47 +0200905};
906
Kevin Wolf7b272452012-11-12 17:05:39 +0100907static int bdrv_open_flags(BlockDriverState *bs, int flags)
908{
Kevin Wolf61de4c62016-03-18 17:46:45 +0100909 int open_flags = flags;
Kevin Wolf7b272452012-11-12 17:05:39 +0100910
911 /*
912 * Clear flags that are internal to the block layer before opening the
913 * image.
914 */
Kevin Wolf20cca272014-06-04 14:33:27 +0200915 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
Kevin Wolf7b272452012-11-12 17:05:39 +0100916
917 /*
918 * Snapshots should be writable.
919 */
Kevin Wolf8bfea152014-04-11 19:16:36 +0200920 if (flags & BDRV_O_TEMPORARY) {
Kevin Wolf7b272452012-11-12 17:05:39 +0100921 open_flags |= BDRV_O_RDWR;
922 }
923
924 return open_flags;
925}
926
Kevin Wolf91a097e2015-05-08 17:49:53 +0200927static void update_flags_from_options(int *flags, QemuOpts *opts)
928{
929 *flags &= ~BDRV_O_CACHE_MASK;
930
Kevin Wolf91a097e2015-05-08 17:49:53 +0200931 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
932 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
933 *flags |= BDRV_O_NO_FLUSH;
934 }
935
936 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
937 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
938 *flags |= BDRV_O_NOCACHE;
939 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300940
941 *flags &= ~BDRV_O_RDWR;
942
943 assert(qemu_opt_find(opts, BDRV_OPT_READ_ONLY));
944 if (!qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false)) {
945 *flags |= BDRV_O_RDWR;
946 }
947
Kevin Wolf91a097e2015-05-08 17:49:53 +0200948}
949
950static void update_options_from_flags(QDict *options, int flags)
951{
Kevin Wolf91a097e2015-05-08 17:49:53 +0200952 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
953 qdict_put(options, BDRV_OPT_CACHE_DIRECT,
954 qbool_from_bool(flags & BDRV_O_NOCACHE));
955 }
956 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
957 qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
958 qbool_from_bool(flags & BDRV_O_NO_FLUSH));
959 }
Alberto Garciaf87a0e22016-09-15 17:53:02 +0300960 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
961 qdict_put(options, BDRV_OPT_READ_ONLY,
962 qbool_from_bool(!(flags & BDRV_O_RDWR)));
963 }
Kevin Wolf91a097e2015-05-08 17:49:53 +0200964}
965
Kevin Wolf636ea372014-01-24 14:11:52 +0100966static void bdrv_assign_node_name(BlockDriverState *bs,
967 const char *node_name,
968 Error **errp)
Benoît Canet6913c0c2014-01-23 21:31:33 +0100969{
Jeff Cody15489c72015-10-12 19:36:50 -0400970 char *gen_node_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +0100971
Jeff Cody15489c72015-10-12 19:36:50 -0400972 if (!node_name) {
973 node_name = gen_node_name = id_generate(ID_BLOCK);
974 } else if (!id_wellformed(node_name)) {
975 /*
976 * Check for empty string or invalid characters, but not if it is
977 * generated (generated names use characters not available to the user)
978 */
Kevin Wolf9aebf3b2014-09-25 09:54:02 +0200979 error_setg(errp, "Invalid node name");
Kevin Wolf636ea372014-01-24 14:11:52 +0100980 return;
Benoît Canet6913c0c2014-01-23 21:31:33 +0100981 }
982
Benoît Canet0c5e94e2014-02-12 17:15:07 +0100983 /* takes care of avoiding namespaces collisions */
Markus Armbruster7f06d472014-10-07 13:59:12 +0200984 if (blk_by_name(node_name)) {
Benoît Canet0c5e94e2014-02-12 17:15:07 +0100985 error_setg(errp, "node-name=%s is conflicting with a device id",
986 node_name);
Jeff Cody15489c72015-10-12 19:36:50 -0400987 goto out;
Benoît Canet0c5e94e2014-02-12 17:15:07 +0100988 }
989
Benoît Canet6913c0c2014-01-23 21:31:33 +0100990 /* takes care of avoiding duplicates node names */
991 if (bdrv_find_node(node_name)) {
992 error_setg(errp, "Duplicate node name");
Jeff Cody15489c72015-10-12 19:36:50 -0400993 goto out;
Benoît Canet6913c0c2014-01-23 21:31:33 +0100994 }
995
996 /* copy node name into the bs and insert it into the graph list */
997 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
998 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
Jeff Cody15489c72015-10-12 19:36:50 -0400999out:
1000 g_free(gen_node_name);
Benoît Canet6913c0c2014-01-23 21:31:33 +01001001}
1002
Kevin Wolf01a56502017-01-18 15:51:56 +01001003static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1004 const char *node_name, QDict *options,
1005 int open_flags, Error **errp)
1006{
1007 Error *local_err = NULL;
1008 int ret;
1009
1010 bdrv_assign_node_name(bs, node_name, &local_err);
1011 if (local_err) {
1012 error_propagate(errp, local_err);
1013 return -EINVAL;
1014 }
1015
1016 bs->drv = drv;
Kevin Wolf680c7f92017-01-18 17:16:41 +01001017 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Kevin Wolf01a56502017-01-18 15:51:56 +01001018 bs->opaque = g_malloc0(drv->instance_size);
1019
1020 if (drv->bdrv_file_open) {
1021 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1022 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001023 } else if (drv->bdrv_open) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001024 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
Kevin Wolf680c7f92017-01-18 17:16:41 +01001025 } else {
1026 ret = 0;
Kevin Wolf01a56502017-01-18 15:51:56 +01001027 }
1028
1029 if (ret < 0) {
1030 if (local_err) {
1031 error_propagate(errp, local_err);
1032 } else if (bs->filename[0]) {
1033 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1034 } else {
1035 error_setg_errno(errp, -ret, "Could not open image");
1036 }
1037 goto free_and_fail;
1038 }
1039
1040 ret = refresh_total_sectors(bs, bs->total_sectors);
1041 if (ret < 0) {
1042 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1043 goto free_and_fail;
1044 }
1045
1046 bdrv_refresh_limits(bs, &local_err);
1047 if (local_err) {
1048 error_propagate(errp, local_err);
1049 ret = -EINVAL;
1050 goto free_and_fail;
1051 }
1052
1053 assert(bdrv_opt_mem_align(bs) != 0);
1054 assert(bdrv_min_mem_align(bs) != 0);
1055 assert(is_power_of_2(bs->bl.request_alignment));
1056
1057 return 0;
1058
1059free_and_fail:
1060 /* FIXME Close bs first if already opened*/
1061 g_free(bs->opaque);
1062 bs->opaque = NULL;
1063 bs->drv = NULL;
1064 return ret;
1065}
1066
Kevin Wolf680c7f92017-01-18 17:16:41 +01001067BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1068 int flags, Error **errp)
1069{
1070 BlockDriverState *bs;
1071 int ret;
1072
1073 bs = bdrv_new();
1074 bs->open_flags = flags;
1075 bs->explicit_options = qdict_new();
1076 bs->options = qdict_new();
1077 bs->opaque = NULL;
1078
1079 update_options_from_flags(bs->options, flags);
1080
1081 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1082 if (ret < 0) {
1083 QDECREF(bs->explicit_options);
1084 QDECREF(bs->options);
1085 bdrv_unref(bs);
1086 return NULL;
1087 }
1088
1089 return bs;
1090}
1091
Kevin Wolfc5f30142016-10-06 11:33:17 +02001092QemuOptsList bdrv_runtime_opts = {
Kevin Wolf18edf282015-04-07 17:12:56 +02001093 .name = "bdrv_common",
1094 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1095 .desc = {
1096 {
1097 .name = "node-name",
1098 .type = QEMU_OPT_STRING,
1099 .help = "Node name of the block device node",
1100 },
Kevin Wolf62392eb2015-04-24 16:38:02 +02001101 {
1102 .name = "driver",
1103 .type = QEMU_OPT_STRING,
1104 .help = "Block driver to use for the node",
1105 },
Kevin Wolf91a097e2015-05-08 17:49:53 +02001106 {
Kevin Wolf91a097e2015-05-08 17:49:53 +02001107 .name = BDRV_OPT_CACHE_DIRECT,
1108 .type = QEMU_OPT_BOOL,
1109 .help = "Bypass software writeback cache on the host",
1110 },
1111 {
1112 .name = BDRV_OPT_CACHE_NO_FLUSH,
1113 .type = QEMU_OPT_BOOL,
1114 .help = "Ignore flush requests",
1115 },
Alberto Garciaf87a0e22016-09-15 17:53:02 +03001116 {
1117 .name = BDRV_OPT_READ_ONLY,
1118 .type = QEMU_OPT_BOOL,
1119 .help = "Node is opened in read-only mode",
1120 },
Kevin Wolf692e01a2016-09-12 21:00:41 +02001121 {
1122 .name = "detect-zeroes",
1123 .type = QEMU_OPT_STRING,
1124 .help = "try to optimize zero writes (off, on, unmap)",
1125 },
Kevin Wolf818584a2016-09-12 18:03:18 +02001126 {
1127 .name = "discard",
1128 .type = QEMU_OPT_STRING,
1129 .help = "discard operation (ignore/off, unmap/on)",
1130 },
Kevin Wolf18edf282015-04-07 17:12:56 +02001131 { /* end of list */ }
1132 },
1133};
1134
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02001135/*
Kevin Wolf57915332010-04-14 15:24:50 +02001136 * Common part for opening disk images and files
Kevin Wolfb6ad4912013-03-15 10:35:04 +01001137 *
1138 * Removes all processed options from *options.
Kevin Wolf57915332010-04-14 15:24:50 +02001139 */
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001140static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001141 QDict *options, Error **errp)
Kevin Wolf57915332010-04-14 15:24:50 +02001142{
1143 int ret, open_flags;
Kevin Wolf035fccd2013-04-09 14:34:19 +02001144 const char *filename;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001145 const char *driver_name = NULL;
Benoît Canet6913c0c2014-01-23 21:31:33 +01001146 const char *node_name = NULL;
Kevin Wolf818584a2016-09-12 18:03:18 +02001147 const char *discard;
Kevin Wolf692e01a2016-09-12 21:00:41 +02001148 const char *detect_zeroes;
Kevin Wolf18edf282015-04-07 17:12:56 +02001149 QemuOpts *opts;
Kevin Wolf62392eb2015-04-24 16:38:02 +02001150 BlockDriver *drv;
Max Reitz34b5d2c2013-09-05 14:45:29 +02001151 Error *local_err = NULL;
Kevin Wolf57915332010-04-14 15:24:50 +02001152
Paolo Bonzini64058752012-05-08 16:51:49 +02001153 assert(bs->file == NULL);
Kevin Wolf707ff822013-03-06 12:20:31 +01001154 assert(options != NULL && bs->options != options);
Kevin Wolf57915332010-04-14 15:24:50 +02001155
Kevin Wolf62392eb2015-04-24 16:38:02 +02001156 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1157 qemu_opts_absorb_qdict(opts, options, &local_err);
1158 if (local_err) {
1159 error_propagate(errp, local_err);
1160 ret = -EINVAL;
1161 goto fail_opts;
1162 }
1163
Alberto Garcia9b7e8692016-09-15 17:53:01 +03001164 update_flags_from_options(&bs->open_flags, opts);
1165
Kevin Wolf62392eb2015-04-24 16:38:02 +02001166 driver_name = qemu_opt_get(opts, "driver");
1167 drv = bdrv_find_format(driver_name);
1168 assert(drv != NULL);
1169
Kevin Wolf45673672013-04-22 17:48:40 +02001170 if (file != NULL) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01001171 filename = blk_bs(file)->filename;
Kevin Wolf45673672013-04-22 17:48:40 +02001172 } else {
Markus Armbruster129c7d12017-03-30 19:43:12 +02001173 /*
1174 * Caution: while qdict_get_try_str() is fine, getting
1175 * non-string types would require more care. When @options
1176 * come from -blockdev or blockdev_add, its members are typed
1177 * according to the QAPI schema, but when they come from
1178 * -drive, they're all QString.
1179 */
Kevin Wolf45673672013-04-22 17:48:40 +02001180 filename = qdict_get_try_str(options, "filename");
1181 }
1182
Kevin Wolf765003d2014-02-03 14:49:42 +01001183 if (drv->bdrv_needs_filename && !filename) {
1184 error_setg(errp, "The '%s' block driver requires a file name",
1185 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001186 ret = -EINVAL;
1187 goto fail_opts;
1188 }
1189
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001190 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1191 drv->format_name);
Kevin Wolf62392eb2015-04-24 16:38:02 +02001192
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001193 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001194
1195 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
Kevin Wolf8f94a6e2013-10-10 11:45:55 +02001196 error_setg(errp,
1197 !bs->read_only && bdrv_is_whitelisted(drv, true)
1198 ? "Driver '%s' can only be used for read-only devices"
1199 : "Driver '%s' is not whitelisted",
1200 drv->format_name);
Kevin Wolf18edf282015-04-07 17:12:56 +02001201 ret = -ENOTSUP;
1202 goto fail_opts;
Fam Zhengb64ec4e2013-05-29 19:35:40 +08001203 }
Kevin Wolf57915332010-04-14 15:24:50 +02001204
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001205 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001206 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001207 if (!bs->read_only) {
1208 bdrv_enable_copy_on_read(bs);
1209 } else {
1210 error_setg(errp, "Can't use copy-on-read on read-only device");
Kevin Wolf18edf282015-04-07 17:12:56 +02001211 ret = -EINVAL;
1212 goto fail_opts;
Kevin Wolf0ebd24e2013-09-19 15:12:18 +02001213 }
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001214 }
1215
Kevin Wolf818584a2016-09-12 18:03:18 +02001216 discard = qemu_opt_get(opts, "discard");
1217 if (discard != NULL) {
1218 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1219 error_setg(errp, "Invalid discard option");
1220 ret = -EINVAL;
1221 goto fail_opts;
1222 }
1223 }
1224
Kevin Wolf692e01a2016-09-12 21:00:41 +02001225 detect_zeroes = qemu_opt_get(opts, "detect-zeroes");
1226 if (detect_zeroes) {
1227 BlockdevDetectZeroesOptions value =
1228 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
1229 detect_zeroes,
1230 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
1231 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
1232 &local_err);
1233 if (local_err) {
1234 error_propagate(errp, local_err);
1235 ret = -EINVAL;
1236 goto fail_opts;
1237 }
1238
1239 if (value == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1240 !(bs->open_flags & BDRV_O_UNMAP))
1241 {
1242 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1243 "without setting discard operation to unmap");
1244 ret = -EINVAL;
1245 goto fail_opts;
1246 }
1247
1248 bs->detect_zeroes = value;
1249 }
1250
Kevin Wolfc2ad1b02013-03-18 16:40:51 +01001251 if (filename != NULL) {
1252 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1253 } else {
1254 bs->filename[0] = '\0';
1255 }
Max Reitz91af7012014-07-18 20:24:56 +02001256 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
Kevin Wolf57915332010-04-14 15:24:50 +02001257
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001258 /* Open the image, either directly or using a protocol */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01001259 open_flags = bdrv_open_flags(bs, bs->open_flags);
Kevin Wolf01a56502017-01-18 15:51:56 +01001260 node_name = qemu_opt_get(opts, "node-name");
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001261
Kevin Wolf01a56502017-01-18 15:51:56 +01001262 assert(!drv->bdrv_file_open || file == NULL);
1263 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
Kevin Wolf57915332010-04-14 15:24:50 +02001264 if (ret < 0) {
Kevin Wolf01a56502017-01-18 15:51:56 +01001265 goto fail_opts;
Kevin Wolf57915332010-04-14 15:24:50 +02001266 }
1267
Kevin Wolf18edf282015-04-07 17:12:56 +02001268 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001269 return 0;
1270
Kevin Wolf18edf282015-04-07 17:12:56 +02001271fail_opts:
1272 qemu_opts_del(opts);
Kevin Wolf57915332010-04-14 15:24:50 +02001273 return ret;
1274}
1275
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001276static QDict *parse_json_filename(const char *filename, Error **errp)
1277{
1278 QObject *options_obj;
1279 QDict *options;
1280 int ret;
1281
1282 ret = strstart(filename, "json:", &filename);
1283 assert(ret);
1284
Markus Armbruster5577fff2017-02-28 22:26:59 +01001285 options_obj = qobject_from_json(filename, errp);
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001286 if (!options_obj) {
Markus Armbruster5577fff2017-02-28 22:26:59 +01001287 /* Work around qobject_from_json() lossage TODO fix that */
1288 if (errp && !*errp) {
1289 error_setg(errp, "Could not parse the JSON options");
1290 return NULL;
1291 }
1292 error_prepend(errp, "Could not parse the JSON options: ");
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001293 return NULL;
1294 }
1295
Markus Armbrusterca6b6e12017-02-17 21:38:18 +01001296 options = qobject_to_qdict(options_obj);
1297 if (!options) {
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001298 qobject_decref(options_obj);
1299 error_setg(errp, "Invalid JSON object given");
1300 return NULL;
1301 }
1302
Kevin Wolf5e5c4f62014-05-26 11:45:08 +02001303 qdict_flatten(options);
1304
1305 return options;
1306}
1307
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001308static void parse_json_protocol(QDict *options, const char **pfilename,
1309 Error **errp)
1310{
1311 QDict *json_options;
1312 Error *local_err = NULL;
1313
1314 /* Parse json: pseudo-protocol */
1315 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1316 return;
1317 }
1318
1319 json_options = parse_json_filename(*pfilename, &local_err);
1320 if (local_err) {
1321 error_propagate(errp, local_err);
1322 return;
1323 }
1324
1325 /* Options given in the filename have lower priority than options
1326 * specified directly */
1327 qdict_join(options, json_options, false);
1328 QDECREF(json_options);
1329 *pfilename = NULL;
1330}
1331
Kevin Wolf57915332010-04-14 15:24:50 +02001332/*
Kevin Wolff54120f2014-05-26 11:09:59 +02001333 * Fills in default options for opening images and converts the legacy
1334 * filename/flags pair to option QDict entries.
Max Reitz53a29512015-03-19 14:53:16 -04001335 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1336 * block driver has been specified explicitly.
Kevin Wolff54120f2014-05-26 11:09:59 +02001337 */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01001338static int bdrv_fill_options(QDict **options, const char *filename,
Max Reitz053e1572015-08-26 19:47:51 +02001339 int *flags, Error **errp)
Kevin Wolff54120f2014-05-26 11:09:59 +02001340{
1341 const char *drvname;
Max Reitz53a29512015-03-19 14:53:16 -04001342 bool protocol = *flags & BDRV_O_PROTOCOL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001343 bool parse_filename = false;
Max Reitz053e1572015-08-26 19:47:51 +02001344 BlockDriver *drv = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001345 Error *local_err = NULL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001346
Markus Armbruster129c7d12017-03-30 19:43:12 +02001347 /*
1348 * Caution: while qdict_get_try_str() is fine, getting non-string
1349 * types would require more care. When @options come from
1350 * -blockdev or blockdev_add, its members are typed according to
1351 * the QAPI schema, but when they come from -drive, they're all
1352 * QString.
1353 */
Max Reitz53a29512015-03-19 14:53:16 -04001354 drvname = qdict_get_try_str(*options, "driver");
Max Reitz053e1572015-08-26 19:47:51 +02001355 if (drvname) {
1356 drv = bdrv_find_format(drvname);
1357 if (!drv) {
1358 error_setg(errp, "Unknown driver '%s'", drvname);
1359 return -ENOENT;
1360 }
1361 /* If the user has explicitly specified the driver, this choice should
1362 * override the BDRV_O_PROTOCOL flag */
1363 protocol = drv->bdrv_file_open;
Max Reitz53a29512015-03-19 14:53:16 -04001364 }
1365
1366 if (protocol) {
1367 *flags |= BDRV_O_PROTOCOL;
1368 } else {
1369 *flags &= ~BDRV_O_PROTOCOL;
1370 }
1371
Kevin Wolf91a097e2015-05-08 17:49:53 +02001372 /* Translate cache options from flags into options */
1373 update_options_from_flags(*options, *flags);
1374
Kevin Wolff54120f2014-05-26 11:09:59 +02001375 /* Fetch the file name from the options QDict if necessary */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001376 if (protocol && filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001377 if (!qdict_haskey(*options, "filename")) {
1378 qdict_put(*options, "filename", qstring_from_str(filename));
1379 parse_filename = true;
1380 } else {
1381 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1382 "the same time");
1383 return -EINVAL;
1384 }
1385 }
1386
1387 /* Find the right block driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02001388 /* See cautionary note on accessing @options above */
Kevin Wolff54120f2014-05-26 11:09:59 +02001389 filename = qdict_get_try_str(*options, "filename");
Kevin Wolff54120f2014-05-26 11:09:59 +02001390
Max Reitz053e1572015-08-26 19:47:51 +02001391 if (!drvname && protocol) {
1392 if (filename) {
1393 drv = bdrv_find_protocol(filename, parse_filename, errp);
1394 if (!drv) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001395 return -EINVAL;
1396 }
Max Reitz053e1572015-08-26 19:47:51 +02001397
1398 drvname = drv->format_name;
1399 qdict_put(*options, "driver", qstring_from_str(drvname));
1400 } else {
1401 error_setg(errp, "Must specify either driver or file");
1402 return -EINVAL;
Kevin Wolff54120f2014-05-26 11:09:59 +02001403 }
1404 }
1405
Kevin Wolf17b005f2014-05-27 10:50:29 +02001406 assert(drv || !protocol);
Kevin Wolff54120f2014-05-26 11:09:59 +02001407
1408 /* Driver-specific filename parsing */
Kevin Wolf17b005f2014-05-27 10:50:29 +02001409 if (drv && drv->bdrv_parse_filename && parse_filename) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001410 drv->bdrv_parse_filename(filename, *options, &local_err);
1411 if (local_err) {
1412 error_propagate(errp, local_err);
1413 return -EINVAL;
1414 }
1415
1416 if (!drv->bdrv_needs_filename) {
1417 qdict_del(*options, "filename");
1418 }
1419 }
1420
1421 return 0;
1422}
1423
Fam Zhengc1cef672017-03-14 10:30:50 +08001424static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1425 GSList *ignore_children, Error **errp);
1426static void bdrv_child_abort_perm_update(BdrvChild *c);
1427static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1428
Kevin Wolf33a610c2016-12-15 13:04:20 +01001429/*
1430 * Check whether permissions on this node can be changed in a way that
1431 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1432 * permissions of all its parents. This involves checking whether all necessary
1433 * permission changes to child nodes can be performed.
1434 *
1435 * A call to this function must always be followed by a call to bdrv_set_perm()
1436 * or bdrv_abort_perm_update().
1437 */
1438static int bdrv_check_perm(BlockDriverState *bs, uint64_t cumulative_perms,
Kevin Wolf46181122017-03-06 15:00:13 +01001439 uint64_t cumulative_shared_perms,
1440 GSList *ignore_children, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001441{
1442 BlockDriver *drv = bs->drv;
1443 BdrvChild *c;
1444 int ret;
1445
1446 /* Write permissions never work with read-only images */
1447 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
1448 bdrv_is_read_only(bs))
1449 {
1450 error_setg(errp, "Block node is read-only");
1451 return -EPERM;
1452 }
1453
1454 /* Check this node */
1455 if (!drv) {
1456 return 0;
1457 }
1458
1459 if (drv->bdrv_check_perm) {
1460 return drv->bdrv_check_perm(bs, cumulative_perms,
1461 cumulative_shared_perms, errp);
1462 }
1463
Kevin Wolf78e421c2016-12-20 23:25:12 +01001464 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01001465 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01001466 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01001467 return 0;
1468 }
1469
1470 /* Check all children */
1471 QLIST_FOREACH(c, &bs->children, next) {
1472 uint64_t cur_perm, cur_shared;
1473 drv->bdrv_child_perm(bs, c, c->role,
1474 cumulative_perms, cumulative_shared_perms,
1475 &cur_perm, &cur_shared);
Kevin Wolf46181122017-03-06 15:00:13 +01001476 ret = bdrv_child_check_perm(c, cur_perm, cur_shared, ignore_children,
1477 errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01001478 if (ret < 0) {
1479 return ret;
1480 }
1481 }
1482
1483 return 0;
1484}
1485
1486/*
1487 * Notifies drivers that after a previous bdrv_check_perm() call, the
1488 * permission update is not performed and any preparations made for it (e.g.
1489 * taken file locks) need to be undone.
1490 *
1491 * This function recursively notifies all child nodes.
1492 */
1493static void bdrv_abort_perm_update(BlockDriverState *bs)
1494{
1495 BlockDriver *drv = bs->drv;
1496 BdrvChild *c;
1497
1498 if (!drv) {
1499 return;
1500 }
1501
1502 if (drv->bdrv_abort_perm_update) {
1503 drv->bdrv_abort_perm_update(bs);
1504 }
1505
1506 QLIST_FOREACH(c, &bs->children, next) {
1507 bdrv_child_abort_perm_update(c);
1508 }
1509}
1510
1511static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1512 uint64_t cumulative_shared_perms)
1513{
1514 BlockDriver *drv = bs->drv;
1515 BdrvChild *c;
1516
1517 if (!drv) {
1518 return;
1519 }
1520
1521 /* Update this node */
1522 if (drv->bdrv_set_perm) {
1523 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1524 }
1525
Kevin Wolf78e421c2016-12-20 23:25:12 +01001526 /* Drivers that never have children can omit .bdrv_child_perm() */
Kevin Wolf33a610c2016-12-15 13:04:20 +01001527 if (!drv->bdrv_child_perm) {
Kevin Wolf78e421c2016-12-20 23:25:12 +01001528 assert(QLIST_EMPTY(&bs->children));
Kevin Wolf33a610c2016-12-15 13:04:20 +01001529 return;
1530 }
1531
1532 /* Update all children */
1533 QLIST_FOREACH(c, &bs->children, next) {
1534 uint64_t cur_perm, cur_shared;
1535 drv->bdrv_child_perm(bs, c, c->role,
1536 cumulative_perms, cumulative_shared_perms,
1537 &cur_perm, &cur_shared);
1538 bdrv_child_set_perm(c, cur_perm, cur_shared);
1539 }
1540}
1541
1542static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1543 uint64_t *shared_perm)
1544{
1545 BdrvChild *c;
1546 uint64_t cumulative_perms = 0;
1547 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1548
1549 QLIST_FOREACH(c, &bs->parents, next_parent) {
1550 cumulative_perms |= c->perm;
1551 cumulative_shared_perms &= c->shared_perm;
1552 }
1553
1554 *perm = cumulative_perms;
1555 *shared_perm = cumulative_shared_perms;
1556}
1557
Kevin Wolfd0833192017-01-16 18:26:20 +01001558static char *bdrv_child_user_desc(BdrvChild *c)
1559{
1560 if (c->role->get_parent_desc) {
1561 return c->role->get_parent_desc(c);
1562 }
1563
1564 return g_strdup("another user");
1565}
1566
1567static char *bdrv_perm_names(uint64_t perm)
1568{
1569 struct perm_name {
1570 uint64_t perm;
1571 const char *name;
1572 } permissions[] = {
1573 { BLK_PERM_CONSISTENT_READ, "consistent read" },
1574 { BLK_PERM_WRITE, "write" },
1575 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1576 { BLK_PERM_RESIZE, "resize" },
1577 { BLK_PERM_GRAPH_MOD, "change children" },
1578 { 0, NULL }
1579 };
1580
1581 char *result = g_strdup("");
1582 struct perm_name *p;
1583
1584 for (p = permissions; p->name; p++) {
1585 if (perm & p->perm) {
1586 char *old = result;
1587 result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
1588 g_free(old);
1589 }
1590 }
1591
1592 return result;
1593}
1594
Kevin Wolf33a610c2016-12-15 13:04:20 +01001595/*
1596 * Checks whether a new reference to @bs can be added if the new user requires
Kevin Wolf46181122017-03-06 15:00:13 +01001597 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
1598 * set, the BdrvChild objects in this list are ignored in the calculations;
1599 * this allows checking permission updates for an existing reference.
Kevin Wolf33a610c2016-12-15 13:04:20 +01001600 *
1601 * Needs to be followed by a call to either bdrv_set_perm() or
1602 * bdrv_abort_perm_update(). */
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001603static int bdrv_check_update_perm(BlockDriverState *bs, uint64_t new_used_perm,
1604 uint64_t new_shared_perm,
Kevin Wolf46181122017-03-06 15:00:13 +01001605 GSList *ignore_children, Error **errp)
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001606{
1607 BdrvChild *c;
Kevin Wolf33a610c2016-12-15 13:04:20 +01001608 uint64_t cumulative_perms = new_used_perm;
1609 uint64_t cumulative_shared_perms = new_shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001610
1611 /* There is no reason why anyone couldn't tolerate write_unchanged */
1612 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
1613
1614 QLIST_FOREACH(c, &bs->parents, next_parent) {
Kevin Wolf46181122017-03-06 15:00:13 +01001615 if (g_slist_find(ignore_children, c)) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001616 continue;
1617 }
1618
Kevin Wolfd0833192017-01-16 18:26:20 +01001619 if ((new_used_perm & c->shared_perm) != new_used_perm) {
1620 char *user = bdrv_child_user_desc(c);
1621 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
1622 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
1623 "allow '%s' on %s",
1624 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1625 g_free(user);
1626 g_free(perm_names);
1627 return -EPERM;
1628 }
1629
1630 if ((c->perm & new_shared_perm) != c->perm) {
1631 char *user = bdrv_child_user_desc(c);
1632 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
1633 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
1634 "'%s' on %s",
1635 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1636 g_free(user);
1637 g_free(perm_names);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001638 return -EPERM;
1639 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01001640
1641 cumulative_perms |= c->perm;
1642 cumulative_shared_perms &= c->shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001643 }
1644
Kevin Wolf46181122017-03-06 15:00:13 +01001645 return bdrv_check_perm(bs, cumulative_perms, cumulative_shared_perms,
1646 ignore_children, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01001647}
1648
1649/* Needs to be followed by a call to either bdrv_child_set_perm() or
1650 * bdrv_child_abort_perm_update(). */
Fam Zhengc1cef672017-03-14 10:30:50 +08001651static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1652 GSList *ignore_children, Error **errp)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001653{
Kevin Wolf46181122017-03-06 15:00:13 +01001654 int ret;
1655
1656 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
1657 ret = bdrv_check_update_perm(c->bs, perm, shared, ignore_children, errp);
1658 g_slist_free(ignore_children);
1659
1660 return ret;
Kevin Wolf33a610c2016-12-15 13:04:20 +01001661}
1662
Fam Zhengc1cef672017-03-14 10:30:50 +08001663static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001664{
1665 uint64_t cumulative_perms, cumulative_shared_perms;
1666
1667 c->perm = perm;
1668 c->shared_perm = shared;
1669
1670 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
1671 &cumulative_shared_perms);
1672 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
1673}
1674
Fam Zhengc1cef672017-03-14 10:30:50 +08001675static void bdrv_child_abort_perm_update(BdrvChild *c)
Kevin Wolf33a610c2016-12-15 13:04:20 +01001676{
1677 bdrv_abort_perm_update(c->bs);
1678}
1679
1680int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1681 Error **errp)
1682{
1683 int ret;
1684
Kevin Wolf46181122017-03-06 15:00:13 +01001685 ret = bdrv_child_check_perm(c, perm, shared, NULL, errp);
Kevin Wolf33a610c2016-12-15 13:04:20 +01001686 if (ret < 0) {
1687 bdrv_child_abort_perm_update(c);
1688 return ret;
1689 }
1690
1691 bdrv_child_set_perm(c, perm, shared);
1692
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001693 return 0;
1694}
1695
Kevin Wolf6a1b9ee2016-12-15 11:27:32 +01001696#define DEFAULT_PERM_PASSTHROUGH (BLK_PERM_CONSISTENT_READ \
1697 | BLK_PERM_WRITE \
1698 | BLK_PERM_WRITE_UNCHANGED \
1699 | BLK_PERM_RESIZE)
1700#define DEFAULT_PERM_UNCHANGED (BLK_PERM_ALL & ~DEFAULT_PERM_PASSTHROUGH)
1701
1702void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
1703 const BdrvChildRole *role,
1704 uint64_t perm, uint64_t shared,
1705 uint64_t *nperm, uint64_t *nshared)
1706{
1707 if (c == NULL) {
1708 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
1709 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
1710 return;
1711 }
1712
1713 *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
1714 (c->perm & DEFAULT_PERM_UNCHANGED);
1715 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
1716 (c->shared_perm & DEFAULT_PERM_UNCHANGED);
1717}
1718
Kevin Wolf6b1a0442016-12-19 15:21:48 +01001719void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
1720 const BdrvChildRole *role,
1721 uint64_t perm, uint64_t shared,
1722 uint64_t *nperm, uint64_t *nshared)
1723{
1724 bool backing = (role == &child_backing);
1725 assert(role == &child_backing || role == &child_file);
1726
1727 if (!backing) {
1728 /* Apart from the modifications below, the same permissions are
1729 * forwarded and left alone as for filters */
1730 bdrv_filter_default_perms(bs, c, role, perm, shared, &perm, &shared);
1731
1732 /* Format drivers may touch metadata even if the guest doesn't write */
1733 if (!bdrv_is_read_only(bs)) {
1734 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
1735 }
1736
1737 /* bs->file always needs to be consistent because of the metadata. We
1738 * can never allow other users to resize or write to it. */
1739 perm |= BLK_PERM_CONSISTENT_READ;
1740 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
1741 } else {
1742 /* We want consistent read from backing files if the parent needs it.
1743 * No other operations are performed on backing files. */
1744 perm &= BLK_PERM_CONSISTENT_READ;
1745
1746 /* If the parent can deal with changing data, we're okay with a
1747 * writable and resizable backing file. */
1748 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
1749 if (shared & BLK_PERM_WRITE) {
1750 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
1751 } else {
1752 shared = 0;
1753 }
1754
1755 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
1756 BLK_PERM_WRITE_UNCHANGED;
1757 }
1758
1759 *nperm = perm;
1760 *nshared = shared;
1761}
1762
Kevin Wolf8ee03992017-03-06 13:45:28 +01001763static void bdrv_replace_child_noperm(BdrvChild *child,
1764 BlockDriverState *new_bs)
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001765{
1766 BlockDriverState *old_bs = child->bs;
1767
Fam Zhengbb2614e2017-04-07 14:54:10 +08001768 if (old_bs && new_bs) {
1769 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
1770 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001771 if (old_bs) {
Kevin Wolf36fe1332016-05-17 14:51:55 +02001772 if (old_bs->quiesce_counter && child->role->drained_end) {
1773 child->role->drained_end(child);
1774 }
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001775 if (child->role->detach) {
1776 child->role->detach(child);
1777 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001778 QLIST_REMOVE(child, next_parent);
1779 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001780
1781 child->bs = new_bs;
Kevin Wolf36fe1332016-05-17 14:51:55 +02001782
1783 if (new_bs) {
1784 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
1785 if (new_bs->quiesce_counter && child->role->drained_begin) {
1786 child->role->drained_begin(child);
1787 }
Kevin Wolf33a610c2016-12-15 13:04:20 +01001788
Kevin Wolfdb95dbb2017-02-08 11:28:52 +01001789 if (child->role->attach) {
1790 child->role->attach(child);
1791 }
Kevin Wolf36fe1332016-05-17 14:51:55 +02001792 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001793}
1794
Kevin Wolf466787f2017-03-08 14:44:07 +01001795/*
1796 * Updates @child to change its reference to point to @new_bs, including
1797 * checking and applying the necessary permisson updates both to the old node
1798 * and to @new_bs.
1799 *
1800 * NULL is passed as @new_bs for removing the reference before freeing @child.
1801 *
1802 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
1803 * function uses bdrv_set_perm() to update the permissions according to the new
1804 * reference that @new_bs gets.
1805 */
1806static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
Kevin Wolf8ee03992017-03-06 13:45:28 +01001807{
1808 BlockDriverState *old_bs = child->bs;
1809 uint64_t perm, shared_perm;
1810
1811 if (old_bs) {
1812 /* Update permissions for old node. This is guaranteed to succeed
1813 * because we're just taking a parent away, so we're loosening
1814 * restrictions. */
1815 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
Kevin Wolf46181122017-03-06 15:00:13 +01001816 bdrv_check_perm(old_bs, perm, shared_perm, NULL, &error_abort);
Kevin Wolf8ee03992017-03-06 13:45:28 +01001817 bdrv_set_perm(old_bs, perm, shared_perm);
1818 }
1819
1820 bdrv_replace_child_noperm(child, new_bs);
1821
1822 if (new_bs) {
Kevin Wolff54120f2014-05-26 11:09:59 +02001823 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
Kevin Wolff54120f2014-05-26 11:09:59 +02001824 bdrv_set_perm(new_bs, perm, shared_perm);
Kevin Wolff54120f2014-05-26 11:09:59 +02001825 }
1826}
1827
Kevin Wolff21d96d2016-03-08 13:47:46 +01001828BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1829 const char *child_name,
Kevin Wolf36fe1332016-05-17 14:51:55 +02001830 const BdrvChildRole *child_role,
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001831 uint64_t perm, uint64_t shared_perm,
1832 void *opaque, Error **errp)
Kevin Wolfdf581792015-06-15 11:53:47 +02001833{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001834 BdrvChild *child;
1835 int ret;
1836
1837 ret = bdrv_check_update_perm(child_bs, perm, shared_perm, NULL, errp);
1838 if (ret < 0) {
Kevin Wolf33a610c2016-12-15 13:04:20 +01001839 bdrv_abort_perm_update(child_bs);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001840 return NULL;
1841 }
1842
1843 child = g_new(BdrvChild, 1);
Kevin Wolfdf581792015-06-15 11:53:47 +02001844 *child = (BdrvChild) {
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001845 .bs = NULL,
1846 .name = g_strdup(child_name),
1847 .role = child_role,
1848 .perm = perm,
1849 .shared_perm = shared_perm,
1850 .opaque = opaque,
Kevin Wolfdf581792015-06-15 11:53:47 +02001851 };
1852
Kevin Wolf33a610c2016-12-15 13:04:20 +01001853 /* This performs the matching bdrv_set_perm() for the above check. */
Kevin Wolf466787f2017-03-08 14:44:07 +01001854 bdrv_replace_child(child, child_bs);
Kevin Wolfb4b059f2015-06-15 13:24:19 +02001855
1856 return child;
Kevin Wolfdf581792015-06-15 11:53:47 +02001857}
1858
Wen Congyang98292c62016-05-10 15:36:38 +08001859BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1860 BlockDriverState *child_bs,
1861 const char *child_name,
Kevin Wolf8b2ff522016-12-20 22:21:17 +01001862 const BdrvChildRole *child_role,
1863 Error **errp)
Kevin Wolff21d96d2016-03-08 13:47:46 +01001864{
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001865 BdrvChild *child;
Kevin Wolff68c5982016-12-20 15:51:12 +01001866 uint64_t perm, shared_perm;
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001867
Kevin Wolff68c5982016-12-20 15:51:12 +01001868 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
1869
1870 assert(parent_bs->drv);
Fam Zhengbb2614e2017-04-07 14:54:10 +08001871 assert(bdrv_get_aio_context(parent_bs) == bdrv_get_aio_context(child_bs));
Kevin Wolff68c5982016-12-20 15:51:12 +01001872 parent_bs->drv->bdrv_child_perm(parent_bs, NULL, child_role,
1873 perm, shared_perm, &perm, &shared_perm);
1874
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001875 child = bdrv_root_attach_child(child_bs, child_name, child_role,
Kevin Wolff68c5982016-12-20 15:51:12 +01001876 perm, shared_perm, parent_bs, errp);
Kevin Wolfd5e6f432016-12-14 17:24:36 +01001877 if (child == NULL) {
1878 return NULL;
1879 }
1880
Kevin Wolff21d96d2016-03-08 13:47:46 +01001881 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1882 return child;
1883}
1884
Kevin Wolf3f09bfb2015-09-15 11:58:23 +02001885static void bdrv_detach_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02001886{
Kevin Wolff21d96d2016-03-08 13:47:46 +01001887 if (child->next.le_prev) {
1888 QLIST_REMOVE(child, next);
1889 child->next.le_prev = NULL;
1890 }
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001891
Kevin Wolf466787f2017-03-08 14:44:07 +01001892 bdrv_replace_child(child, NULL);
Kevin Wolfe9740bc2016-05-23 15:52:26 +02001893
Kevin Wolf260fecf2015-04-27 13:46:22 +02001894 g_free(child->name);
Kevin Wolf33a60402015-06-15 13:51:04 +02001895 g_free(child);
1896}
1897
Kevin Wolff21d96d2016-03-08 13:47:46 +01001898void bdrv_root_unref_child(BdrvChild *child)
Kevin Wolf33a60402015-06-15 13:51:04 +02001899{
Kevin Wolf779020c2015-10-13 14:09:44 +02001900 BlockDriverState *child_bs;
1901
Kevin Wolff21d96d2016-03-08 13:47:46 +01001902 child_bs = child->bs;
1903 bdrv_detach_child(child);
1904 bdrv_unref(child_bs);
1905}
1906
1907void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1908{
Kevin Wolf779020c2015-10-13 14:09:44 +02001909 if (child == NULL) {
1910 return;
1911 }
Kevin Wolf33a60402015-06-15 13:51:04 +02001912
1913 if (child->bs->inherits_from == parent) {
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01001914 BdrvChild *c;
1915
1916 /* Remove inherits_from only when the last reference between parent and
1917 * child->bs goes away. */
1918 QLIST_FOREACH(c, &parent->children, next) {
1919 if (c != child && c->bs == child->bs) {
1920 break;
1921 }
1922 }
1923 if (c == NULL) {
1924 child->bs->inherits_from = NULL;
1925 }
Kevin Wolf33a60402015-06-15 13:51:04 +02001926 }
1927
Kevin Wolff21d96d2016-03-08 13:47:46 +01001928 bdrv_root_unref_child(child);
Kevin Wolf33a60402015-06-15 13:51:04 +02001929}
1930
Kevin Wolf5c8cab42016-02-24 15:13:35 +01001931
1932static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
1933{
1934 BdrvChild *c;
1935 QLIST_FOREACH(c, &bs->parents, next_parent) {
1936 if (c->role->change_media) {
1937 c->role->change_media(c, load);
1938 }
1939 }
1940}
1941
1942static void bdrv_parent_cb_resize(BlockDriverState *bs)
1943{
1944 BdrvChild *c;
1945 QLIST_FOREACH(c, &bs->parents, next_parent) {
1946 if (c->role->resize) {
1947 c->role->resize(c);
1948 }
1949 }
1950}
1951
Kevin Wolf5db15a52015-09-14 15:33:33 +02001952/*
1953 * Sets the backing file link of a BDS. A new reference is created; callers
1954 * which don't need their own reference any more must call bdrv_unref().
1955 */
Kevin Wolf12fa4af2017-02-17 20:42:32 +01001956void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
1957 Error **errp)
Fam Zheng8d24cce2014-05-23 21:29:45 +08001958{
Kevin Wolf5db15a52015-09-14 15:33:33 +02001959 if (backing_hd) {
1960 bdrv_ref(backing_hd);
1961 }
Fam Zheng8d24cce2014-05-23 21:29:45 +08001962
Kevin Wolf760e0062015-06-17 14:55:21 +02001963 if (bs->backing) {
Kevin Wolf5db15a52015-09-14 15:33:33 +02001964 bdrv_unref_child(bs, bs->backing);
Fam Zheng826b6ca2014-05-23 21:29:47 +08001965 }
1966
Fam Zheng8d24cce2014-05-23 21:29:45 +08001967 if (!backing_hd) {
Kevin Wolf760e0062015-06-17 14:55:21 +02001968 bs->backing = NULL;
Fam Zheng8d24cce2014-05-23 21:29:45 +08001969 goto out;
1970 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01001971
Kevin Wolf8b2ff522016-12-20 22:21:17 +01001972 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
Kevin Wolf12fa4af2017-02-17 20:42:32 +01001973 errp);
1974 if (!bs->backing) {
1975 bdrv_unref(backing_hd);
1976 }
Fam Zheng826b6ca2014-05-23 21:29:47 +08001977
Kevin Wolf9e7e9402017-03-09 11:45:39 +01001978 bdrv_refresh_filename(bs);
1979
Fam Zheng8d24cce2014-05-23 21:29:45 +08001980out:
Kevin Wolf3baca892014-07-16 17:48:16 +02001981 bdrv_refresh_limits(bs, NULL);
Fam Zheng8d24cce2014-05-23 21:29:45 +08001982}
1983
Kevin Wolf31ca6d02013-03-28 15:29:24 +01001984/*
1985 * Opens the backing file for a BlockDriverState if not yet open
1986 *
Kevin Wolfd9b7b052015-01-16 18:23:41 +01001987 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1988 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1989 * itself, all options starting with "${bdref_key}." are considered part of the
1990 * BlockdevRef.
1991 *
1992 * TODO Can this be unified with bdrv_open_image()?
Kevin Wolf31ca6d02013-03-28 15:29:24 +01001993 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01001994int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1995 const char *bdref_key, Error **errp)
Paolo Bonzini9156df12012-10-18 16:49:17 +02001996{
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02001997 char *backing_filename = g_malloc0(PATH_MAX);
Kevin Wolfd9b7b052015-01-16 18:23:41 +01001998 char *bdref_key_dot;
1999 const char *reference = NULL;
Kevin Wolf317fc442014-04-25 13:27:34 +02002000 int ret = 0;
Fam Zheng8d24cce2014-05-23 21:29:45 +08002001 BlockDriverState *backing_hd;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002002 QDict *options;
2003 QDict *tmp_parent_options = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002004 Error *local_err = NULL;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002005
Kevin Wolf760e0062015-06-17 14:55:21 +02002006 if (bs->backing != NULL) {
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002007 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002008 }
2009
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002010 /* NULL means an empty set of options */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002011 if (parent_options == NULL) {
2012 tmp_parent_options = qdict_new();
2013 parent_options = tmp_parent_options;
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002014 }
2015
Paolo Bonzini9156df12012-10-18 16:49:17 +02002016 bs->open_flags &= ~BDRV_O_NO_BACKING;
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002017
2018 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2019 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2020 g_free(bdref_key_dot);
2021
Markus Armbruster129c7d12017-03-30 19:43:12 +02002022 /*
2023 * Caution: while qdict_get_try_str() is fine, getting non-string
2024 * types would require more care. When @parent_options come from
2025 * -blockdev or blockdev_add, its members are typed according to
2026 * the QAPI schema, but when they come from -drive, they're all
2027 * QString.
2028 */
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002029 reference = qdict_get_try_str(parent_options, bdref_key);
2030 if (reference || qdict_haskey(options, "file.filename")) {
Kevin Wolf1cb6f502013-04-12 20:27:07 +02002031 backing_filename[0] = '\0';
2032 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
Kevin Wolf31ca6d02013-03-28 15:29:24 +01002033 QDECREF(options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002034 goto free_exit;
Fam Zhengdbecebd2013-09-22 20:05:06 +08002035 } else {
Max Reitz9f074292014-11-26 17:20:26 +01002036 bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
2037 &local_err);
2038 if (local_err) {
2039 ret = -EINVAL;
2040 error_propagate(errp, local_err);
2041 QDECREF(options);
2042 goto free_exit;
2043 }
Paolo Bonzini9156df12012-10-18 16:49:17 +02002044 }
2045
Kevin Wolf8ee79e72014-06-04 15:09:35 +02002046 if (!bs->drv || !bs->drv->supports_backing) {
2047 ret = -EINVAL;
2048 error_setg(errp, "Driver doesn't support backing files");
2049 QDECREF(options);
2050 goto free_exit;
2051 }
2052
Kevin Wolfc5f6e492014-11-25 18:12:42 +01002053 if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
2054 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
Paolo Bonzini9156df12012-10-18 16:49:17 +02002055 }
2056
Max Reitz5b363932016-05-17 16:41:31 +02002057 backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
2058 reference, options, 0, bs, &child_backing,
2059 errp);
2060 if (!backing_hd) {
Paolo Bonzini9156df12012-10-18 16:49:17 +02002061 bs->open_flags |= BDRV_O_NO_BACKING;
Markus Armbrustere43bfd92015-12-18 16:35:15 +01002062 error_prepend(errp, "Could not open backing file: ");
Max Reitz5b363932016-05-17 16:41:31 +02002063 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002064 goto free_exit;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002065 }
Kevin Wolfdf581792015-06-15 11:53:47 +02002066
Kevin Wolf5db15a52015-09-14 15:33:33 +02002067 /* Hook up the backing file link; drop our reference, bs owns the
2068 * backing_hd reference now */
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002069 bdrv_set_backing_hd(bs, backing_hd, &local_err);
Kevin Wolf5db15a52015-09-14 15:33:33 +02002070 bdrv_unref(backing_hd);
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002071 if (local_err) {
Fam Zheng8cd1a3e2017-03-17 09:56:30 +08002072 error_propagate(errp, local_err);
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002073 ret = -EINVAL;
2074 goto free_exit;
2075 }
Peter Feinerd80ac652014-01-08 19:43:25 +00002076
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002077 qdict_del(parent_options, bdref_key);
2078
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002079free_exit:
2080 g_free(backing_filename);
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002081 QDECREF(tmp_parent_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002082 return ret;
Paolo Bonzini9156df12012-10-18 16:49:17 +02002083}
2084
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002085static BlockDriverState *
2086bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2087 BlockDriverState *parent, const BdrvChildRole *child_role,
2088 bool allow_none, Error **errp)
Max Reitzda557aa2013-12-20 19:28:11 +01002089{
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002090 BlockDriverState *bs = NULL;
Max Reitzda557aa2013-12-20 19:28:11 +01002091 QDict *image_options;
Max Reitzda557aa2013-12-20 19:28:11 +01002092 char *bdref_key_dot;
2093 const char *reference;
2094
Kevin Wolfdf581792015-06-15 11:53:47 +02002095 assert(child_role != NULL);
Max Reitzf67503e2014-02-18 18:33:05 +01002096
Max Reitzda557aa2013-12-20 19:28:11 +01002097 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2098 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2099 g_free(bdref_key_dot);
2100
Markus Armbruster129c7d12017-03-30 19:43:12 +02002101 /*
2102 * Caution: while qdict_get_try_str() is fine, getting non-string
2103 * types would require more care. When @options come from
2104 * -blockdev or blockdev_add, its members are typed according to
2105 * the QAPI schema, but when they come from -drive, they're all
2106 * QString.
2107 */
Max Reitzda557aa2013-12-20 19:28:11 +01002108 reference = qdict_get_try_str(options, bdref_key);
2109 if (!filename && !reference && !qdict_size(image_options)) {
Kevin Wolfb4b059f2015-06-15 13:24:19 +02002110 if (!allow_none) {
Max Reitzda557aa2013-12-20 19:28:11 +01002111 error_setg(errp, "A block device must be specified for \"%s\"",
2112 bdref_key);
Max Reitzda557aa2013-12-20 19:28:11 +01002113 }
Markus Armbrusterb20e61e2014-05-28 11:16:57 +02002114 QDECREF(image_options);
Max Reitzda557aa2013-12-20 19:28:11 +01002115 goto done;
2116 }
2117
Max Reitz5b363932016-05-17 16:41:31 +02002118 bs = bdrv_open_inherit(filename, reference, image_options, 0,
2119 parent, child_role, errp);
2120 if (!bs) {
Kevin Wolfdf581792015-06-15 11:53:47 +02002121 goto done;
2122 }
2123
Max Reitzda557aa2013-12-20 19:28:11 +01002124done:
2125 qdict_del(options, bdref_key);
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002126 return bs;
2127}
2128
2129/*
2130 * Opens a disk image whose options are given as BlockdevRef in another block
2131 * device's options.
2132 *
2133 * If allow_none is true, no image will be opened if filename is false and no
2134 * BlockdevRef is given. NULL will be returned, but errp remains unset.
2135 *
2136 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2137 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2138 * itself, all options starting with "${bdref_key}." are considered part of the
2139 * BlockdevRef.
2140 *
2141 * The BlockdevRef will be removed from the options QDict.
2142 */
2143BdrvChild *bdrv_open_child(const char *filename,
2144 QDict *options, const char *bdref_key,
2145 BlockDriverState *parent,
2146 const BdrvChildRole *child_role,
2147 bool allow_none, Error **errp)
2148{
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002149 BdrvChild *c;
Kevin Wolf2d6b86a2017-02-17 17:43:59 +01002150 BlockDriverState *bs;
2151
2152 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2153 allow_none, errp);
2154 if (bs == NULL) {
2155 return NULL;
2156 }
2157
Kevin Wolf8b2ff522016-12-20 22:21:17 +01002158 c = bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
2159 if (!c) {
2160 bdrv_unref(bs);
2161 return NULL;
2162 }
2163
2164 return c;
Kevin Wolfb4b059f2015-06-15 13:24:19 +02002165}
2166
Max Reitz66836182016-05-17 16:41:27 +02002167static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2168 int flags,
2169 QDict *snapshot_options,
2170 Error **errp)
Kevin Wolfb9988752014-04-03 12:09:34 +02002171{
2172 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002173 char *tmp_filename = g_malloc0(PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02002174 int64_t total_size;
Chunyan Liu83d05212014-06-05 17:20:51 +08002175 QemuOpts *opts = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02002176 BlockDriverState *bs_snapshot;
Kevin Wolfb2c28322017-02-20 12:46:42 +01002177 Error *local_err = NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02002178 int ret;
2179
2180 /* if snapshot, we create a temporary backing file and open it
2181 instead of opening 'filename' directly */
2182
2183 /* Get the required size from the image */
Kevin Wolff1877432014-04-04 17:07:19 +02002184 total_size = bdrv_getlength(bs);
2185 if (total_size < 0) {
2186 error_setg_errno(errp, -total_size, "Could not get image size");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002187 goto out;
Kevin Wolff1877432014-04-04 17:07:19 +02002188 }
Kevin Wolfb9988752014-04-03 12:09:34 +02002189
2190 /* Create the temporary image */
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002191 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
Kevin Wolfb9988752014-04-03 12:09:34 +02002192 if (ret < 0) {
2193 error_setg_errno(errp, -ret, "Could not get temporary filename");
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002194 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02002195 }
2196
Max Reitzef810432014-12-02 18:32:42 +01002197 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
Chunyan Liuc282e1f2014-06-05 17:21:11 +08002198 &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01002199 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
Markus Armbrustere43bfd92015-12-18 16:35:15 +01002200 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
Chunyan Liu83d05212014-06-05 17:20:51 +08002201 qemu_opts_del(opts);
Kevin Wolfb9988752014-04-03 12:09:34 +02002202 if (ret < 0) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01002203 error_prepend(errp, "Could not create temporary overlay '%s': ",
2204 tmp_filename);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002205 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02002206 }
2207
Kevin Wolf73176be2016-03-07 13:02:15 +01002208 /* Prepare options QDict for the temporary file */
Kevin Wolfb9988752014-04-03 12:09:34 +02002209 qdict_put(snapshot_options, "file.driver",
2210 qstring_from_str("file"));
2211 qdict_put(snapshot_options, "file.filename",
2212 qstring_from_str(tmp_filename));
Max Reitze6641712015-08-26 19:47:48 +02002213 qdict_put(snapshot_options, "driver",
2214 qstring_from_str("qcow2"));
Kevin Wolfb9988752014-04-03 12:09:34 +02002215
Max Reitz5b363932016-05-17 16:41:31 +02002216 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
Kevin Wolf73176be2016-03-07 13:02:15 +01002217 snapshot_options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02002218 if (!bs_snapshot) {
2219 ret = -EINVAL;
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002220 goto out;
Kevin Wolfb9988752014-04-03 12:09:34 +02002221 }
2222
Max Reitz66836182016-05-17 16:41:27 +02002223 /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
2224 * call bdrv_unref() on it), so in order to be able to return one, we have
2225 * to increase bs_snapshot's refcount here */
2226 bdrv_ref(bs_snapshot);
Kevin Wolfb2c28322017-02-20 12:46:42 +01002227 bdrv_append(bs_snapshot, bs, &local_err);
2228 if (local_err) {
2229 error_propagate(errp, local_err);
2230 ret = -EINVAL;
2231 goto out;
2232 }
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002233
Max Reitz66836182016-05-17 16:41:27 +02002234 g_free(tmp_filename);
2235 return bs_snapshot;
2236
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002237out:
Kevin Wolf73176be2016-03-07 13:02:15 +01002238 QDECREF(snapshot_options);
Benoît Canet1ba4b6a2014-04-22 17:05:27 +02002239 g_free(tmp_filename);
Max Reitz66836182016-05-17 16:41:27 +02002240 return NULL;
Kevin Wolfb9988752014-04-03 12:09:34 +02002241}
2242
Max Reitzda557aa2013-12-20 19:28:11 +01002243/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002244 * Opens a disk image (raw, qcow2, vmdk, ...)
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002245 *
2246 * options is a QDict of options to pass to the block drivers, or NULL for an
2247 * empty set of options. The reference to the QDict belongs to the block layer
2248 * after the call (even on failure), so if the caller intends to reuse the
2249 * dictionary, it needs to use QINCREF() before calling bdrv_open.
Max Reitzf67503e2014-02-18 18:33:05 +01002250 *
2251 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2252 * If it is not NULL, the referenced BDS will be reused.
Max Reitzddf56362014-02-18 18:33:06 +01002253 *
2254 * The reference parameter may be used to specify an existing block device which
2255 * should be opened. If specified, neither options nor a filename may be given,
2256 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002257 */
Max Reitz5b363932016-05-17 16:41:31 +02002258static BlockDriverState *bdrv_open_inherit(const char *filename,
2259 const char *reference,
2260 QDict *options, int flags,
2261 BlockDriverState *parent,
2262 const BdrvChildRole *child_role,
2263 Error **errp)
bellardea2384d2004-08-01 21:59:26 +00002264{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002265 int ret;
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002266 BlockBackend *file = NULL;
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02002267 BlockDriverState *bs;
Max Reitzce343772015-08-26 19:47:50 +02002268 BlockDriver *drv = NULL;
Kevin Wolf74fe54f2013-07-09 11:09:02 +02002269 const char *drvname;
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02002270 const char *backing;
Max Reitz34b5d2c2013-09-05 14:45:29 +02002271 Error *local_err = NULL;
Kevin Wolf73176be2016-03-07 13:02:15 +01002272 QDict *snapshot_options = NULL;
Kevin Wolfb1e6fc02014-05-06 12:11:42 +02002273 int snapshot_flags = 0;
bellard712e7872005-04-28 21:09:32 +00002274
Kevin Wolff3930ed2015-04-08 13:43:47 +02002275 assert(!child_role || !flags);
2276 assert(!child_role == !parent);
Max Reitzf67503e2014-02-18 18:33:05 +01002277
Max Reitzddf56362014-02-18 18:33:06 +01002278 if (reference) {
2279 bool options_non_empty = options ? qdict_size(options) : false;
2280 QDECREF(options);
2281
Max Reitzddf56362014-02-18 18:33:06 +01002282 if (filename || options_non_empty) {
2283 error_setg(errp, "Cannot reference an existing block device with "
2284 "additional options or a new filename");
Max Reitz5b363932016-05-17 16:41:31 +02002285 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01002286 }
2287
2288 bs = bdrv_lookup_bs(reference, reference, errp);
2289 if (!bs) {
Max Reitz5b363932016-05-17 16:41:31 +02002290 return NULL;
Max Reitzddf56362014-02-18 18:33:06 +01002291 }
Kevin Wolf76b22322016-04-04 17:11:13 +02002292
Max Reitzddf56362014-02-18 18:33:06 +01002293 bdrv_ref(bs);
Max Reitz5b363932016-05-17 16:41:31 +02002294 return bs;
Max Reitzddf56362014-02-18 18:33:06 +01002295 }
2296
Max Reitz5b363932016-05-17 16:41:31 +02002297 bs = bdrv_new();
Max Reitzf67503e2014-02-18 18:33:05 +01002298
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002299 /* NULL means an empty set of options */
2300 if (options == NULL) {
2301 options = qdict_new();
2302 }
2303
Kevin Wolf145f5982015-05-08 16:15:03 +02002304 /* json: syntax counts as explicit options, as if in the QDict */
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002305 parse_json_protocol(options, &filename, &local_err);
2306 if (local_err) {
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002307 goto fail;
2308 }
2309
Kevin Wolf145f5982015-05-08 16:15:03 +02002310 bs->explicit_options = qdict_clone_shallow(options);
2311
Kevin Wolff3930ed2015-04-08 13:43:47 +02002312 if (child_role) {
Kevin Wolfbddcec32015-04-09 18:47:50 +02002313 bs->inherits_from = parent;
Kevin Wolf8e2160e2015-04-29 17:29:39 +02002314 child_role->inherit_options(&flags, options,
2315 parent->open_flags, parent->options);
Kevin Wolff3930ed2015-04-08 13:43:47 +02002316 }
2317
Kevin Wolfde3b53f2015-10-29 15:24:41 +01002318 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
Kevin Wolf462f5bc2014-05-26 11:39:55 +02002319 if (local_err) {
2320 goto fail;
2321 }
2322
Markus Armbruster129c7d12017-03-30 19:43:12 +02002323 /*
2324 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
2325 * Caution: getting a boolean member of @options requires care.
2326 * When @options come from -blockdev or blockdev_add, members are
2327 * typed according to the QAPI schema, but when they come from
2328 * -drive, they're all QString.
2329 */
Alberto Garciaf87a0e22016-09-15 17:53:02 +03002330 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
2331 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
2332 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
2333 } else {
2334 flags &= ~BDRV_O_RDWR;
Alberto Garcia14499ea2016-09-15 17:53:00 +03002335 }
2336
2337 if (flags & BDRV_O_SNAPSHOT) {
2338 snapshot_options = qdict_new();
2339 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
2340 flags, options);
Alberto Garciaf87a0e22016-09-15 17:53:02 +03002341 /* Let bdrv_backing_options() override "read-only" */
2342 qdict_del(options, BDRV_OPT_READ_ONLY);
Alberto Garcia14499ea2016-09-15 17:53:00 +03002343 bdrv_backing_options(&flags, options, flags, options);
2344 }
2345
Kevin Wolf62392eb2015-04-24 16:38:02 +02002346 bs->open_flags = flags;
2347 bs->options = options;
2348 options = qdict_clone_shallow(options);
2349
Kevin Wolf76c591b2014-06-04 14:19:44 +02002350 /* Find the right image format driver */
Markus Armbruster129c7d12017-03-30 19:43:12 +02002351 /* See cautionary note on accessing @options above */
Kevin Wolf76c591b2014-06-04 14:19:44 +02002352 drvname = qdict_get_try_str(options, "driver");
2353 if (drvname) {
2354 drv = bdrv_find_format(drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02002355 if (!drv) {
2356 error_setg(errp, "Unknown driver: '%s'", drvname);
Kevin Wolf76c591b2014-06-04 14:19:44 +02002357 goto fail;
2358 }
2359 }
2360
2361 assert(drvname || !(flags & BDRV_O_PROTOCOL));
Kevin Wolf76c591b2014-06-04 14:19:44 +02002362
Markus Armbruster129c7d12017-03-30 19:43:12 +02002363 /* See cautionary note on accessing @options above */
Alberto Garcia3e8c2e52015-10-26 14:27:15 +02002364 backing = qdict_get_try_str(options, "backing");
2365 if (backing && *backing == '\0') {
2366 flags |= BDRV_O_NO_BACKING;
2367 qdict_del(options, "backing");
2368 }
2369
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002370 /* Open image file without format layer. This BlockBackend is only used for
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002371 * probing, the block drivers will do their own bdrv_open_child() for the
2372 * same BDS, which is why we put the node name back into options. */
Kevin Wolff4788ad2014-06-03 16:44:19 +02002373 if ((flags & BDRV_O_PROTOCOL) == 0) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002374 BlockDriverState *file_bs;
2375
2376 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
2377 &child_file, true, &local_err);
Kevin Wolf1fdd6932015-06-15 14:11:51 +02002378 if (local_err) {
Max Reitz5469a2a2014-02-18 18:33:10 +01002379 goto fail;
2380 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002381 if (file_bs != NULL) {
Kevin Wolf6d0eb642017-01-20 17:07:26 +01002382 file = blk_new(BLK_PERM_CONSISTENT_READ, BLK_PERM_ALL);
Kevin Wolfd7086422017-01-13 19:02:32 +01002383 blk_insert_bs(file, file_bs, &local_err);
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002384 bdrv_unref(file_bs);
Kevin Wolfd7086422017-01-13 19:02:32 +01002385 if (local_err) {
2386 goto fail;
2387 }
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002388
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002389 qdict_put(options, "file",
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002390 qstring_from_str(bdrv_get_node_name(file_bs)));
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002391 }
Max Reitz5469a2a2014-02-18 18:33:10 +01002392 }
2393
Kevin Wolf76c591b2014-06-04 14:19:44 +02002394 /* Image format probing */
Kevin Wolf38f3ef52014-11-20 16:27:12 +01002395 bs->probed = !drv;
Kevin Wolf76c591b2014-06-04 14:19:44 +02002396 if (!drv && file) {
Kevin Wolfcf2ab8f2016-06-20 18:24:02 +02002397 ret = find_image_format(file, filename, &drv, &local_err);
Kevin Wolf17b005f2014-05-27 10:50:29 +02002398 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02002399 goto fail;
Max Reitz2a05cbe2013-12-20 19:28:10 +01002400 }
Kevin Wolf62392eb2015-04-24 16:38:02 +02002401 /*
2402 * This option update would logically belong in bdrv_fill_options(),
2403 * but we first need to open bs->file for the probing to work, while
2404 * opening bs->file already requires the (mostly) final set of options
2405 * so that cache mode etc. can be inherited.
2406 *
2407 * Adding the driver later is somewhat ugly, but it's not an option
2408 * that would ever be inherited, so it's correct. We just need to make
2409 * sure to update both bs->options (which has the full effective
2410 * options for bs) and options (which has file.* already removed).
2411 */
2412 qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
2413 qdict_put(options, "driver", qstring_from_str(drv->format_name));
Kevin Wolf76c591b2014-06-04 14:19:44 +02002414 } else if (!drv) {
Kevin Wolf17b005f2014-05-27 10:50:29 +02002415 error_setg(errp, "Must specify either driver or file");
Kevin Wolf8bfea152014-04-11 19:16:36 +02002416 goto fail;
Kevin Wolff500a6d2012-11-12 17:35:27 +01002417 }
2418
Max Reitz53a29512015-03-19 14:53:16 -04002419 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
2420 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
2421 /* file must be NULL if a protocol BDS is about to be created
2422 * (the inverse results in an error message from bdrv_open_common()) */
2423 assert(!(flags & BDRV_O_PROTOCOL) || !file);
2424
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002425 /* Open the image */
Kevin Wolf82dc8b42016-01-11 19:07:50 +01002426 ret = bdrv_open_common(bs, file, options, &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002427 if (ret < 0) {
Kevin Wolf8bfea152014-04-11 19:16:36 +02002428 goto fail;
Christoph Hellwig69873072010-01-20 18:13:25 +01002429 }
2430
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002431 if (file) {
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002432 blk_unref(file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01002433 file = NULL;
2434 }
2435
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002436 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +02002437 if ((flags & BDRV_O_NO_BACKING) == 0) {
Kevin Wolfd9b7b052015-01-16 18:23:41 +01002438 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002439 if (ret < 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002440 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002441 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002442 }
2443
Max Reitz91af7012014-07-18 20:24:56 +02002444 bdrv_refresh_filename(bs);
2445
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002446 /* Check if any unknown options were used */
Paolo Bonzini7ad27572017-01-04 15:59:14 +01002447 if (qdict_size(options) != 0) {
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002448 const QDictEntry *entry = qdict_first(options);
Max Reitz5acd9d82014-02-18 18:33:11 +01002449 if (flags & BDRV_O_PROTOCOL) {
2450 error_setg(errp, "Block protocol '%s' doesn't support the option "
2451 "'%s'", drv->format_name, entry->key);
2452 } else {
Max Reitzd0e46a52016-03-16 19:54:34 +01002453 error_setg(errp,
2454 "Block format '%s' does not support the option '%s'",
2455 drv->format_name, entry->key);
Max Reitz5acd9d82014-02-18 18:33:11 +01002456 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002457
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002458 goto close_and_fail;
2459 }
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002460
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002461 if (!bdrv_key_required(bs)) {
Kevin Wolf5c8cab42016-02-24 15:13:35 +01002462 bdrv_parent_cb_change_media(bs, true);
Markus Armbrusterc3adb582014-03-14 09:22:48 +01002463 } else if (!runstate_check(RUN_STATE_PRELAUNCH)
2464 && !runstate_check(RUN_STATE_INMIGRATE)
2465 && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
2466 error_setg(errp,
2467 "Guest must be stopped for opening of encrypted image");
Markus Armbrusterc3adb582014-03-14 09:22:48 +01002468 goto close_and_fail;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002469 }
2470
Markus Armbrusterc3adb582014-03-14 09:22:48 +01002471 QDECREF(options);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02002472
2473 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
2474 * temporary snapshot afterwards. */
2475 if (snapshot_flags) {
Max Reitz66836182016-05-17 16:41:27 +02002476 BlockDriverState *snapshot_bs;
2477 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
2478 snapshot_options, &local_err);
Kevin Wolf73176be2016-03-07 13:02:15 +01002479 snapshot_options = NULL;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02002480 if (local_err) {
2481 goto close_and_fail;
2482 }
Max Reitz5b363932016-05-17 16:41:31 +02002483 /* We are not going to return bs but the overlay on top of it
2484 * (snapshot_bs); thus, we have to drop the strong reference to bs
2485 * (which we obtained by calling bdrv_new()). bs will not be deleted,
2486 * though, because the overlay still has a reference to it. */
2487 bdrv_unref(bs);
2488 bs = snapshot_bs;
Max Reitz66836182016-05-17 16:41:27 +02002489 }
2490
Max Reitz5b363932016-05-17 16:41:31 +02002491 return bs;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002492
Kevin Wolf8bfea152014-04-11 19:16:36 +02002493fail:
Kevin Wolf5696c6e2017-02-17 18:39:24 +01002494 blk_unref(file);
Kevin Wolf4e4bf5c2016-12-16 18:52:37 +01002495 if (bs->file != NULL) {
2496 bdrv_unref_child(bs, bs->file);
Kevin Wolff500a6d2012-11-12 17:35:27 +01002497 }
Kevin Wolf73176be2016-03-07 13:02:15 +01002498 QDECREF(snapshot_options);
Kevin Wolf145f5982015-05-08 16:15:03 +02002499 QDECREF(bs->explicit_options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002500 QDECREF(bs->options);
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002501 QDECREF(options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002502 bs->options = NULL;
Max Reitz5b363932016-05-17 16:41:31 +02002503 bdrv_unref(bs);
Eduardo Habkost621ff942016-06-13 18:57:56 -03002504 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02002505 return NULL;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002506
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002507close_and_fail:
Max Reitz5b363932016-05-17 16:41:31 +02002508 bdrv_unref(bs);
Kevin Wolf73176be2016-03-07 13:02:15 +01002509 QDECREF(snapshot_options);
Kevin Wolfb6ad4912013-03-15 10:35:04 +01002510 QDECREF(options);
Eduardo Habkost621ff942016-06-13 18:57:56 -03002511 error_propagate(errp, local_err);
Max Reitz5b363932016-05-17 16:41:31 +02002512 return NULL;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +02002513}
2514
Max Reitz5b363932016-05-17 16:41:31 +02002515BlockDriverState *bdrv_open(const char *filename, const char *reference,
2516 QDict *options, int flags, Error **errp)
Kevin Wolff3930ed2015-04-08 13:43:47 +02002517{
Max Reitz5b363932016-05-17 16:41:31 +02002518 return bdrv_open_inherit(filename, reference, options, flags, NULL,
Max Reitzce343772015-08-26 19:47:50 +02002519 NULL, errp);
Kevin Wolff3930ed2015-04-08 13:43:47 +02002520}
2521
Jeff Codye971aa12012-09-20 15:13:19 -04002522typedef struct BlockReopenQueueEntry {
2523 bool prepared;
2524 BDRVReopenState state;
2525 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
2526} BlockReopenQueueEntry;
2527
2528/*
2529 * Adds a BlockDriverState to a simple queue for an atomic, transactional
2530 * reopen of multiple devices.
2531 *
2532 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
2533 * already performed, or alternatively may be NULL a new BlockReopenQueue will
2534 * be created and initialized. This newly created BlockReopenQueue should be
2535 * passed back in for subsequent calls that are intended to be of the same
2536 * atomic 'set'.
2537 *
2538 * bs is the BlockDriverState to add to the reopen queue.
2539 *
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002540 * options contains the changed options for the associated bs
2541 * (the BlockReopenQueue takes ownership)
2542 *
Jeff Codye971aa12012-09-20 15:13:19 -04002543 * flags contains the open flags for the associated bs
2544 *
2545 * returns a pointer to bs_queue, which is either the newly allocated
2546 * bs_queue, or the existing bs_queue being used.
2547 *
2548 */
Kevin Wolf28518102015-05-08 17:07:31 +02002549static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
2550 BlockDriverState *bs,
2551 QDict *options,
2552 int flags,
2553 const BdrvChildRole *role,
2554 QDict *parent_options,
2555 int parent_flags)
Jeff Codye971aa12012-09-20 15:13:19 -04002556{
2557 assert(bs != NULL);
2558
2559 BlockReopenQueueEntry *bs_entry;
Kevin Wolf67251a32015-04-09 18:54:04 +02002560 BdrvChild *child;
Kevin Wolf145f5982015-05-08 16:15:03 +02002561 QDict *old_options, *explicit_options;
Kevin Wolf67251a32015-04-09 18:54:04 +02002562
Jeff Codye971aa12012-09-20 15:13:19 -04002563 if (bs_queue == NULL) {
2564 bs_queue = g_new0(BlockReopenQueue, 1);
2565 QSIMPLEQ_INIT(bs_queue);
2566 }
2567
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002568 if (!options) {
2569 options = qdict_new();
2570 }
2571
Alberto Garcia5b7ba052016-09-15 17:53:03 +03002572 /* Check if this BlockDriverState is already in the queue */
2573 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2574 if (bs == bs_entry->state.bs) {
2575 break;
2576 }
2577 }
2578
Kevin Wolf28518102015-05-08 17:07:31 +02002579 /*
2580 * Precedence of options:
2581 * 1. Explicitly passed in options (highest)
Kevin Wolf91a097e2015-05-08 17:49:53 +02002582 * 2. Set in flags (only for top level)
Kevin Wolf145f5982015-05-08 16:15:03 +02002583 * 3. Retained from explicitly set options of bs
Kevin Wolf8e2160e2015-04-29 17:29:39 +02002584 * 4. Inherited from parent node
Kevin Wolf28518102015-05-08 17:07:31 +02002585 * 5. Retained from effective options of bs
2586 */
2587
Kevin Wolf91a097e2015-05-08 17:49:53 +02002588 if (!parent_options) {
2589 /*
2590 * Any setting represented by flags is always updated. If the
2591 * corresponding QDict option is set, it takes precedence. Otherwise
2592 * the flag is translated into a QDict option. The old setting of bs is
2593 * not considered.
2594 */
2595 update_options_from_flags(options, flags);
2596 }
2597
Kevin Wolf145f5982015-05-08 16:15:03 +02002598 /* Old explicitly set values (don't overwrite by inherited value) */
Alberto Garcia5b7ba052016-09-15 17:53:03 +03002599 if (bs_entry) {
2600 old_options = qdict_clone_shallow(bs_entry->state.explicit_options);
2601 } else {
2602 old_options = qdict_clone_shallow(bs->explicit_options);
2603 }
Kevin Wolf145f5982015-05-08 16:15:03 +02002604 bdrv_join_options(bs, options, old_options);
2605 QDECREF(old_options);
2606
2607 explicit_options = qdict_clone_shallow(options);
2608
Kevin Wolf28518102015-05-08 17:07:31 +02002609 /* Inherit from parent node */
2610 if (parent_options) {
2611 assert(!flags);
Kevin Wolf8e2160e2015-04-29 17:29:39 +02002612 role->inherit_options(&flags, options, parent_flags, parent_options);
Kevin Wolf28518102015-05-08 17:07:31 +02002613 }
2614
2615 /* Old values are used for options that aren't set yet */
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002616 old_options = qdict_clone_shallow(bs->options);
Kevin Wolfcddff5b2015-11-16 16:43:27 +01002617 bdrv_join_options(bs, options, old_options);
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002618 QDECREF(old_options);
2619
Kevin Wolff1f25a22014-04-25 19:04:55 +02002620 /* bdrv_open() masks this flag out */
2621 flags &= ~BDRV_O_PROTOCOL;
2622
Kevin Wolf67251a32015-04-09 18:54:04 +02002623 QLIST_FOREACH(child, &bs->children, next) {
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02002624 QDict *new_child_options;
2625 char *child_key_dot;
Kevin Wolf67251a32015-04-09 18:54:04 +02002626
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02002627 /* reopen can only change the options of block devices that were
2628 * implicitly created and inherited options. For other (referenced)
2629 * block devices, a syntax like "backing.foo" results in an error. */
Kevin Wolf67251a32015-04-09 18:54:04 +02002630 if (child->bs->inherits_from != bs) {
2631 continue;
2632 }
2633
Kevin Wolf4c9dfe52015-05-08 15:14:15 +02002634 child_key_dot = g_strdup_printf("%s.", child->name);
2635 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
2636 g_free(child_key_dot);
2637
Kevin Wolf28518102015-05-08 17:07:31 +02002638 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
2639 child->role, options, flags);
Jeff Codye971aa12012-09-20 15:13:19 -04002640 }
2641
Alberto Garcia5b7ba052016-09-15 17:53:03 +03002642 if (!bs_entry) {
2643 bs_entry = g_new0(BlockReopenQueueEntry, 1);
2644 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
2645 } else {
2646 QDECREF(bs_entry->state.options);
2647 QDECREF(bs_entry->state.explicit_options);
2648 }
Jeff Codye971aa12012-09-20 15:13:19 -04002649
2650 bs_entry->state.bs = bs;
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002651 bs_entry->state.options = options;
Kevin Wolf145f5982015-05-08 16:15:03 +02002652 bs_entry->state.explicit_options = explicit_options;
Jeff Codye971aa12012-09-20 15:13:19 -04002653 bs_entry->state.flags = flags;
2654
2655 return bs_queue;
2656}
2657
Kevin Wolf28518102015-05-08 17:07:31 +02002658BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
2659 BlockDriverState *bs,
2660 QDict *options, int flags)
2661{
2662 return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
2663 NULL, NULL, 0);
2664}
2665
Jeff Codye971aa12012-09-20 15:13:19 -04002666/*
2667 * Reopen multiple BlockDriverStates atomically & transactionally.
2668 *
2669 * The queue passed in (bs_queue) must have been built up previous
2670 * via bdrv_reopen_queue().
2671 *
2672 * Reopens all BDS specified in the queue, with the appropriate
2673 * flags. All devices are prepared for reopen, and failure of any
2674 * device will cause all device changes to be abandonded, and intermediate
2675 * data cleaned up.
2676 *
2677 * If all devices prepare successfully, then the changes are committed
2678 * to all devices.
2679 *
2680 */
Paolo Bonzini720150f2016-10-27 12:49:02 +02002681int bdrv_reopen_multiple(AioContext *ctx, BlockReopenQueue *bs_queue, Error **errp)
Jeff Codye971aa12012-09-20 15:13:19 -04002682{
2683 int ret = -1;
2684 BlockReopenQueueEntry *bs_entry, *next;
2685 Error *local_err = NULL;
2686
2687 assert(bs_queue != NULL);
2688
Paolo Bonzinic9d1a562016-10-27 12:49:05 +02002689 aio_context_release(ctx);
Alberto Garcia40840e42016-10-28 10:08:03 +03002690 bdrv_drain_all_begin();
Paolo Bonzinic9d1a562016-10-27 12:49:05 +02002691 aio_context_acquire(ctx);
Jeff Codye971aa12012-09-20 15:13:19 -04002692
2693 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2694 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
2695 error_propagate(errp, local_err);
2696 goto cleanup;
2697 }
2698 bs_entry->prepared = true;
2699 }
2700
2701 /* If we reach this point, we have success and just need to apply the
2702 * changes
2703 */
2704 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2705 bdrv_reopen_commit(&bs_entry->state);
2706 }
2707
2708 ret = 0;
2709
2710cleanup:
2711 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
2712 if (ret && bs_entry->prepared) {
2713 bdrv_reopen_abort(&bs_entry->state);
Kevin Wolf145f5982015-05-08 16:15:03 +02002714 } else if (ret) {
2715 QDECREF(bs_entry->state.explicit_options);
Jeff Codye971aa12012-09-20 15:13:19 -04002716 }
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002717 QDECREF(bs_entry->state.options);
Jeff Codye971aa12012-09-20 15:13:19 -04002718 g_free(bs_entry);
2719 }
2720 g_free(bs_queue);
Alberto Garcia40840e42016-10-28 10:08:03 +03002721
2722 bdrv_drain_all_end();
2723
Jeff Codye971aa12012-09-20 15:13:19 -04002724 return ret;
2725}
2726
2727
2728/* Reopen a single BlockDriverState with the specified flags. */
2729int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
2730{
2731 int ret = -1;
2732 Error *local_err = NULL;
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002733 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
Jeff Codye971aa12012-09-20 15:13:19 -04002734
Paolo Bonzini720150f2016-10-27 12:49:02 +02002735 ret = bdrv_reopen_multiple(bdrv_get_aio_context(bs), queue, &local_err);
Jeff Codye971aa12012-09-20 15:13:19 -04002736 if (local_err != NULL) {
2737 error_propagate(errp, local_err);
2738 }
2739 return ret;
2740}
2741
2742
2743/*
2744 * Prepares a BlockDriverState for reopen. All changes are staged in the
2745 * 'opaque' field of the BDRVReopenState, which is used and allocated by
2746 * the block driver layer .bdrv_reopen_prepare()
2747 *
2748 * bs is the BlockDriverState to reopen
2749 * flags are the new open flags
2750 * queue is the reopen queue
2751 *
2752 * Returns 0 on success, non-zero on error. On error errp will be set
2753 * as well.
2754 *
2755 * On failure, bdrv_reopen_abort() will be called to clean up any data.
2756 * It is the responsibility of the caller to then call the abort() or
2757 * commit() for any other BDS that have been left in a prepare() state
2758 *
2759 */
2760int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
2761 Error **errp)
2762{
2763 int ret = -1;
2764 Error *local_err = NULL;
2765 BlockDriver *drv;
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002766 QemuOpts *opts;
2767 const char *value;
Jeff Codye971aa12012-09-20 15:13:19 -04002768
2769 assert(reopen_state != NULL);
2770 assert(reopen_state->bs->drv != NULL);
2771 drv = reopen_state->bs->drv;
2772
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002773 /* Process generic block layer options */
2774 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2775 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2776 if (local_err) {
2777 error_propagate(errp, local_err);
2778 ret = -EINVAL;
2779 goto error;
2780 }
2781
Kevin Wolf91a097e2015-05-08 17:49:53 +02002782 update_flags_from_options(&reopen_state->flags, opts);
2783
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002784 /* node-name and driver must be unchanged. Put them back into the QDict, so
2785 * that they are checked at the end of this function. */
2786 value = qemu_opt_get(opts, "node-name");
2787 if (value) {
2788 qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2789 }
2790
2791 value = qemu_opt_get(opts, "driver");
2792 if (value) {
2793 qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2794 }
2795
Jeff Codye971aa12012-09-20 15:13:19 -04002796 /* if we are to stay read-only, do not allow permission change
2797 * to r/w */
2798 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2799 reopen_state->flags & BDRV_O_RDWR) {
Alberto Garcia81e5f782015-04-08 12:29:19 +03002800 error_setg(errp, "Node '%s' is read only",
2801 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04002802 goto error;
2803 }
2804
2805
2806 ret = bdrv_flush(reopen_state->bs);
2807 if (ret) {
Eric Blake455b0fd2015-11-10 23:51:20 -07002808 error_setg_errno(errp, -ret, "Error flushing drive");
Jeff Codye971aa12012-09-20 15:13:19 -04002809 goto error;
2810 }
2811
2812 if (drv->bdrv_reopen_prepare) {
2813 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2814 if (ret) {
2815 if (local_err != NULL) {
2816 error_propagate(errp, local_err);
2817 } else {
Luiz Capitulinod8b68952013-06-10 11:29:27 -04002818 error_setg(errp, "failed while preparing to reopen image '%s'",
2819 reopen_state->bs->filename);
Jeff Codye971aa12012-09-20 15:13:19 -04002820 }
2821 goto error;
2822 }
2823 } else {
2824 /* It is currently mandatory to have a bdrv_reopen_prepare()
2825 * handler for each supported drv. */
Alberto Garcia81e5f782015-04-08 12:29:19 +03002826 error_setg(errp, "Block format '%s' used by node '%s' "
2827 "does not support reopening files", drv->format_name,
2828 bdrv_get_device_or_node_name(reopen_state->bs));
Jeff Codye971aa12012-09-20 15:13:19 -04002829 ret = -1;
2830 goto error;
2831 }
2832
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002833 /* Options that are not handled are only okay if they are unchanged
2834 * compared to the old state. It is expected that some options are only
2835 * used for the initial open, but not reopen (e.g. filename) */
2836 if (qdict_size(reopen_state->options)) {
2837 const QDictEntry *entry = qdict_first(reopen_state->options);
2838
2839 do {
2840 QString *new_obj = qobject_to_qstring(entry->value);
2841 const char *new = qstring_get_str(new_obj);
Markus Armbruster129c7d12017-03-30 19:43:12 +02002842 /*
2843 * Caution: while qdict_get_try_str() is fine, getting
2844 * non-string types would require more care. When
2845 * bs->options come from -blockdev or blockdev_add, its
2846 * members are typed according to the QAPI schema, but
2847 * when they come from -drive, they're all QString.
2848 */
Kevin Wolf4d2cb092015-04-10 17:50:50 +02002849 const char *old = qdict_get_try_str(reopen_state->bs->options,
2850 entry->key);
2851
2852 if (!old || strcmp(new, old)) {
2853 error_setg(errp, "Cannot change the option '%s'", entry->key);
2854 ret = -EINVAL;
2855 goto error;
2856 }
2857 } while ((entry = qdict_next(reopen_state->options, entry)));
2858 }
2859
Jeff Codye971aa12012-09-20 15:13:19 -04002860 ret = 0;
2861
2862error:
Kevin Wolfccf9dc02015-05-08 17:24:56 +02002863 qemu_opts_del(opts);
Jeff Codye971aa12012-09-20 15:13:19 -04002864 return ret;
2865}
2866
2867/*
2868 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2869 * makes them final by swapping the staging BlockDriverState contents into
2870 * the active BlockDriverState contents.
2871 */
2872void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2873{
2874 BlockDriver *drv;
2875
2876 assert(reopen_state != NULL);
2877 drv = reopen_state->bs->drv;
2878 assert(drv != NULL);
2879
2880 /* If there are any driver level actions to take */
2881 if (drv->bdrv_reopen_commit) {
2882 drv->bdrv_reopen_commit(reopen_state);
2883 }
2884
2885 /* set BDS specific flags now */
Kevin Wolf145f5982015-05-08 16:15:03 +02002886 QDECREF(reopen_state->bs->explicit_options);
2887
2888 reopen_state->bs->explicit_options = reopen_state->explicit_options;
Jeff Codye971aa12012-09-20 15:13:19 -04002889 reopen_state->bs->open_flags = reopen_state->flags;
Jeff Codye971aa12012-09-20 15:13:19 -04002890 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
Kevin Wolf355ef4a2013-12-11 20:14:09 +01002891
Kevin Wolf3baca892014-07-16 17:48:16 +02002892 bdrv_refresh_limits(reopen_state->bs, NULL);
Jeff Codye971aa12012-09-20 15:13:19 -04002893}
2894
2895/*
2896 * Abort the reopen, and delete and free the staged changes in
2897 * reopen_state
2898 */
2899void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2900{
2901 BlockDriver *drv;
2902
2903 assert(reopen_state != NULL);
2904 drv = reopen_state->bs->drv;
2905 assert(drv != NULL);
2906
2907 if (drv->bdrv_reopen_abort) {
2908 drv->bdrv_reopen_abort(reopen_state);
2909 }
Kevin Wolf145f5982015-05-08 16:15:03 +02002910
2911 QDECREF(reopen_state->explicit_options);
Jeff Codye971aa12012-09-20 15:13:19 -04002912}
2913
2914
Max Reitz64dff522016-01-29 16:36:10 +01002915static void bdrv_close(BlockDriverState *bs)
bellardfc01f7e2003-06-30 10:03:06 +00002916{
Max Reitz33384422014-06-20 21:57:33 +02002917 BdrvAioNotifier *ban, *ban_next;
2918
Max Reitzca9bd242016-01-29 16:36:14 +01002919 assert(!bs->job);
Max Reitz30f55fb2016-05-17 16:41:32 +02002920 assert(!bs->refcnt);
Alberto Garcia99b7e772015-09-25 16:41:44 +03002921
Paolo Bonzinifc272912015-12-23 11:48:24 +01002922 bdrv_drained_begin(bs); /* complete I/O */
Stefan Hajnoczi58fda172013-07-02 15:36:25 +02002923 bdrv_flush(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08002924 bdrv_drain(bs); /* in case flush left pending I/O */
Paolo Bonzinifc272912015-12-23 11:48:24 +01002925
Max Reitzc5acdc92016-01-29 16:36:01 +01002926 bdrv_release_named_dirty_bitmaps(bs);
2927 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2928
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02002929 if (bs->drv) {
Kevin Wolf6e93e7c2015-04-08 13:49:41 +02002930 BdrvChild *child, *next;
2931
Kevin Wolf9a7dedb2015-06-16 10:58:20 +02002932 bs->drv->bdrv_close(bs);
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02002933 bs->drv = NULL;
Kevin Wolf9a7dedb2015-06-16 10:58:20 +02002934
Kevin Wolf12fa4af2017-02-17 20:42:32 +01002935 bdrv_set_backing_hd(bs, NULL, &error_abort);
Kevin Wolf9a7dedb2015-06-16 10:58:20 +02002936
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02002937 if (bs->file != NULL) {
2938 bdrv_unref_child(bs, bs->file);
2939 bs->file = NULL;
2940 }
2941
Kevin Wolf6e93e7c2015-04-08 13:49:41 +02002942 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
Kevin Wolf33a60402015-06-15 13:51:04 +02002943 /* TODO Remove bdrv_unref() from drivers' close function and use
2944 * bdrv_unref_child() here */
Kevin Wolfbddcec32015-04-09 18:47:50 +02002945 if (child->bs->inherits_from == bs) {
2946 child->bs->inherits_from = NULL;
2947 }
Kevin Wolf33a60402015-06-15 13:51:04 +02002948 bdrv_detach_child(child);
Kevin Wolf6e93e7c2015-04-08 13:49:41 +02002949 }
2950
Anthony Liguori7267c092011-08-20 22:09:37 -05002951 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +00002952 bs->opaque = NULL;
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00002953 bs->copy_on_read = 0;
Paolo Bonzinia275fa42012-05-08 16:51:43 +02002954 bs->backing_file[0] = '\0';
2955 bs->backing_format[0] = '\0';
Paolo Bonzini64058752012-05-08 16:51:49 +02002956 bs->total_sectors = 0;
Eric Blake54115412016-06-23 16:37:26 -06002957 bs->encrypted = false;
2958 bs->valid_key = false;
2959 bs->sg = false;
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002960 QDECREF(bs->options);
Kevin Wolf145f5982015-05-08 16:15:03 +02002961 QDECREF(bs->explicit_options);
Kevin Wolfde9c0ce2013-03-15 10:35:02 +01002962 bs->options = NULL;
Max Reitz91af7012014-07-18 20:24:56 +02002963 QDECREF(bs->full_open_options);
2964 bs->full_open_options = NULL;
bellardb3380822004-03-14 21:38:54 +00002965 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08002966
Max Reitz33384422014-06-20 21:57:33 +02002967 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
2968 g_free(ban);
2969 }
2970 QLIST_INIT(&bs->aio_notifiers);
Paolo Bonzinifc272912015-12-23 11:48:24 +01002971 bdrv_drained_end(bs);
bellardb3380822004-03-14 21:38:54 +00002972}
2973
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09002974void bdrv_close_all(void)
2975{
Kevin Wolfa1a2af02016-04-08 18:26:37 +02002976 block_job_cancel_sync_all();
Kevin Wolfcd7fca92016-07-06 11:22:39 +02002977 nbd_export_close_all();
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09002978
Max Reitzca9bd242016-01-29 16:36:14 +01002979 /* Drop references from requests still in flight, such as canceled block
2980 * jobs whose AIO context has not been polled yet */
2981 bdrv_drain_all();
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02002982
Max Reitzca9bd242016-01-29 16:36:14 +01002983 blk_remove_all_bs();
2984 blockdev_close_all_bdrv_states();
2985
Kevin Wolfa1a2af02016-04-08 18:26:37 +02002986 assert(QTAILQ_EMPTY(&all_bdrv_states));
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09002987}
2988
Kevin Wolfd0ac0382017-03-01 17:30:41 +01002989static bool should_update_child(BdrvChild *c, BlockDriverState *to)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02002990{
Kevin Wolfd0ac0382017-03-01 17:30:41 +01002991 BdrvChild *to_c;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02002992
Kevin Wolfd0ac0382017-03-01 17:30:41 +01002993 if (c->role->stay_at_node) {
2994 return false;
2995 }
2996
2997 if (c->role == &child_backing) {
2998 /* If @from is a backing file of @to, ignore the child to avoid
2999 * creating a loop. We only want to change the pointer of other
3000 * parents. */
3001 QLIST_FOREACH(to_c, &to->children, next) {
3002 if (to_c == c) {
3003 break;
3004 }
3005 }
3006 if (to_c) {
3007 return false;
3008 }
3009 }
3010
3011 return true;
3012}
3013
Kevin Wolf5fe31c22017-03-06 16:20:51 +01003014void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
3015 Error **errp)
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003016{
Kevin Wolfd0ac0382017-03-01 17:30:41 +01003017 BdrvChild *c, *next;
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003018 GSList *list = NULL, *p;
3019 uint64_t old_perm, old_shared;
3020 uint64_t perm = 0, shared = BLK_PERM_ALL;
3021 int ret;
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003022
Kevin Wolf5fe31c22017-03-06 16:20:51 +01003023 assert(!atomic_read(&from->in_flight));
3024 assert(!atomic_read(&to->in_flight));
3025
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003026 /* Make sure that @from doesn't go away until we have successfully attached
3027 * all of its parents to @to. */
3028 bdrv_ref(from);
3029
3030 /* Put all parents into @list and calculate their cumulative permissions */
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003031 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
Kevin Wolfd0ac0382017-03-01 17:30:41 +01003032 if (!should_update_child(c, to)) {
Kevin Wolf26de9432017-01-17 13:39:34 +01003033 continue;
3034 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003035 list = g_slist_prepend(list, c);
3036 perm |= c->perm;
3037 shared &= c->shared_perm;
3038 }
3039
3040 /* Check whether the required permissions can be granted on @to, ignoring
3041 * all BdrvChild in @list so that they can't block themselves. */
3042 ret = bdrv_check_update_perm(to, perm, shared, list, errp);
3043 if (ret < 0) {
3044 bdrv_abort_perm_update(to);
3045 goto out;
3046 }
3047
3048 /* Now actually perform the change. We performed the permission check for
3049 * all elements of @list at once, so set the permissions all at once at the
3050 * very end. */
3051 for (p = list; p != NULL; p = p->next) {
3052 c = p->data;
Max Reitz9bd910e2016-06-10 20:57:46 +02003053
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003054 bdrv_ref(to);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003055 bdrv_replace_child_noperm(c, to);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003056 bdrv_unref(from);
3057 }
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003058
3059 bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
3060 bdrv_set_perm(to, old_perm | perm, old_shared | shared);
3061
3062out:
3063 g_slist_free(list);
3064 bdrv_unref(from);
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003065}
3066
Jeff Cody8802d1f2012-02-28 15:54:06 -05003067/*
3068 * Add new bs contents at the top of an image chain while the chain is
3069 * live, while keeping required fields on the top layer.
3070 *
3071 * This will modify the BlockDriverState fields, and swap contents
3072 * between bs_new and bs_top. Both bs_new and bs_top are modified.
3073 *
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02003074 * bs_new must not be attached to a BlockBackend.
Jeff Codyf6801b82012-03-27 16:30:19 -04003075 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05003076 * This function does not create any image files.
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003077 *
3078 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
3079 * that's what the callers commonly need. bs_new will be referenced by the old
3080 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
3081 * reference of its own, it must call bdrv_ref().
Jeff Cody8802d1f2012-02-28 15:54:06 -05003082 */
Kevin Wolfb2c28322017-02-20 12:46:42 +01003083void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
3084 Error **errp)
Jeff Cody8802d1f2012-02-28 15:54:06 -05003085{
Kevin Wolfb2c28322017-02-20 12:46:42 +01003086 Error *local_err = NULL;
3087
Kevin Wolfb2c28322017-02-20 12:46:42 +01003088 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
3089 if (local_err) {
3090 error_propagate(errp, local_err);
3091 goto out;
3092 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003093
Kevin Wolf5fe31c22017-03-06 16:20:51 +01003094 bdrv_replace_node(bs_top, bs_new, &local_err);
Kevin Wolf234ac1a2017-03-02 18:43:00 +01003095 if (local_err) {
3096 error_propagate(errp, local_err);
3097 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
3098 goto out;
3099 }
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003100
3101 /* bs_new is now referenced by its new parents, we don't need the
3102 * additional reference any more. */
Kevin Wolfb2c28322017-02-20 12:46:42 +01003103out:
Kevin Wolfdd62f1c2015-06-18 14:09:57 +02003104 bdrv_unref(bs_new);
Jeff Cody8802d1f2012-02-28 15:54:06 -05003105}
3106
Fam Zheng4f6fd342013-08-23 09:14:47 +08003107static void bdrv_delete(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00003108{
Paolo Bonzini3e914652012-03-30 13:17:11 +02003109 assert(!bs->job);
Fam Zheng3718d8a2014-05-23 21:29:43 +08003110 assert(bdrv_op_blocker_is_empty(bs));
Fam Zheng4f6fd342013-08-23 09:14:47 +08003111 assert(!bs->refcnt);
Markus Armbruster18846de2010-06-29 16:58:30 +02003112
Stefan Hajnoczie1b5c522013-06-27 15:32:26 +02003113 bdrv_close(bs);
3114
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01003115 /* remove from list, if necessary */
Kevin Wolf63eaaae2016-03-18 10:46:57 +01003116 if (bs->node_name[0] != '\0') {
3117 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
3118 }
Max Reitz2c1d04e2016-01-29 16:36:11 +01003119 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
3120
Anthony Liguori7267c092011-08-20 22:09:37 -05003121 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00003122}
3123
aliguorie97fc192009-04-21 23:11:50 +00003124/*
3125 * Run consistency checks on an image
3126 *
Kevin Wolfe076f332010-06-29 11:43:13 +02003127 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02003128 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02003129 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00003130 */
Kevin Wolf4534ff52012-05-11 16:07:02 +02003131int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00003132{
Max Reitz908bcd52014-08-07 22:47:55 +02003133 if (bs->drv == NULL) {
3134 return -ENOMEDIUM;
3135 }
aliguorie97fc192009-04-21 23:11:50 +00003136 if (bs->drv->bdrv_check == NULL) {
3137 return -ENOTSUP;
3138 }
3139
Kevin Wolfe076f332010-06-29 11:43:13 +02003140 memset(res, 0, sizeof(*res));
Kevin Wolf4534ff52012-05-11 16:07:02 +02003141 return bs->drv->bdrv_check(bs, res, fix);
aliguorie97fc192009-04-21 23:11:50 +00003142}
3143
Kevin Wolf756e6732010-01-12 12:55:17 +01003144/*
3145 * Return values:
3146 * 0 - success
3147 * -EINVAL - backing format specified, but no file
3148 * -ENOSPC - can't update the backing file because no space is left in the
3149 * image file header
3150 * -ENOTSUP - format driver doesn't support changing the backing file
3151 */
3152int bdrv_change_backing_file(BlockDriverState *bs,
3153 const char *backing_file, const char *backing_fmt)
3154{
3155 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02003156 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01003157
Paolo Bonzini5f377792012-04-12 14:01:01 +02003158 /* Backing file format doesn't make sense without a backing file */
3159 if (backing_fmt && !backing_file) {
3160 return -EINVAL;
3161 }
3162
Kevin Wolf756e6732010-01-12 12:55:17 +01003163 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02003164 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01003165 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02003166 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01003167 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02003168
3169 if (ret == 0) {
3170 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3171 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3172 }
3173 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01003174}
3175
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003176/*
3177 * Finds the image layer in the chain that has 'bs' as its backing file.
3178 *
3179 * active is the current topmost image.
3180 *
3181 * Returns NULL if bs is not found in active's image chain,
3182 * or if active == bs.
Jeff Cody4caf0fc2014-06-25 15:35:26 -04003183 *
3184 * Returns the bottommost base image if bs == NULL.
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003185 */
3186BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
3187 BlockDriverState *bs)
3188{
Kevin Wolf760e0062015-06-17 14:55:21 +02003189 while (active && bs != backing_bs(active)) {
3190 active = backing_bs(active);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003191 }
3192
Jeff Cody4caf0fc2014-06-25 15:35:26 -04003193 return active;
3194}
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003195
Jeff Cody4caf0fc2014-06-25 15:35:26 -04003196/* Given a BDS, searches for the base layer. */
3197BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3198{
3199 return bdrv_find_overlay(bs, NULL);
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003200}
3201
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003202/*
3203 * Drops images above 'base' up to and including 'top', and sets the image
3204 * above 'top' to have base as its backing file.
3205 *
3206 * Requires that the overlay to 'top' is opened r/w, so that the backing file
3207 * information in 'bs' can be properly updated.
3208 *
3209 * E.g., this will convert the following chain:
3210 * bottom <- base <- intermediate <- top <- active
3211 *
3212 * to
3213 *
3214 * bottom <- base <- active
3215 *
3216 * It is allowed for bottom==base, in which case it converts:
3217 *
3218 * base <- intermediate <- top <- active
3219 *
3220 * to
3221 *
3222 * base <- active
3223 *
Jeff Cody54e26902014-06-25 15:40:10 -04003224 * If backing_file_str is non-NULL, it will be used when modifying top's
3225 * overlay image metadata.
3226 *
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003227 * Error conditions:
3228 * if active == top, that is considered an error
3229 *
3230 */
3231int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
Jeff Cody54e26902014-06-25 15:40:10 -04003232 BlockDriverState *base, const char *backing_file_str)
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003233{
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003234 BlockDriverState *new_top_bs = NULL;
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003235 Error *local_err = NULL;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003236 int ret = -EIO;
3237
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003238 if (!top->drv || !base->drv) {
3239 goto exit;
3240 }
3241
3242 new_top_bs = bdrv_find_overlay(active, top);
3243
3244 if (new_top_bs == NULL) {
3245 /* we could not find the image above 'top', this is an error */
3246 goto exit;
3247 }
3248
Kevin Wolf760e0062015-06-17 14:55:21 +02003249 /* special case of new_top_bs->backing->bs already pointing to base - nothing
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003250 * to do, no intermediate images */
Kevin Wolf760e0062015-06-17 14:55:21 +02003251 if (backing_bs(new_top_bs) == base) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003252 ret = 0;
3253 goto exit;
3254 }
3255
Kevin Wolf5db15a52015-09-14 15:33:33 +02003256 /* Make sure that base is in the backing chain of top */
3257 if (!bdrv_chain_contains(top, base)) {
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003258 goto exit;
3259 }
3260
3261 /* success - we can delete the intermediate states, and link top->base */
Kevin Wolf5db15a52015-09-14 15:33:33 +02003262 backing_file_str = backing_file_str ? backing_file_str : base->filename;
Jeff Cody54e26902014-06-25 15:40:10 -04003263 ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
Kevin Wolf5db15a52015-09-14 15:33:33 +02003264 base->drv ? base->drv->format_name : "");
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003265 if (ret) {
3266 goto exit;
3267 }
Kevin Wolf12fa4af2017-02-17 20:42:32 +01003268
3269 bdrv_set_backing_hd(new_top_bs, base, &local_err);
3270 if (local_err) {
3271 ret = -EPERM;
3272 error_report_err(local_err);
3273 goto exit;
3274 }
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003275
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003276 ret = 0;
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003277exit:
Jeff Cody6ebdcee2012-09-27 13:29:12 -04003278 return ret;
3279}
3280
bellard83f64092006-08-01 16:21:11 +00003281/**
bellard83f64092006-08-01 16:21:11 +00003282 * Truncate file to 'offset' bytes (needed only for file protocols)
3283 */
Kevin Wolf52cdbc52017-02-16 18:39:03 +01003284int bdrv_truncate(BdrvChild *child, int64_t offset)
bellard83f64092006-08-01 16:21:11 +00003285{
Kevin Wolf52cdbc52017-02-16 18:39:03 +01003286 BlockDriverState *bs = child->bs;
bellard83f64092006-08-01 16:21:11 +00003287 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003288 int ret;
Kevin Wolfc8f6d582017-02-17 14:52:00 +01003289
Max Reitze3e00032017-04-11 16:50:50 +02003290 /* FIXME: Some format block drivers use this function instead of implicitly
3291 * growing their file by writing beyond its end.
3292 * See bdrv_aligned_pwritev() for an explanation why we currently
3293 * cannot assert this permission in that case. */
3294 // assert(child->perm & BLK_PERM_RESIZE);
Kevin Wolfc8f6d582017-02-17 14:52:00 +01003295
bellard83f64092006-08-01 16:21:11 +00003296 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003297 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00003298 if (!drv->bdrv_truncate)
3299 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02003300 if (bs->read_only)
3301 return -EACCES;
Jeff Cody9c75e162014-06-25 16:55:30 -04003302
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003303 ret = drv->bdrv_truncate(bs, offset);
3304 if (ret == 0) {
3305 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
John Snowce1ffea2015-04-17 19:50:03 -04003306 bdrv_dirty_bitmap_truncate(bs);
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003307 bdrv_parent_cb_resize(bs);
Evgeny Yakovlev3ff2f672016-07-18 22:39:52 +03003308 ++bs->write_gen;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003309 }
3310 return ret;
bellard83f64092006-08-01 16:21:11 +00003311}
3312
3313/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08003314 * Length of a allocated file in bytes. Sparse files are counted by actual
3315 * allocated space. Return < 0 if error or unknown.
3316 */
3317int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
3318{
3319 BlockDriver *drv = bs->drv;
3320 if (!drv) {
3321 return -ENOMEDIUM;
3322 }
3323 if (drv->bdrv_get_allocated_file_size) {
3324 return drv->bdrv_get_allocated_file_size(bs);
3325 }
3326 if (bs->file) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003327 return bdrv_get_allocated_file_size(bs->file->bs);
Fam Zheng4a1d5e12011-07-12 19:56:39 +08003328 }
3329 return -ENOTSUP;
3330}
3331
3332/**
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003333 * Return number of sectors on success, -errno on error.
bellard83f64092006-08-01 16:21:11 +00003334 */
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003335int64_t bdrv_nb_sectors(BlockDriverState *bs)
bellard83f64092006-08-01 16:21:11 +00003336{
3337 BlockDriver *drv = bs->drv;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003338
bellard83f64092006-08-01 16:21:11 +00003339 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003340 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01003341
Kevin Wolfb94a2612013-10-29 12:18:58 +01003342 if (drv->has_variable_length) {
3343 int ret = refresh_total_sectors(bs, bs->total_sectors);
3344 if (ret < 0) {
3345 return ret;
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01003346 }
bellard83f64092006-08-01 16:21:11 +00003347 }
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003348 return bs->total_sectors;
3349}
3350
3351/**
3352 * Return length in bytes on success, -errno on error.
3353 * The length is always a multiple of BDRV_SECTOR_SIZE.
3354 */
3355int64_t bdrv_getlength(BlockDriverState *bs)
3356{
3357 int64_t ret = bdrv_nb_sectors(bs);
3358
Fam Zheng4a9c9ea2015-05-15 16:36:05 +08003359 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003360 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00003361}
3362
bellard19cb3732006-08-19 11:45:59 +00003363/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00003364void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00003365{
Markus Armbruster65a9bb22014-06-26 13:23:17 +02003366 int64_t nb_sectors = bdrv_nb_sectors(bs);
3367
3368 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
bellardfc01f7e2003-06-30 10:03:06 +00003369}
bellardcf989512004-02-16 21:56:36 +00003370
Eric Blake54115412016-06-23 16:37:26 -06003371bool bdrv_is_read_only(BlockDriverState *bs)
bellardb3380822004-03-14 21:38:54 +00003372{
3373 return bs->read_only;
3374}
3375
Eric Blake54115412016-06-23 16:37:26 -06003376bool bdrv_is_sg(BlockDriverState *bs)
ths985a03b2007-12-24 16:10:43 +00003377{
3378 return bs->sg;
3379}
3380
Eric Blake54115412016-06-23 16:37:26 -06003381bool bdrv_is_encrypted(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00003382{
Kevin Wolf760e0062015-06-17 14:55:21 +02003383 if (bs->backing && bs->backing->bs->encrypted) {
Eric Blake54115412016-06-23 16:37:26 -06003384 return true;
Kevin Wolf760e0062015-06-17 14:55:21 +02003385 }
bellardea2384d2004-08-01 21:59:26 +00003386 return bs->encrypted;
3387}
3388
Eric Blake54115412016-06-23 16:37:26 -06003389bool bdrv_key_required(BlockDriverState *bs)
aliguoric0f4ce72009-03-05 23:01:01 +00003390{
Kevin Wolf760e0062015-06-17 14:55:21 +02003391 BdrvChild *backing = bs->backing;
aliguoric0f4ce72009-03-05 23:01:01 +00003392
Kevin Wolf760e0062015-06-17 14:55:21 +02003393 if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
Eric Blake54115412016-06-23 16:37:26 -06003394 return true;
Kevin Wolf760e0062015-06-17 14:55:21 +02003395 }
aliguoric0f4ce72009-03-05 23:01:01 +00003396 return (bs->encrypted && !bs->valid_key);
3397}
3398
bellardea2384d2004-08-01 21:59:26 +00003399int bdrv_set_key(BlockDriverState *bs, const char *key)
3400{
3401 int ret;
Kevin Wolf760e0062015-06-17 14:55:21 +02003402 if (bs->backing && bs->backing->bs->encrypted) {
3403 ret = bdrv_set_key(bs->backing->bs, key);
bellardea2384d2004-08-01 21:59:26 +00003404 if (ret < 0)
3405 return ret;
3406 if (!bs->encrypted)
3407 return 0;
3408 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02003409 if (!bs->encrypted) {
3410 return -EINVAL;
3411 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3412 return -ENOMEDIUM;
3413 }
aliguoric0f4ce72009-03-05 23:01:01 +00003414 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00003415 if (ret < 0) {
Eric Blake54115412016-06-23 16:37:26 -06003416 bs->valid_key = false;
aliguoribb5fc202009-03-05 23:01:15 +00003417 } else if (!bs->valid_key) {
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003418 /* call the change callback now, we skipped it on open */
Eric Blake54115412016-06-23 16:37:26 -06003419 bs->valid_key = true;
Kevin Wolf5c8cab42016-02-24 15:13:35 +01003420 bdrv_parent_cb_change_media(bs, true);
aliguoribb5fc202009-03-05 23:01:15 +00003421 }
aliguoric0f4ce72009-03-05 23:01:01 +00003422 return ret;
bellardea2384d2004-08-01 21:59:26 +00003423}
3424
Markus Armbruster4d2855a2015-01-29 10:37:00 +01003425/*
3426 * Provide an encryption key for @bs.
3427 * If @key is non-null:
3428 * If @bs is not encrypted, fail.
3429 * Else if the key is invalid, fail.
3430 * Else set @bs's key to @key, replacing the existing key, if any.
3431 * If @key is null:
3432 * If @bs is encrypted and still lacks a key, fail.
3433 * Else do nothing.
3434 * On failure, store an error object through @errp if non-null.
3435 */
3436void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
3437{
3438 if (key) {
3439 if (!bdrv_is_encrypted(bs)) {
Alberto Garcia81e5f782015-04-08 12:29:19 +03003440 error_setg(errp, "Node '%s' is not encrypted",
3441 bdrv_get_device_or_node_name(bs));
Markus Armbruster4d2855a2015-01-29 10:37:00 +01003442 } else if (bdrv_set_key(bs, key) < 0) {
Markus Armbrusterc6bd8c72015-03-17 11:54:50 +01003443 error_setg(errp, QERR_INVALID_PASSWORD);
Markus Armbruster4d2855a2015-01-29 10:37:00 +01003444 }
3445 } else {
3446 if (bdrv_key_required(bs)) {
Markus Armbrusterb1ca6392015-01-29 10:37:01 +01003447 error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
3448 "'%s' (%s) is encrypted",
Alberto Garcia81e5f782015-04-08 12:29:19 +03003449 bdrv_get_device_or_node_name(bs),
Markus Armbruster4d2855a2015-01-29 10:37:00 +01003450 bdrv_get_encrypted_filename(bs));
3451 }
3452 }
3453}
3454
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02003455const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00003456{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02003457 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00003458}
3459
Stefan Hajnocziada42402014-08-27 12:08:55 +01003460static int qsort_strcmp(const void *a, const void *b)
3461{
Max Reitzceff5bd2016-10-12 22:49:05 +02003462 return strcmp(*(char *const *)a, *(char *const *)b);
Stefan Hajnocziada42402014-08-27 12:08:55 +01003463}
3464
ths5fafdf22007-09-16 21:08:06 +00003465void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00003466 void *opaque)
3467{
3468 BlockDriver *drv;
Jeff Codye855e4f2014-04-28 18:29:54 -04003469 int count = 0;
Stefan Hajnocziada42402014-08-27 12:08:55 +01003470 int i;
Jeff Codye855e4f2014-04-28 18:29:54 -04003471 const char **formats = NULL;
bellardea2384d2004-08-01 21:59:26 +00003472
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01003473 QLIST_FOREACH(drv, &bdrv_drivers, list) {
Jeff Codye855e4f2014-04-28 18:29:54 -04003474 if (drv->format_name) {
3475 bool found = false;
3476 int i = count;
3477 while (formats && i && !found) {
3478 found = !strcmp(formats[--i], drv->format_name);
3479 }
3480
3481 if (!found) {
Markus Armbruster5839e532014-08-19 10:31:08 +02003482 formats = g_renew(const char *, formats, count + 1);
Jeff Codye855e4f2014-04-28 18:29:54 -04003483 formats[count++] = drv->format_name;
Jeff Codye855e4f2014-04-28 18:29:54 -04003484 }
3485 }
bellardea2384d2004-08-01 21:59:26 +00003486 }
Stefan Hajnocziada42402014-08-27 12:08:55 +01003487
Max Reitzeb0df692016-10-12 22:49:06 +02003488 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
3489 const char *format_name = block_driver_modules[i].format_name;
3490
3491 if (format_name) {
3492 bool found = false;
3493 int j = count;
3494
3495 while (formats && j && !found) {
3496 found = !strcmp(formats[--j], format_name);
3497 }
3498
3499 if (!found) {
3500 formats = g_renew(const char *, formats, count + 1);
3501 formats[count++] = format_name;
3502 }
3503 }
3504 }
3505
Stefan Hajnocziada42402014-08-27 12:08:55 +01003506 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
3507
3508 for (i = 0; i < count; i++) {
3509 it(opaque, formats[i]);
3510 }
3511
Jeff Codye855e4f2014-04-28 18:29:54 -04003512 g_free(formats);
bellardea2384d2004-08-01 21:59:26 +00003513}
3514
Benoît Canetdc364f42014-01-23 21:31:32 +01003515/* This function is to find a node in the bs graph */
3516BlockDriverState *bdrv_find_node(const char *node_name)
3517{
3518 BlockDriverState *bs;
3519
3520 assert(node_name);
3521
3522 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3523 if (!strcmp(node_name, bs->node_name)) {
3524 return bs;
3525 }
3526 }
3527 return NULL;
3528}
3529
Benoît Canetc13163f2014-01-23 21:31:34 +01003530/* Put this QMP function here so it can access the static graph_bdrv_states. */
Alberto Garciad5a8ee62015-04-17 14:52:43 +03003531BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
Benoît Canetc13163f2014-01-23 21:31:34 +01003532{
3533 BlockDeviceInfoList *list, *entry;
3534 BlockDriverState *bs;
3535
3536 list = NULL;
3537 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
Kevin Wolfc83f9fb2016-03-03 11:37:48 +01003538 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
Alberto Garciad5a8ee62015-04-17 14:52:43 +03003539 if (!info) {
3540 qapi_free_BlockDeviceInfoList(list);
3541 return NULL;
3542 }
Benoît Canetc13163f2014-01-23 21:31:34 +01003543 entry = g_malloc0(sizeof(*entry));
Alberto Garciad5a8ee62015-04-17 14:52:43 +03003544 entry->value = info;
Benoît Canetc13163f2014-01-23 21:31:34 +01003545 entry->next = list;
3546 list = entry;
3547 }
3548
3549 return list;
3550}
3551
Benoît Canet12d3ba82014-01-23 21:31:35 +01003552BlockDriverState *bdrv_lookup_bs(const char *device,
3553 const char *node_name,
3554 Error **errp)
3555{
Markus Armbruster7f06d472014-10-07 13:59:12 +02003556 BlockBackend *blk;
3557 BlockDriverState *bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01003558
Benoît Canet12d3ba82014-01-23 21:31:35 +01003559 if (device) {
Markus Armbruster7f06d472014-10-07 13:59:12 +02003560 blk = blk_by_name(device);
Benoît Canet12d3ba82014-01-23 21:31:35 +01003561
Markus Armbruster7f06d472014-10-07 13:59:12 +02003562 if (blk) {
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02003563 bs = blk_bs(blk);
3564 if (!bs) {
Max Reitz5433c242015-10-19 17:53:29 +02003565 error_setg(errp, "Device '%s' has no medium", device);
Max Reitz5433c242015-10-19 17:53:29 +02003566 }
3567
Alberto Garcia9f4ed6f2015-10-26 16:46:49 +02003568 return bs;
Benoît Canet12d3ba82014-01-23 21:31:35 +01003569 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01003570 }
3571
Benoît Canetdd67fa52014-02-12 17:15:06 +01003572 if (node_name) {
3573 bs = bdrv_find_node(node_name);
Benoît Canet12d3ba82014-01-23 21:31:35 +01003574
Benoît Canetdd67fa52014-02-12 17:15:06 +01003575 if (bs) {
3576 return bs;
3577 }
Benoît Canet12d3ba82014-01-23 21:31:35 +01003578 }
3579
Benoît Canetdd67fa52014-02-12 17:15:06 +01003580 error_setg(errp, "Cannot find device=%s nor node_name=%s",
3581 device ? device : "",
3582 node_name ? node_name : "");
3583 return NULL;
Benoît Canet12d3ba82014-01-23 21:31:35 +01003584}
3585
Jeff Cody5a6684d2014-06-25 15:40:09 -04003586/* If 'base' is in the same chain as 'top', return true. Otherwise,
3587 * return false. If either argument is NULL, return false. */
3588bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
3589{
3590 while (top && top != base) {
Kevin Wolf760e0062015-06-17 14:55:21 +02003591 top = backing_bs(top);
Jeff Cody5a6684d2014-06-25 15:40:09 -04003592 }
3593
3594 return top != NULL;
3595}
3596
Fam Zheng04df7652014-10-31 11:32:54 +08003597BlockDriverState *bdrv_next_node(BlockDriverState *bs)
3598{
3599 if (!bs) {
3600 return QTAILQ_FIRST(&graph_bdrv_states);
3601 }
3602 return QTAILQ_NEXT(bs, node_list);
3603}
3604
Fam Zheng20a9e772014-10-31 11:32:55 +08003605const char *bdrv_get_node_name(const BlockDriverState *bs)
3606{
3607 return bs->node_name;
3608}
3609
Kevin Wolf1f0c4612016-03-22 18:38:44 +01003610const char *bdrv_get_parent_name(const BlockDriverState *bs)
Kevin Wolf4c265bf2016-02-26 10:22:16 +01003611{
3612 BdrvChild *c;
3613 const char *name;
3614
3615 /* If multiple parents have a name, just pick the first one. */
3616 QLIST_FOREACH(c, &bs->parents, next_parent) {
3617 if (c->role->get_name) {
3618 name = c->role->get_name(c);
3619 if (name && *name) {
3620 return name;
3621 }
3622 }
3623 }
3624
3625 return NULL;
3626}
3627
Markus Armbruster7f06d472014-10-07 13:59:12 +02003628/* TODO check what callers really want: bs->node_name or blk_name() */
Markus Armbrusterbfb197e2014-10-07 13:59:11 +02003629const char *bdrv_get_device_name(const BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00003630{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01003631 return bdrv_get_parent_name(bs) ?: "";
bellardea2384d2004-08-01 21:59:26 +00003632}
3633
Alberto Garcia9b2aa842015-04-08 12:29:18 +03003634/* This can be used to identify nodes that might not have a device
3635 * name associated. Since node and device names live in the same
3636 * namespace, the result is unambiguous. The exception is if both are
3637 * absent, then this returns an empty (non-null) string. */
3638const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
3639{
Kevin Wolf4c265bf2016-02-26 10:22:16 +01003640 return bdrv_get_parent_name(bs) ?: bs->node_name;
Alberto Garcia9b2aa842015-04-08 12:29:18 +03003641}
3642
Markus Armbrusterc8433282012-06-05 16:49:24 +02003643int bdrv_get_flags(BlockDriverState *bs)
3644{
3645 return bs->open_flags;
3646}
3647
Peter Lieven3ac21622013-06-28 12:47:42 +02003648int bdrv_has_zero_init_1(BlockDriverState *bs)
3649{
3650 return 1;
3651}
3652
Kevin Wolff2feebb2010-04-14 17:30:35 +02003653int bdrv_has_zero_init(BlockDriverState *bs)
3654{
3655 assert(bs->drv);
3656
Paolo Bonzini11212d82013-09-04 19:00:27 +02003657 /* If BS is a copy on write image, it is initialized to
3658 the contents of the base image, which may not be zeroes. */
Kevin Wolf760e0062015-06-17 14:55:21 +02003659 if (bs->backing) {
Paolo Bonzini11212d82013-09-04 19:00:27 +02003660 return 0;
3661 }
Kevin Wolf336c1c12010-07-28 11:26:29 +02003662 if (bs->drv->bdrv_has_zero_init) {
3663 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02003664 }
3665
Peter Lieven3ac21622013-06-28 12:47:42 +02003666 /* safe default */
3667 return 0;
Kevin Wolff2feebb2010-04-14 17:30:35 +02003668}
3669
Peter Lieven4ce78692013-10-24 12:06:54 +02003670bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
3671{
3672 BlockDriverInfo bdi;
3673
Kevin Wolf760e0062015-06-17 14:55:21 +02003674 if (bs->backing) {
Peter Lieven4ce78692013-10-24 12:06:54 +02003675 return false;
3676 }
3677
3678 if (bdrv_get_info(bs, &bdi) == 0) {
3679 return bdi.unallocated_blocks_are_zero;
3680 }
3681
3682 return false;
3683}
3684
3685bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
3686{
3687 BlockDriverInfo bdi;
3688
Denis V. Lunev2f0342e2016-07-14 16:33:26 +03003689 if (!(bs->open_flags & BDRV_O_UNMAP)) {
Peter Lieven4ce78692013-10-24 12:06:54 +02003690 return false;
3691 }
3692
3693 if (bdrv_get_info(bs, &bdi) == 0) {
3694 return bdi.can_write_zeroes_with_unmap;
3695 }
3696
3697 return false;
3698}
3699
aliguori045df332009-03-05 23:00:48 +00003700const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3701{
Kevin Wolf760e0062015-06-17 14:55:21 +02003702 if (bs->backing && bs->backing->bs->encrypted)
aliguori045df332009-03-05 23:00:48 +00003703 return bs->backing_file;
3704 else if (bs->encrypted)
3705 return bs->filename;
3706 else
3707 return NULL;
3708}
3709
ths5fafdf22007-09-16 21:08:06 +00003710void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00003711 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00003712{
Kevin Wolf3574c602011-10-26 11:02:11 +02003713 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00003714}
3715
bellardfaea38e2006-08-05 21:31:00 +00003716int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3717{
3718 BlockDriver *drv = bs->drv;
3719 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003720 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00003721 if (!drv->bdrv_get_info)
3722 return -ENOTSUP;
3723 memset(bdi, 0, sizeof(*bdi));
3724 return drv->bdrv_get_info(bs, bdi);
3725}
3726
Max Reitzeae041f2013-10-09 10:46:16 +02003727ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3728{
3729 BlockDriver *drv = bs->drv;
3730 if (drv && drv->bdrv_get_specific_info) {
3731 return drv->bdrv_get_specific_info(bs);
3732 }
3733 return NULL;
3734}
3735
Eric Blakea31939e2015-11-18 01:52:54 -07003736void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003737{
Kevin Wolfbf736fe2013-06-05 15:17:55 +02003738 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003739 return;
3740 }
3741
Kevin Wolfbf736fe2013-06-05 15:17:55 +02003742 bs->drv->bdrv_debug_event(bs, event);
Kevin Wolf41c695c2012-12-06 14:32:58 +01003743}
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003744
Kevin Wolf41c695c2012-12-06 14:32:58 +01003745int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3746 const char *tag)
3747{
3748 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003749 bs = bs->file ? bs->file->bs : NULL;
Kevin Wolf41c695c2012-12-06 14:32:58 +01003750 }
3751
3752 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3753 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3754 }
3755
3756 return -ENOTSUP;
3757}
3758
Fam Zheng4cc70e92013-11-20 10:01:54 +08003759int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
3760{
3761 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003762 bs = bs->file ? bs->file->bs : NULL;
Fam Zheng4cc70e92013-11-20 10:01:54 +08003763 }
3764
3765 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
3766 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
3767 }
3768
3769 return -ENOTSUP;
3770}
3771
Kevin Wolf41c695c2012-12-06 14:32:58 +01003772int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3773{
Max Reitz938789e2014-03-10 23:44:08 +01003774 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003775 bs = bs->file ? bs->file->bs : NULL;
Kevin Wolf41c695c2012-12-06 14:32:58 +01003776 }
3777
3778 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3779 return bs->drv->bdrv_debug_resume(bs, tag);
3780 }
3781
3782 return -ENOTSUP;
3783}
3784
3785bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3786{
3787 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02003788 bs = bs->file ? bs->file->bs : NULL;
Kevin Wolf41c695c2012-12-06 14:32:58 +01003789 }
3790
3791 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3792 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3793 }
3794
3795 return false;
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003796}
3797
Jeff Codyb1b1d782012-10-16 15:49:09 -04003798/* backing_file can either be relative, or absolute, or a protocol. If it is
3799 * relative, it must be relative to the chain. So, passing in bs->filename
3800 * from a BDS as backing_file should not be done, as that may be relative to
3801 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003802BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3803 const char *backing_file)
3804{
Jeff Codyb1b1d782012-10-16 15:49:09 -04003805 char *filename_full = NULL;
3806 char *backing_file_full = NULL;
3807 char *filename_tmp = NULL;
3808 int is_protocol = 0;
3809 BlockDriverState *curr_bs = NULL;
3810 BlockDriverState *retval = NULL;
Jeff Cody418661e2017-01-25 20:08:20 -05003811 Error *local_error = NULL;
Jeff Codyb1b1d782012-10-16 15:49:09 -04003812
3813 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003814 return NULL;
3815 }
3816
Jeff Codyb1b1d782012-10-16 15:49:09 -04003817 filename_full = g_malloc(PATH_MAX);
3818 backing_file_full = g_malloc(PATH_MAX);
3819 filename_tmp = g_malloc(PATH_MAX);
3820
3821 is_protocol = path_has_protocol(backing_file);
3822
Kevin Wolf760e0062015-06-17 14:55:21 +02003823 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
Jeff Codyb1b1d782012-10-16 15:49:09 -04003824
3825 /* If either of the filename paths is actually a protocol, then
3826 * compare unmodified paths; otherwise make paths relative */
3827 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3828 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
Kevin Wolf760e0062015-06-17 14:55:21 +02003829 retval = curr_bs->backing->bs;
Jeff Codyb1b1d782012-10-16 15:49:09 -04003830 break;
3831 }
Jeff Cody418661e2017-01-25 20:08:20 -05003832 /* Also check against the full backing filename for the image */
3833 bdrv_get_full_backing_filename(curr_bs, backing_file_full, PATH_MAX,
3834 &local_error);
3835 if (local_error == NULL) {
3836 if (strcmp(backing_file, backing_file_full) == 0) {
3837 retval = curr_bs->backing->bs;
3838 break;
3839 }
3840 } else {
3841 error_free(local_error);
3842 local_error = NULL;
3843 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003844 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04003845 /* If not an absolute filename path, make it relative to the current
3846 * image's filename path */
3847 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3848 backing_file);
3849
3850 /* We are going to compare absolute pathnames */
3851 if (!realpath(filename_tmp, filename_full)) {
3852 continue;
3853 }
3854
3855 /* We need to make sure the backing filename we are comparing against
3856 * is relative to the current image filename (or absolute) */
3857 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3858 curr_bs->backing_file);
3859
3860 if (!realpath(filename_tmp, backing_file_full)) {
3861 continue;
3862 }
3863
3864 if (strcmp(backing_file_full, filename_full) == 0) {
Kevin Wolf760e0062015-06-17 14:55:21 +02003865 retval = curr_bs->backing->bs;
Jeff Codyb1b1d782012-10-16 15:49:09 -04003866 break;
3867 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003868 }
3869 }
3870
Jeff Codyb1b1d782012-10-16 15:49:09 -04003871 g_free(filename_full);
3872 g_free(backing_file_full);
3873 g_free(filename_tmp);
3874 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003875}
3876
Benoît Canetf198fd12012-08-02 10:22:47 +02003877int bdrv_get_backing_file_depth(BlockDriverState *bs)
3878{
3879 if (!bs->drv) {
3880 return 0;
3881 }
3882
Kevin Wolf760e0062015-06-17 14:55:21 +02003883 if (!bs->backing) {
Benoît Canetf198fd12012-08-02 10:22:47 +02003884 return 0;
3885 }
3886
Kevin Wolf760e0062015-06-17 14:55:21 +02003887 return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
Benoît Canetf198fd12012-08-02 10:22:47 +02003888}
3889
bellardea2384d2004-08-01 21:59:26 +00003890void bdrv_init(void)
3891{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05003892 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00003893}
pbrookce1a14d2006-08-07 02:38:06 +00003894
Markus Armbrustereb852012009-10-27 18:41:44 +01003895void bdrv_init_with_whitelist(void)
3896{
3897 use_bdrv_whitelist = 1;
3898 bdrv_init();
3899}
3900
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003901void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06003902{
Fam Zheng0d1c5c92016-05-11 10:45:33 +08003903 BdrvChild *child;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003904 Error *local_err = NULL;
3905 int ret;
3906
Kevin Wolf3456a8d2014-03-11 10:58:39 +01003907 if (!bs->drv) {
3908 return;
Anthony Liguori0f154232011-11-14 15:09:45 -06003909 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01003910
Kevin Wolf04c01a52016-01-13 15:56:06 +01003911 if (!(bs->open_flags & BDRV_O_INACTIVE)) {
Alexey Kardashevskiy7ea2d262014-10-09 13:50:46 +11003912 return;
3913 }
Alexey Kardashevskiy7ea2d262014-10-09 13:50:46 +11003914
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03003915 QLIST_FOREACH(child, &bs->children, next) {
3916 bdrv_invalidate_cache(child->bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08003917 if (local_err) {
Fam Zheng0d1c5c92016-05-11 10:45:33 +08003918 error_propagate(errp, local_err);
3919 return;
3920 }
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003921 }
Fam Zheng0d1c5c92016-05-11 10:45:33 +08003922
Vladimir Sementsov-Ogievskiy16e977d2017-01-31 14:23:08 +03003923 bs->open_flags &= ~BDRV_O_INACTIVE;
3924 if (bs->drv->bdrv_invalidate_cache) {
3925 bs->drv->bdrv_invalidate_cache(bs, &local_err);
Fam Zheng0d1c5c92016-05-11 10:45:33 +08003926 if (local_err) {
3927 bs->open_flags |= BDRV_O_INACTIVE;
3928 error_propagate(errp, local_err);
3929 return;
3930 }
Kevin Wolf3456a8d2014-03-11 10:58:39 +01003931 }
3932
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003933 ret = refresh_total_sectors(bs, bs->total_sectors);
3934 if (ret < 0) {
Kevin Wolf04c01a52016-01-13 15:56:06 +01003935 bs->open_flags |= BDRV_O_INACTIVE;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003936 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3937 return;
3938 }
Anthony Liguori0f154232011-11-14 15:09:45 -06003939}
3940
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003941void bdrv_invalidate_cache_all(Error **errp)
Anthony Liguori0f154232011-11-14 15:09:45 -06003942{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01003943 BlockDriverState *bs;
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003944 Error *local_err = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02003945 BdrvNextIterator it;
Anthony Liguori0f154232011-11-14 15:09:45 -06003946
Kevin Wolf88be7b42016-05-20 18:49:07 +02003947 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02003948 AioContext *aio_context = bdrv_get_aio_context(bs);
3949
3950 aio_context_acquire(aio_context);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003951 bdrv_invalidate_cache(bs, &local_err);
Stefan Hajnoczied78cda2014-05-08 16:34:35 +02003952 aio_context_release(aio_context);
Kevin Wolf5a8a30d2014-03-12 15:59:16 +01003953 if (local_err) {
3954 error_propagate(errp, local_err);
3955 return;
3956 }
Anthony Liguori0f154232011-11-14 15:09:45 -06003957 }
3958}
3959
Fam Zhengaad0b7a2016-05-11 10:45:35 +08003960static int bdrv_inactivate_recurse(BlockDriverState *bs,
3961 bool setting_flag)
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01003962{
Fam Zhengaad0b7a2016-05-11 10:45:35 +08003963 BdrvChild *child;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01003964 int ret;
3965
Fam Zhengaad0b7a2016-05-11 10:45:35 +08003966 if (!setting_flag && bs->drv->bdrv_inactivate) {
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01003967 ret = bs->drv->bdrv_inactivate(bs);
3968 if (ret < 0) {
3969 return ret;
3970 }
3971 }
3972
Fam Zhengaad0b7a2016-05-11 10:45:35 +08003973 QLIST_FOREACH(child, &bs->children, next) {
3974 ret = bdrv_inactivate_recurse(child->bs, setting_flag);
3975 if (ret < 0) {
3976 return ret;
3977 }
3978 }
3979
3980 if (setting_flag) {
3981 bs->open_flags |= BDRV_O_INACTIVE;
3982 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01003983 return 0;
3984}
3985
3986int bdrv_inactivate_all(void)
3987{
Max Reitz79720af2016-03-16 19:54:44 +01003988 BlockDriverState *bs = NULL;
Kevin Wolf88be7b42016-05-20 18:49:07 +02003989 BdrvNextIterator it;
Fam Zhengaad0b7a2016-05-11 10:45:35 +08003990 int ret = 0;
3991 int pass;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01003992
Kevin Wolf88be7b42016-05-20 18:49:07 +02003993 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Fam Zhengaad0b7a2016-05-11 10:45:35 +08003994 aio_context_acquire(bdrv_get_aio_context(bs));
3995 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01003996
Fam Zhengaad0b7a2016-05-11 10:45:35 +08003997 /* We do two passes of inactivation. The first pass calls to drivers'
3998 * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
3999 * the second pass sets the BDRV_O_INACTIVE flag so that no further write
4000 * is allowed. */
4001 for (pass = 0; pass < 2; pass++) {
Kevin Wolf88be7b42016-05-20 18:49:07 +02004002 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004003 ret = bdrv_inactivate_recurse(bs, pass);
4004 if (ret < 0) {
4005 goto out;
4006 }
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004007 }
4008 }
4009
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004010out:
Kevin Wolf88be7b42016-05-20 18:49:07 +02004011 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Fam Zhengaad0b7a2016-05-11 10:45:35 +08004012 aio_context_release(bdrv_get_aio_context(bs));
4013 }
4014
4015 return ret;
Kevin Wolf76b1c7f2015-12-22 14:07:08 +01004016}
4017
Kevin Wolff9f05dc2011-07-15 13:50:26 +02004018/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00004019/* removable device support */
4020
4021/**
4022 * Return TRUE if the media is present
4023 */
Max Reitze031f752015-10-19 17:53:11 +02004024bool bdrv_is_inserted(BlockDriverState *bs)
bellard19cb3732006-08-19 11:45:59 +00004025{
4026 BlockDriver *drv = bs->drv;
Max Reitz28d7a782015-10-19 17:53:13 +02004027 BdrvChild *child;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02004028
Max Reitze031f752015-10-19 17:53:11 +02004029 if (!drv) {
4030 return false;
4031 }
Max Reitz28d7a782015-10-19 17:53:13 +02004032 if (drv->bdrv_is_inserted) {
4033 return drv->bdrv_is_inserted(bs);
Max Reitze031f752015-10-19 17:53:11 +02004034 }
Max Reitz28d7a782015-10-19 17:53:13 +02004035 QLIST_FOREACH(child, &bs->children, next) {
4036 if (!bdrv_is_inserted(child->bs)) {
4037 return false;
4038 }
4039 }
4040 return true;
bellard19cb3732006-08-19 11:45:59 +00004041}
4042
4043/**
Markus Armbruster8e49ca42011-08-03 15:08:08 +02004044 * Return whether the media changed since the last call to this
4045 * function, or -ENOTSUP if we don't know. Most drivers don't know.
bellard19cb3732006-08-19 11:45:59 +00004046 */
4047int bdrv_media_changed(BlockDriverState *bs)
4048{
4049 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00004050
Markus Armbruster8e49ca42011-08-03 15:08:08 +02004051 if (drv && drv->bdrv_media_changed) {
4052 return drv->bdrv_media_changed(bs);
4053 }
4054 return -ENOTSUP;
bellard19cb3732006-08-19 11:45:59 +00004055}
4056
4057/**
4058 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4059 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02004060void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00004061{
4062 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00004063
Markus Armbruster822e1cd2011-07-20 18:23:42 +02004064 if (drv && drv->bdrv_eject) {
4065 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00004066 }
bellard19cb3732006-08-19 11:45:59 +00004067}
4068
bellard19cb3732006-08-19 11:45:59 +00004069/**
4070 * Lock or unlock the media (if it is locked, the user won't be able
4071 * to eject it manually).
4072 */
Markus Armbruster025e8492011-09-06 18:58:47 +02004073void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00004074{
4075 BlockDriver *drv = bs->drv;
4076
Markus Armbruster025e8492011-09-06 18:58:47 +02004077 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01004078
Markus Armbruster025e8492011-09-06 18:58:47 +02004079 if (drv && drv->bdrv_lock_medium) {
4080 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00004081 }
4082}
ths985a03b2007-12-24 16:10:43 +00004083
Fam Zheng9fcb0252013-08-23 09:14:46 +08004084/* Get a reference to bs */
4085void bdrv_ref(BlockDriverState *bs)
4086{
4087 bs->refcnt++;
4088}
4089
4090/* Release a previously grabbed reference to bs.
4091 * If after releasing, reference count is zero, the BlockDriverState is
4092 * deleted. */
4093void bdrv_unref(BlockDriverState *bs)
4094{
Jeff Cody9a4d5ca2014-07-23 17:22:57 -04004095 if (!bs) {
4096 return;
4097 }
Fam Zheng9fcb0252013-08-23 09:14:46 +08004098 assert(bs->refcnt > 0);
4099 if (--bs->refcnt == 0) {
4100 bdrv_delete(bs);
4101 }
4102}
4103
Fam Zhengfbe40ff2014-05-23 21:29:42 +08004104struct BdrvOpBlocker {
4105 Error *reason;
4106 QLIST_ENTRY(BdrvOpBlocker) list;
4107};
4108
4109bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
4110{
4111 BdrvOpBlocker *blocker;
4112 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4113 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
4114 blocker = QLIST_FIRST(&bs->op_blockers[op]);
4115 if (errp) {
Markus Armbrustere43bfd92015-12-18 16:35:15 +01004116 *errp = error_copy(blocker->reason);
4117 error_prepend(errp, "Node '%s' is busy: ",
4118 bdrv_get_device_or_node_name(bs));
Fam Zhengfbe40ff2014-05-23 21:29:42 +08004119 }
4120 return true;
4121 }
4122 return false;
4123}
4124
4125void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
4126{
4127 BdrvOpBlocker *blocker;
4128 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4129
Markus Armbruster5839e532014-08-19 10:31:08 +02004130 blocker = g_new0(BdrvOpBlocker, 1);
Fam Zhengfbe40ff2014-05-23 21:29:42 +08004131 blocker->reason = reason;
4132 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
4133}
4134
4135void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
4136{
4137 BdrvOpBlocker *blocker, *next;
4138 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4139 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
4140 if (blocker->reason == reason) {
4141 QLIST_REMOVE(blocker, list);
4142 g_free(blocker);
4143 }
4144 }
4145}
4146
4147void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
4148{
4149 int i;
4150 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4151 bdrv_op_block(bs, i, reason);
4152 }
4153}
4154
4155void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
4156{
4157 int i;
4158 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4159 bdrv_op_unblock(bs, i, reason);
4160 }
4161}
4162
4163bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
4164{
4165 int i;
4166
4167 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4168 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
4169 return false;
4170 }
4171 }
4172 return true;
4173}
4174
Luiz Capitulinod92ada22012-11-30 10:52:09 -02004175void bdrv_img_create(const char *filename, const char *fmt,
4176 const char *base_filename, const char *base_fmt,
Fam Zheng92172832017-04-21 20:27:01 +08004177 char *options, uint64_t img_size, int flags, bool quiet,
4178 Error **errp)
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004179{
Chunyan Liu83d05212014-06-05 17:20:51 +08004180 QemuOptsList *create_opts = NULL;
4181 QemuOpts *opts = NULL;
4182 const char *backing_fmt, *backing_file;
4183 int64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004184 BlockDriver *drv, *proto_drv;
Max Reitzcc84d902013-09-06 17:14:26 +02004185 Error *local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004186 int ret = 0;
4187
4188 /* Find driver and parse its options */
4189 drv = bdrv_find_format(fmt);
4190 if (!drv) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004191 error_setg(errp, "Unknown file format '%s'", fmt);
Luiz Capitulinod92ada22012-11-30 10:52:09 -02004192 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004193 }
4194
Max Reitzb65a5e12015-02-05 13:58:12 -05004195 proto_drv = bdrv_find_protocol(filename, true, errp);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004196 if (!proto_drv) {
Luiz Capitulinod92ada22012-11-30 10:52:09 -02004197 return;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004198 }
4199
Max Reitzc6149722014-12-02 18:32:45 +01004200 if (!drv->create_opts) {
4201 error_setg(errp, "Format driver '%s' does not support image creation",
4202 drv->format_name);
4203 return;
4204 }
4205
4206 if (!proto_drv->create_opts) {
4207 error_setg(errp, "Protocol driver '%s' does not support image creation",
4208 proto_drv->format_name);
4209 return;
4210 }
4211
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004212 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4213 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004214
4215 /* Create parameter list with default values */
Chunyan Liu83d05212014-06-05 17:20:51 +08004216 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
Markus Armbruster39101f22015-02-12 16:46:36 +01004217 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004218
4219 /* Parse -o options */
4220 if (options) {
Markus Armbrusterdc523cd342015-02-12 18:37:11 +01004221 qemu_opts_do_parse(opts, options, NULL, &local_err);
4222 if (local_err) {
4223 error_report_err(local_err);
4224 local_err = NULL;
Chunyan Liu83d05212014-06-05 17:20:51 +08004225 error_setg(errp, "Invalid options for file format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004226 goto out;
4227 }
4228 }
4229
4230 if (base_filename) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01004231 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
Markus Armbruster6be41942015-02-12 17:49:02 +01004232 if (local_err) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004233 error_setg(errp, "Backing file not supported for file format '%s'",
4234 fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004235 goto out;
4236 }
4237 }
4238
4239 if (base_fmt) {
Markus Armbrusterf43e47d2015-02-12 17:52:20 +01004240 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
Markus Armbruster6be41942015-02-12 17:49:02 +01004241 if (local_err) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004242 error_setg(errp, "Backing file format not supported for file "
4243 "format '%s'", fmt);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004244 goto out;
4245 }
4246 }
4247
Chunyan Liu83d05212014-06-05 17:20:51 +08004248 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4249 if (backing_file) {
4250 if (!strcmp(filename, backing_file)) {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004251 error_setg(errp, "Error: Trying to create an image with the "
4252 "same filename as the backing file");
Jes Sorensen792da932010-12-16 13:52:17 +01004253 goto out;
4254 }
4255 }
4256
Chunyan Liu83d05212014-06-05 17:20:51 +08004257 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004258
4259 // The size for the image must always be specified, with one exception:
4260 // If we are using a backing file, we can obtain the size from there
Chunyan Liu83d05212014-06-05 17:20:51 +08004261 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4262 if (size == -1) {
4263 if (backing_file) {
Max Reitz66f6b812013-12-03 14:57:52 +01004264 BlockDriverState *bs;
Max Reitz29168012014-11-26 17:20:27 +01004265 char *full_backing = g_new0(char, PATH_MAX);
Markus Armbruster52bf1e72014-06-26 13:23:25 +02004266 int64_t size;
Paolo Bonzini63090da2012-04-12 14:01:03 +02004267 int back_flags;
Max Reitze6641712015-08-26 19:47:48 +02004268 QDict *backing_options = NULL;
Paolo Bonzini63090da2012-04-12 14:01:03 +02004269
Max Reitz29168012014-11-26 17:20:27 +01004270 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
4271 full_backing, PATH_MAX,
4272 &local_err);
4273 if (local_err) {
4274 g_free(full_backing);
4275 goto out;
4276 }
4277
Paolo Bonzini63090da2012-04-12 14:01:03 +02004278 /* backing files always opened read-only */
Kevin Wolf61de4c62016-03-18 17:46:45 +01004279 back_flags = flags;
Kevin Wolfbfd18d12016-03-04 14:28:01 +01004280 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004281
Max Reitze6641712015-08-26 19:47:48 +02004282 if (backing_fmt) {
4283 backing_options = qdict_new();
4284 qdict_put(backing_options, "driver",
4285 qstring_from_str(backing_fmt));
4286 }
4287
Max Reitz5b363932016-05-17 16:41:31 +02004288 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
4289 &local_err);
Max Reitz29168012014-11-26 17:20:27 +01004290 g_free(full_backing);
Max Reitz5b363932016-05-17 16:41:31 +02004291 if (!bs) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004292 goto out;
4293 }
Markus Armbruster52bf1e72014-06-26 13:23:25 +02004294 size = bdrv_getlength(bs);
4295 if (size < 0) {
4296 error_setg_errno(errp, -size, "Could not get size of '%s'",
4297 backing_file);
4298 bdrv_unref(bs);
4299 goto out;
4300 }
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004301
Markus Armbruster39101f22015-02-12 16:46:36 +01004302 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
Max Reitz66f6b812013-12-03 14:57:52 +01004303
4304 bdrv_unref(bs);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004305 } else {
Luiz Capitulino71c79812012-11-30 10:52:04 -02004306 error_setg(errp, "Image creation needs a size parameter");
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004307 goto out;
4308 }
4309 }
4310
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01004311 if (!quiet) {
Kővágó, Zoltánfe646692015-07-07 16:42:10 +02004312 printf("Formatting '%s', fmt=%s ", filename, fmt);
Fam Zheng43c5d8f2014-12-09 15:38:04 +08004313 qemu_opts_print(opts, " ");
Miroslav Rezaninaf382d432013-02-13 09:09:40 +01004314 puts("");
4315 }
Chunyan Liu83d05212014-06-05 17:20:51 +08004316
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004317 ret = bdrv_create(drv, filename, opts, &local_err);
Chunyan Liu83d05212014-06-05 17:20:51 +08004318
Max Reitzcc84d902013-09-06 17:14:26 +02004319 if (ret == -EFBIG) {
4320 /* This is generally a better message than whatever the driver would
4321 * deliver (especially because of the cluster_size_hint), since that
4322 * is most probably not much different from "image too large". */
4323 const char *cluster_size_hint = "";
Chunyan Liu83d05212014-06-05 17:20:51 +08004324 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
Max Reitzcc84d902013-09-06 17:14:26 +02004325 cluster_size_hint = " (try using a larger cluster size)";
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004326 }
Max Reitzcc84d902013-09-06 17:14:26 +02004327 error_setg(errp, "The image size is too large for file format '%s'"
4328 "%s", fmt, cluster_size_hint);
4329 error_free(local_err);
4330 local_err = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004331 }
4332
4333out:
Chunyan Liu83d05212014-06-05 17:20:51 +08004334 qemu_opts_del(opts);
4335 qemu_opts_free(create_opts);
Eduardo Habkost621ff942016-06-13 18:57:56 -03004336 error_propagate(errp, local_err);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004337}
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01004338
4339AioContext *bdrv_get_aio_context(BlockDriverState *bs)
4340{
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004341 return bs->aio_context;
4342}
4343
Fam Zheng052a7572017-04-10 20:09:25 +08004344void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
4345{
4346 aio_co_enter(bdrv_get_aio_context(bs), co);
4347}
4348
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004349static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
4350{
4351 QLIST_REMOVE(ban, list);
4352 g_free(ban);
4353}
4354
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004355void bdrv_detach_aio_context(BlockDriverState *bs)
4356{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004357 BdrvAioNotifier *baf, *baf_tmp;
Max Reitzb97511c2016-05-17 13:38:04 +02004358 BdrvChild *child;
Max Reitz33384422014-06-20 21:57:33 +02004359
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004360 if (!bs->drv) {
4361 return;
4362 }
4363
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004364 assert(!bs->walking_aio_notifiers);
4365 bs->walking_aio_notifiers = true;
4366 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
4367 if (baf->deleted) {
4368 bdrv_do_remove_aio_context_notifier(baf);
4369 } else {
4370 baf->detach_aio_context(baf->opaque);
4371 }
Max Reitz33384422014-06-20 21:57:33 +02004372 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004373 /* Never mind iterating again to check for ->deleted. bdrv_close() will
4374 * remove remaining aio notifiers if we aren't called again.
4375 */
4376 bs->walking_aio_notifiers = false;
Max Reitz33384422014-06-20 21:57:33 +02004377
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004378 if (bs->drv->bdrv_detach_aio_context) {
4379 bs->drv->bdrv_detach_aio_context(bs);
4380 }
Max Reitzb97511c2016-05-17 13:38:04 +02004381 QLIST_FOREACH(child, &bs->children, next) {
4382 bdrv_detach_aio_context(child->bs);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004383 }
4384
4385 bs->aio_context = NULL;
4386}
4387
4388void bdrv_attach_aio_context(BlockDriverState *bs,
4389 AioContext *new_context)
4390{
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004391 BdrvAioNotifier *ban, *ban_tmp;
Max Reitzb97511c2016-05-17 13:38:04 +02004392 BdrvChild *child;
Max Reitz33384422014-06-20 21:57:33 +02004393
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004394 if (!bs->drv) {
4395 return;
4396 }
4397
4398 bs->aio_context = new_context;
4399
Max Reitzb97511c2016-05-17 13:38:04 +02004400 QLIST_FOREACH(child, &bs->children, next) {
4401 bdrv_attach_aio_context(child->bs, new_context);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004402 }
4403 if (bs->drv->bdrv_attach_aio_context) {
4404 bs->drv->bdrv_attach_aio_context(bs, new_context);
4405 }
Max Reitz33384422014-06-20 21:57:33 +02004406
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004407 assert(!bs->walking_aio_notifiers);
4408 bs->walking_aio_notifiers = true;
4409 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
4410 if (ban->deleted) {
4411 bdrv_do_remove_aio_context_notifier(ban);
4412 } else {
4413 ban->attached_aio_context(new_context, ban->opaque);
4414 }
Max Reitz33384422014-06-20 21:57:33 +02004415 }
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004416 bs->walking_aio_notifiers = false;
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004417}
4418
4419void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
4420{
Fam Zhengaabf5912017-04-05 14:44:24 +08004421 AioContext *ctx = bdrv_get_aio_context(bs);
Paolo Bonzinic2b64282017-03-14 12:11:57 +01004422
Fam Zhengaabf5912017-04-05 14:44:24 +08004423 aio_disable_external(ctx);
4424 bdrv_parent_drained_begin(bs);
Fam Zheng53ec73e2015-05-29 18:53:14 +08004425 bdrv_drain(bs); /* ensure there are no in-flight requests */
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004426
Paolo Bonzinic2b64282017-03-14 12:11:57 +01004427 while (aio_poll(ctx, false)) {
4428 /* wait for all bottom halves to execute */
4429 }
4430
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004431 bdrv_detach_aio_context(bs);
4432
4433 /* This function executes in the old AioContext so acquire the new one in
4434 * case it runs in a different thread.
4435 */
4436 aio_context_acquire(new_context);
4437 bdrv_attach_aio_context(bs, new_context);
Fam Zhengaabf5912017-04-05 14:44:24 +08004438 bdrv_parent_drained_end(bs);
4439 aio_enable_external(ctx);
Stefan Hajnoczidcd04222014-05-08 16:34:37 +02004440 aio_context_release(new_context);
Stefan Hajnoczi85d126f2013-03-07 13:41:48 +01004441}
Stefan Hajnoczid616b222013-06-24 17:13:10 +02004442
Max Reitz33384422014-06-20 21:57:33 +02004443void bdrv_add_aio_context_notifier(BlockDriverState *bs,
4444 void (*attached_aio_context)(AioContext *new_context, void *opaque),
4445 void (*detach_aio_context)(void *opaque), void *opaque)
4446{
4447 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
4448 *ban = (BdrvAioNotifier){
4449 .attached_aio_context = attached_aio_context,
4450 .detach_aio_context = detach_aio_context,
4451 .opaque = opaque
4452 };
4453
4454 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
4455}
4456
4457void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
4458 void (*attached_aio_context)(AioContext *,
4459 void *),
4460 void (*detach_aio_context)(void *),
4461 void *opaque)
4462{
4463 BdrvAioNotifier *ban, *ban_next;
4464
4465 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4466 if (ban->attached_aio_context == attached_aio_context &&
4467 ban->detach_aio_context == detach_aio_context &&
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004468 ban->opaque == opaque &&
4469 ban->deleted == false)
Max Reitz33384422014-06-20 21:57:33 +02004470 {
Stefan Hajnoczie8a095d2016-06-16 17:56:26 +01004471 if (bs->walking_aio_notifiers) {
4472 ban->deleted = true;
4473 } else {
4474 bdrv_do_remove_aio_context_notifier(ban);
4475 }
Max Reitz33384422014-06-20 21:57:33 +02004476 return;
4477 }
4478 }
4479
4480 abort();
4481}
4482
Max Reitz77485432014-10-27 11:12:50 +01004483int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
Max Reitz8b139762015-07-27 17:51:32 +02004484 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
Max Reitz6f176b42013-09-03 10:09:50 +02004485{
Chunyan Liuc282e1f2014-06-05 17:21:11 +08004486 if (!bs->drv->bdrv_amend_options) {
Max Reitz6f176b42013-09-03 10:09:50 +02004487 return -ENOTSUP;
4488 }
Max Reitz8b139762015-07-27 17:51:32 +02004489 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
Max Reitz6f176b42013-09-03 10:09:50 +02004490}
Benoît Canetf6186f42013-10-02 14:33:48 +02004491
Benoît Canetb5042a32014-03-03 19:11:34 +01004492/* This function will be called by the bdrv_recurse_is_first_non_filter method
4493 * of block filter and by bdrv_is_first_non_filter.
4494 * It is used to test if the given bs is the candidate or recurse more in the
4495 * node graph.
Benoît Canet212a5a82014-01-23 21:31:36 +01004496 */
Benoît Canet212a5a82014-01-23 21:31:36 +01004497bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
4498 BlockDriverState *candidate)
Benoît Canetf6186f42013-10-02 14:33:48 +02004499{
Benoît Canetb5042a32014-03-03 19:11:34 +01004500 /* return false if basic checks fails */
4501 if (!bs || !bs->drv) {
4502 return false;
4503 }
4504
4505 /* the code reached a non block filter driver -> check if the bs is
4506 * the same as the candidate. It's the recursion termination condition.
4507 */
4508 if (!bs->drv->is_filter) {
4509 return bs == candidate;
4510 }
4511 /* Down this path the driver is a block filter driver */
4512
4513 /* If the block filter recursion method is defined use it to recurse down
4514 * the node graph.
4515 */
4516 if (bs->drv->bdrv_recurse_is_first_non_filter) {
Benoît Canet212a5a82014-01-23 21:31:36 +01004517 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
4518 }
4519
Benoît Canetb5042a32014-03-03 19:11:34 +01004520 /* the driver is a block filter but don't allow to recurse -> return false
4521 */
4522 return false;
Benoît Canet212a5a82014-01-23 21:31:36 +01004523}
4524
4525/* This function checks if the candidate is the first non filter bs down it's
4526 * bs chain. Since we don't have pointers to parents it explore all bs chains
4527 * from the top. Some filters can choose not to pass down the recursion.
4528 */
4529bool bdrv_is_first_non_filter(BlockDriverState *candidate)
4530{
Kevin Wolf7c8eece2016-03-22 18:58:50 +01004531 BlockDriverState *bs;
Kevin Wolf88be7b42016-05-20 18:49:07 +02004532 BdrvNextIterator it;
Benoît Canet212a5a82014-01-23 21:31:36 +01004533
4534 /* walk down the bs forest recursively */
Kevin Wolf88be7b42016-05-20 18:49:07 +02004535 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
Benoît Canet212a5a82014-01-23 21:31:36 +01004536 bool perm;
4537
Benoît Canetb5042a32014-03-03 19:11:34 +01004538 /* try to recurse in this top level bs */
Kevin Wolfe6dc8a12014-02-04 11:45:31 +01004539 perm = bdrv_recurse_is_first_non_filter(bs, candidate);
Benoît Canet212a5a82014-01-23 21:31:36 +01004540
4541 /* candidate is the first non filter */
4542 if (perm) {
4543 return true;
4544 }
4545 }
4546
4547 return false;
Benoît Canetf6186f42013-10-02 14:33:48 +02004548}
Benoît Canet09158f02014-06-27 18:25:25 +02004549
Wen Congyange12f3782015-07-17 10:12:22 +08004550BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
4551 const char *node_name, Error **errp)
Benoît Canet09158f02014-06-27 18:25:25 +02004552{
4553 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004554 AioContext *aio_context;
4555
Benoît Canet09158f02014-06-27 18:25:25 +02004556 if (!to_replace_bs) {
4557 error_setg(errp, "Node name '%s' not found", node_name);
4558 return NULL;
4559 }
4560
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004561 aio_context = bdrv_get_aio_context(to_replace_bs);
4562 aio_context_acquire(aio_context);
4563
Benoît Canet09158f02014-06-27 18:25:25 +02004564 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004565 to_replace_bs = NULL;
4566 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02004567 }
4568
4569 /* We don't want arbitrary node of the BDS chain to be replaced only the top
4570 * most non filter in order to prevent data corruption.
4571 * Another benefit is that this tests exclude backing files which are
4572 * blocked by the backing blockers.
4573 */
Wen Congyange12f3782015-07-17 10:12:22 +08004574 if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
Benoît Canet09158f02014-06-27 18:25:25 +02004575 error_setg(errp, "Only top most non filter can be replaced");
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004576 to_replace_bs = NULL;
4577 goto out;
Benoît Canet09158f02014-06-27 18:25:25 +02004578 }
4579
Stefan Hajnoczi5a7e7a02014-10-21 12:03:58 +01004580out:
4581 aio_context_release(aio_context);
Benoît Canet09158f02014-06-27 18:25:25 +02004582 return to_replace_bs;
4583}
Ming Lei448ad912014-07-04 18:04:33 +08004584
Max Reitz91af7012014-07-18 20:24:56 +02004585static bool append_open_options(QDict *d, BlockDriverState *bs)
4586{
4587 const QDictEntry *entry;
Kevin Wolf9e700c12015-04-24 15:20:28 +02004588 QemuOptDesc *desc;
Kevin Wolf260fecf2015-04-27 13:46:22 +02004589 BdrvChild *child;
Max Reitz91af7012014-07-18 20:24:56 +02004590 bool found_any = false;
Kevin Wolf260fecf2015-04-27 13:46:22 +02004591 const char *p;
Max Reitz91af7012014-07-18 20:24:56 +02004592
4593 for (entry = qdict_first(bs->options); entry;
4594 entry = qdict_next(bs->options, entry))
4595 {
Kevin Wolf260fecf2015-04-27 13:46:22 +02004596 /* Exclude options for children */
4597 QLIST_FOREACH(child, &bs->children, next) {
4598 if (strstart(qdict_entry_key(entry), child->name, &p)
4599 && (!*p || *p == '.'))
4600 {
4601 break;
4602 }
4603 }
4604 if (child) {
Kevin Wolf9e700c12015-04-24 15:20:28 +02004605 continue;
Max Reitz91af7012014-07-18 20:24:56 +02004606 }
Kevin Wolf9e700c12015-04-24 15:20:28 +02004607
4608 /* And exclude all non-driver-specific options */
4609 for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
4610 if (!strcmp(qdict_entry_key(entry), desc->name)) {
4611 break;
4612 }
4613 }
4614 if (desc->name) {
4615 continue;
4616 }
4617
4618 qobject_incref(qdict_entry_value(entry));
4619 qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
4620 found_any = true;
Max Reitz91af7012014-07-18 20:24:56 +02004621 }
4622
4623 return found_any;
4624}
4625
4626/* Updates the following BDS fields:
4627 * - exact_filename: A filename which may be used for opening a block device
4628 * which (mostly) equals the given BDS (even without any
4629 * other options; so reading and writing must return the same
4630 * results, but caching etc. may be different)
4631 * - full_open_options: Options which, when given when opening a block device
4632 * (without a filename), result in a BDS (mostly)
4633 * equalling the given one
4634 * - filename: If exact_filename is set, it is copied here. Otherwise,
4635 * full_open_options is converted to a JSON object, prefixed with
4636 * "json:" (for use through the JSON pseudo protocol) and put here.
4637 */
4638void bdrv_refresh_filename(BlockDriverState *bs)
4639{
4640 BlockDriver *drv = bs->drv;
4641 QDict *opts;
4642
4643 if (!drv) {
4644 return;
4645 }
4646
4647 /* This BDS's file name will most probably depend on its file's name, so
4648 * refresh that first */
4649 if (bs->file) {
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004650 bdrv_refresh_filename(bs->file->bs);
Max Reitz91af7012014-07-18 20:24:56 +02004651 }
4652
4653 if (drv->bdrv_refresh_filename) {
4654 /* Obsolete information is of no use here, so drop the old file name
4655 * information before refreshing it */
4656 bs->exact_filename[0] = '\0';
4657 if (bs->full_open_options) {
4658 QDECREF(bs->full_open_options);
4659 bs->full_open_options = NULL;
4660 }
4661
Kevin Wolf4cdd01d2015-04-27 13:50:54 +02004662 opts = qdict_new();
4663 append_open_options(opts, bs);
4664 drv->bdrv_refresh_filename(bs, opts);
4665 QDECREF(opts);
Max Reitz91af7012014-07-18 20:24:56 +02004666 } else if (bs->file) {
4667 /* Try to reconstruct valid information from the underlying file */
4668 bool has_open_options;
4669
4670 bs->exact_filename[0] = '\0';
4671 if (bs->full_open_options) {
4672 QDECREF(bs->full_open_options);
4673 bs->full_open_options = NULL;
4674 }
4675
4676 opts = qdict_new();
4677 has_open_options = append_open_options(opts, bs);
4678
4679 /* If no specific options have been given for this BDS, the filename of
4680 * the underlying file should suffice for this one as well */
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004681 if (bs->file->bs->exact_filename[0] && !has_open_options) {
4682 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
Max Reitz91af7012014-07-18 20:24:56 +02004683 }
4684 /* Reconstructing the full options QDict is simple for most format block
4685 * drivers, as long as the full options are known for the underlying
4686 * file BDS. The full options QDict of that file BDS should somehow
4687 * contain a representation of the filename, therefore the following
4688 * suffices without querying the (exact_)filename of this BDS. */
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004689 if (bs->file->bs->full_open_options) {
Max Reitz91af7012014-07-18 20:24:56 +02004690 qdict_put_obj(opts, "driver",
4691 QOBJECT(qstring_from_str(drv->format_name)));
Kevin Wolf9a4f4c32015-06-16 14:19:22 +02004692 QINCREF(bs->file->bs->full_open_options);
4693 qdict_put_obj(opts, "file",
4694 QOBJECT(bs->file->bs->full_open_options));
Max Reitz91af7012014-07-18 20:24:56 +02004695
4696 bs->full_open_options = opts;
4697 } else {
4698 QDECREF(opts);
4699 }
4700 } else if (!bs->full_open_options && qdict_size(bs->options)) {
4701 /* There is no underlying file BDS (at least referenced by BDS.file),
4702 * so the full options QDict should be equal to the options given
4703 * specifically for this block device when it was opened (plus the
4704 * driver specification).
4705 * Because those options don't change, there is no need to update
4706 * full_open_options when it's already set. */
4707
4708 opts = qdict_new();
4709 append_open_options(opts, bs);
4710 qdict_put_obj(opts, "driver",
4711 QOBJECT(qstring_from_str(drv->format_name)));
4712
4713 if (bs->exact_filename[0]) {
4714 /* This may not work for all block protocol drivers (some may
4715 * require this filename to be parsed), but we have to find some
4716 * default solution here, so just include it. If some block driver
4717 * does not support pure options without any filename at all or
4718 * needs some special format of the options QDict, it needs to
4719 * implement the driver-specific bdrv_refresh_filename() function.
4720 */
4721 qdict_put_obj(opts, "filename",
4722 QOBJECT(qstring_from_str(bs->exact_filename)));
4723 }
4724
4725 bs->full_open_options = opts;
4726 }
4727
4728 if (bs->exact_filename[0]) {
4729 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
4730 } else if (bs->full_open_options) {
4731 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
4732 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
4733 qstring_get_str(json));
4734 QDECREF(json);
4735 }
4736}
Wen Congyange06018a2016-05-10 15:36:37 +08004737
4738/*
4739 * Hot add/remove a BDS's child. So the user can take a child offline when
4740 * it is broken and take a new child online
4741 */
4742void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
4743 Error **errp)
4744{
4745
4746 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
4747 error_setg(errp, "The node %s does not support adding a child",
4748 bdrv_get_device_or_node_name(parent_bs));
4749 return;
4750 }
4751
4752 if (!QLIST_EMPTY(&child_bs->parents)) {
4753 error_setg(errp, "The node %s already has a parent",
4754 child_bs->node_name);
4755 return;
4756 }
4757
4758 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
4759}
4760
4761void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
4762{
4763 BdrvChild *tmp;
4764
4765 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
4766 error_setg(errp, "The node %s does not support removing a child",
4767 bdrv_get_device_or_node_name(parent_bs));
4768 return;
4769 }
4770
4771 QLIST_FOREACH(tmp, &parent_bs->children, next) {
4772 if (tmp == child) {
4773 break;
4774 }
4775 }
4776
4777 if (!tmp) {
4778 error_setg(errp, "The node %s does not have a child named %s",
4779 bdrv_get_device_or_node_name(parent_bs),
4780 bdrv_get_device_or_node_name(child->bs));
4781 return;
4782 }
4783
4784 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
4785}