blob: c4f5566b5de6cfa371d7b60dd8b0e1a2da7fd55f [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 */
blueswir13990d092008-12-05 17:53:21 +000024#include "config-host.h"
pbrookfaf07962007-11-11 02:51:17 +000025#include "qemu-common.h"
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +010026#include "trace.h"
aliguori376253e2009-03-05 23:01:23 +000027#include "monitor.h"
bellardea2384d2004-08-01 21:59:26 +000028#include "block_int.h"
Paolo Bonzini2f0c9fe2012-09-28 17:22:47 +020029#include "blockjob.h"
Anthony Liguori5efa9d52009-05-09 17:03:42 -050030#include "module.h"
Luiz Capitulinof795e742011-10-21 16:05:43 -020031#include "qjson.h"
Paolo Bonzini3e1caa52012-09-28 17:22:57 +020032#include "sysemu.h"
Paolo Bonzinid7d512f2012-08-23 11:20:36 +020033#include "notify.h"
Kevin Wolf68485422011-06-30 10:05:46 +020034#include "qemu-coroutine.h"
Luiz Capitulinob2023812011-09-21 17:16:47 -030035#include "qmp-commands.h"
Zhi Yong Wu0563e192011-11-03 16:57:25 +080036#include "qemu-timer.h"
bellardfc01f7e2003-06-30 10:03:06 +000037
Juan Quintela71e72a12009-07-27 16:12:56 +020038#ifdef CONFIG_BSD
bellard7674e7b2005-04-26 21:59:26 +000039#include <sys/types.h>
40#include <sys/stat.h>
41#include <sys/ioctl.h>
Blue Swirl72cf2d42009-09-12 07:36:22 +000042#include <sys/queue.h>
blueswir1c5e97232009-03-07 20:06:23 +000043#ifndef __DragonFly__
bellard7674e7b2005-04-26 21:59:26 +000044#include <sys/disk.h>
45#endif
blueswir1c5e97232009-03-07 20:06:23 +000046#endif
bellard7674e7b2005-04-26 21:59:26 +000047
aliguori49dc7682009-03-08 16:26:59 +000048#ifdef _WIN32
49#include <windows.h>
50#endif
51
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010052#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
53
Stefan Hajnoczi470c0502012-01-18 14:40:42 +000054typedef enum {
55 BDRV_REQ_COPY_ON_READ = 0x1,
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +000056 BDRV_REQ_ZERO_WRITE = 0x2,
Stefan Hajnoczi470c0502012-01-18 14:40:42 +000057} BdrvRequestFlags;
58
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +020059static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
aliguorif141eaf2009-04-07 18:43:24 +000060static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
aliguoric87c0672009-04-07 18:43:20 +000062 BlockDriverCompletionFunc *cb, void *opaque);
aliguorif141eaf2009-04-07 18:43:24 +000063static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +000065 BlockDriverCompletionFunc *cb, void *opaque);
Kevin Wolff9f05dc2011-07-15 13:50:26 +020066static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67 int64_t sector_num, int nb_sectors,
68 QEMUIOVector *iov);
69static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70 int64_t sector_num, int nb_sectors,
71 QEMUIOVector *iov);
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +010072static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
Stefan Hajnoczi470c0502012-01-18 14:40:42 +000073 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74 BdrvRequestFlags flags);
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +010075static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +000076 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77 BdrvRequestFlags flags);
Stefan Hajnoczib2a61372011-10-13 13:08:23 +010078static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79 int64_t sector_num,
80 QEMUIOVector *qiov,
81 int nb_sectors,
82 BlockDriverCompletionFunc *cb,
83 void *opaque,
Stefan Hajnoczi8c5873d2011-10-13 21:09:28 +010084 bool is_write);
Stefan Hajnoczib2a61372011-10-13 13:08:23 +010085static void coroutine_fn bdrv_co_do_rw(void *opaque);
Kevin Wolf621f0582012-03-20 15:12:58 +010086static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87 int64_t sector_num, int nb_sectors);
bellardec530c82006-04-25 22:36:06 +000088
Zhi Yong Wu98f90db2011-11-08 13:00:14 +080089static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
90 bool is_write, double elapsed_time, uint64_t *wait);
91static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
92 double elapsed_time, uint64_t *wait);
93static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
94 bool is_write, int64_t *wait);
95
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +010096static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
97 QTAILQ_HEAD_INITIALIZER(bdrv_states);
blueswir17ee930d2008-09-17 19:04:14 +000098
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +010099static QLIST_HEAD(, BlockDriver) bdrv_drivers =
100 QLIST_HEAD_INITIALIZER(bdrv_drivers);
bellardea2384d2004-08-01 21:59:26 +0000101
Markus Armbrusterf9092b12010-06-25 10:33:39 +0200102/* The device to use for VM snapshots */
103static BlockDriverState *bs_snapshots;
104
Markus Armbrustereb852012009-10-27 18:41:44 +0100105/* If non-zero, use only whitelisted block drivers */
106static int use_bdrv_whitelist;
107
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000108#ifdef _WIN32
109static int is_windows_drive_prefix(const char *filename)
110{
111 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
112 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
113 filename[1] == ':');
114}
115
116int is_windows_drive(const char *filename)
117{
118 if (is_windows_drive_prefix(filename) &&
119 filename[2] == '\0')
120 return 1;
121 if (strstart(filename, "\\\\.\\", NULL) ||
122 strstart(filename, "//./", NULL))
123 return 1;
124 return 0;
125}
126#endif
127
Zhi Yong Wu0563e192011-11-03 16:57:25 +0800128/* throttling disk I/O limits */
Zhi Yong Wu98f90db2011-11-08 13:00:14 +0800129void bdrv_io_limits_disable(BlockDriverState *bs)
130{
131 bs->io_limits_enabled = false;
132
133 while (qemu_co_queue_next(&bs->throttled_reqs));
134
135 if (bs->block_timer) {
136 qemu_del_timer(bs->block_timer);
137 qemu_free_timer(bs->block_timer);
138 bs->block_timer = NULL;
139 }
140
141 bs->slice_start = 0;
142 bs->slice_end = 0;
143 bs->slice_time = 0;
144 memset(&bs->io_base, 0, sizeof(bs->io_base));
145}
146
Zhi Yong Wu0563e192011-11-03 16:57:25 +0800147static void bdrv_block_timer(void *opaque)
148{
149 BlockDriverState *bs = opaque;
150
151 qemu_co_queue_next(&bs->throttled_reqs);
152}
153
154void bdrv_io_limits_enable(BlockDriverState *bs)
155{
156 qemu_co_queue_init(&bs->throttled_reqs);
157 bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
158 bs->slice_time = 5 * BLOCK_IO_SLICE_TIME;
159 bs->slice_start = qemu_get_clock_ns(vm_clock);
160 bs->slice_end = bs->slice_start + bs->slice_time;
161 memset(&bs->io_base, 0, sizeof(bs->io_base));
162 bs->io_limits_enabled = true;
163}
164
165bool bdrv_io_limits_enabled(BlockDriverState *bs)
166{
167 BlockIOLimit *io_limits = &bs->io_limits;
168 return io_limits->bps[BLOCK_IO_LIMIT_READ]
169 || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
170 || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
171 || io_limits->iops[BLOCK_IO_LIMIT_READ]
172 || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
173 || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
174}
175
Zhi Yong Wu98f90db2011-11-08 13:00:14 +0800176static void bdrv_io_limits_intercept(BlockDriverState *bs,
177 bool is_write, int nb_sectors)
178{
179 int64_t wait_time = -1;
180
181 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
182 qemu_co_queue_wait(&bs->throttled_reqs);
183 }
184
185 /* In fact, we hope to keep each request's timing, in FIFO mode. The next
186 * throttled requests will not be dequeued until the current request is
187 * allowed to be serviced. So if the current request still exceeds the
188 * limits, it will be inserted to the head. All requests followed it will
189 * be still in throttled_reqs queue.
190 */
191
192 while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
193 qemu_mod_timer(bs->block_timer,
194 wait_time + qemu_get_clock_ns(vm_clock));
195 qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
196 }
197
198 qemu_co_queue_next(&bs->throttled_reqs);
199}
200
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000201/* check if the path starts with "<protocol>:" */
202static int path_has_protocol(const char *path)
203{
Paolo Bonzini947995c2012-05-08 16:51:48 +0200204 const char *p;
205
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000206#ifdef _WIN32
207 if (is_windows_drive(path) ||
208 is_windows_drive_prefix(path)) {
209 return 0;
210 }
Paolo Bonzini947995c2012-05-08 16:51:48 +0200211 p = path + strcspn(path, ":/\\");
212#else
213 p = path + strcspn(path, ":/");
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000214#endif
215
Paolo Bonzini947995c2012-05-08 16:51:48 +0200216 return *p == ':';
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000217}
218
bellard83f64092006-08-01 16:21:11 +0000219int path_is_absolute(const char *path)
220{
bellard21664422007-01-07 18:22:37 +0000221#ifdef _WIN32
222 /* specific case for names like: "\\.\d:" */
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200223 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
bellard21664422007-01-07 18:22:37 +0000224 return 1;
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200225 }
226 return (*path == '/' || *path == '\\');
bellard3b9f94e2007-01-07 17:27:07 +0000227#else
Paolo Bonzinif53f4da2012-05-08 16:51:47 +0200228 return (*path == '/');
bellard3b9f94e2007-01-07 17:27:07 +0000229#endif
bellard83f64092006-08-01 16:21:11 +0000230}
231
232/* if filename is absolute, just copy it to dest. Otherwise, build a
233 path to it by considering it is relative to base_path. URL are
234 supported. */
235void path_combine(char *dest, int dest_size,
236 const char *base_path,
237 const char *filename)
238{
239 const char *p, *p1;
240 int len;
241
242 if (dest_size <= 0)
243 return;
244 if (path_is_absolute(filename)) {
245 pstrcpy(dest, dest_size, filename);
246 } else {
247 p = strchr(base_path, ':');
248 if (p)
249 p++;
250 else
251 p = base_path;
bellard3b9f94e2007-01-07 17:27:07 +0000252 p1 = strrchr(base_path, '/');
253#ifdef _WIN32
254 {
255 const char *p2;
256 p2 = strrchr(base_path, '\\');
257 if (!p1 || p2 > p1)
258 p1 = p2;
259 }
260#endif
bellard83f64092006-08-01 16:21:11 +0000261 if (p1)
262 p1++;
263 else
264 p1 = base_path;
265 if (p1 > p)
266 p = p1;
267 len = p - base_path;
268 if (len > dest_size - 1)
269 len = dest_size - 1;
270 memcpy(dest, base_path, len);
271 dest[len] = '\0';
272 pstrcat(dest, dest_size, filename);
273 }
274}
275
Paolo Bonzinidc5a1372012-05-08 16:51:50 +0200276void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
277{
278 if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
279 pstrcpy(dest, sz, bs->backing_file);
280 } else {
281 path_combine(dest, sz, bs->filename, bs->backing_file);
282 }
283}
284
Anthony Liguori5efa9d52009-05-09 17:03:42 -0500285void bdrv_register(BlockDriver *bdrv)
bellardea2384d2004-08-01 21:59:26 +0000286{
Stefan Hajnoczi8c5873d2011-10-13 21:09:28 +0100287 /* Block drivers without coroutine functions need emulation */
288 if (!bdrv->bdrv_co_readv) {
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200289 bdrv->bdrv_co_readv = bdrv_co_readv_em;
290 bdrv->bdrv_co_writev = bdrv_co_writev_em;
291
Stefan Hajnoczif8c35c12011-10-13 21:09:31 +0100292 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
293 * the block driver lacks aio we need to emulate that too.
294 */
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200295 if (!bdrv->bdrv_aio_readv) {
296 /* add AIO emulation layer */
297 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
298 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
Kevin Wolff9f05dc2011-07-15 13:50:26 +0200299 }
bellard83f64092006-08-01 16:21:11 +0000300 }
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +0200301
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100302 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
bellardea2384d2004-08-01 21:59:26 +0000303}
bellardb3380822004-03-14 21:38:54 +0000304
305/* create a new block device (by default it is empty) */
306BlockDriverState *bdrv_new(const char *device_name)
bellardfc01f7e2003-06-30 10:03:06 +0000307{
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100308 BlockDriverState *bs;
bellardb3380822004-03-14 21:38:54 +0000309
Anthony Liguori7267c092011-08-20 22:09:37 -0500310 bs = g_malloc0(sizeof(BlockDriverState));
bellardb3380822004-03-14 21:38:54 +0000311 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
bellardea2384d2004-08-01 21:59:26 +0000312 if (device_name[0] != '\0') {
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +0100313 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
bellardea2384d2004-08-01 21:59:26 +0000314 }
Luiz Capitulino28a72822011-09-26 17:43:50 -0300315 bdrv_iostatus_disable(bs);
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200316 notifier_list_init(&bs->close_notifiers);
317
bellardb3380822004-03-14 21:38:54 +0000318 return bs;
319}
320
Paolo Bonzinid7d512f2012-08-23 11:20:36 +0200321void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
322{
323 notifier_list_add(&bs->close_notifiers, notify);
324}
325
bellardea2384d2004-08-01 21:59:26 +0000326BlockDriver *bdrv_find_format(const char *format_name)
327{
328 BlockDriver *drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100329 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
330 if (!strcmp(drv1->format_name, format_name)) {
bellardea2384d2004-08-01 21:59:26 +0000331 return drv1;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100332 }
bellardea2384d2004-08-01 21:59:26 +0000333 }
334 return NULL;
335}
336
Markus Armbrustereb852012009-10-27 18:41:44 +0100337static int bdrv_is_whitelisted(BlockDriver *drv)
338{
339 static const char *whitelist[] = {
340 CONFIG_BDRV_WHITELIST
341 };
342 const char **p;
343
344 if (!whitelist[0])
345 return 1; /* no whitelist, anything goes */
346
347 for (p = whitelist; *p; p++) {
348 if (!strcmp(drv->format_name, *p)) {
349 return 1;
350 }
351 }
352 return 0;
353}
354
355BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
356{
357 BlockDriver *drv = bdrv_find_format(format_name);
358 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
359}
360
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800361typedef struct CreateCo {
362 BlockDriver *drv;
363 char *filename;
364 QEMUOptionParameter *options;
365 int ret;
366} CreateCo;
367
368static void coroutine_fn bdrv_create_co_entry(void *opaque)
369{
370 CreateCo *cco = opaque;
371 assert(cco->drv);
372
373 cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
374}
375
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200376int bdrv_create(BlockDriver *drv, const char* filename,
377 QEMUOptionParameter *options)
bellardea2384d2004-08-01 21:59:26 +0000378{
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800379 int ret;
Kevin Wolf0e7e1982009-05-18 16:42:10 +0200380
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800381 Coroutine *co;
382 CreateCo cco = {
383 .drv = drv,
384 .filename = g_strdup(filename),
385 .options = options,
386 .ret = NOT_DONE,
387 };
388
389 if (!drv->bdrv_create) {
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300390 ret = -ENOTSUP;
391 goto out;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800392 }
393
394 if (qemu_in_coroutine()) {
395 /* Fast-path if already in coroutine context */
396 bdrv_create_co_entry(&cco);
397 } else {
398 co = qemu_coroutine_create(bdrv_create_co_entry);
399 qemu_coroutine_enter(co, &cco);
400 while (cco.ret == NOT_DONE) {
401 qemu_aio_wait();
402 }
403 }
404
405 ret = cco.ret;
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800406
Luiz Capitulino80168bf2012-10-17 16:45:25 -0300407out:
408 g_free(cco.filename);
Zhi Yong Wu5b7e1542012-05-07 16:50:42 +0800409 return ret;
bellardea2384d2004-08-01 21:59:26 +0000410}
411
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200412int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
413{
414 BlockDriver *drv;
415
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900416 drv = bdrv_find_protocol(filename);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200417 if (drv == NULL) {
Stefan Hajnoczi16905d72010-11-30 15:14:14 +0000418 return -ENOENT;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200419 }
420
421 return bdrv_create(drv, filename, options);
422}
423
Jim Meyeringeba25052012-05-28 09:27:54 +0200424/*
425 * Create a uniquely-named empty temporary file.
426 * Return 0 upon success, otherwise a negative errno value.
427 */
428int get_tmp_filename(char *filename, int size)
429{
bellardd5249392004-08-03 21:14:23 +0000430#ifdef _WIN32
bellard3b9f94e2007-01-07 17:27:07 +0000431 char temp_dir[MAX_PATH];
Jim Meyeringeba25052012-05-28 09:27:54 +0200432 /* GetTempFileName requires that its output buffer (4th param)
433 have length MAX_PATH or greater. */
434 assert(size >= MAX_PATH);
435 return (GetTempPath(MAX_PATH, temp_dir)
436 && GetTempFileName(temp_dir, "qem", 0, filename)
437 ? 0 : -GetLastError());
bellardd5249392004-08-03 21:14:23 +0000438#else
bellardea2384d2004-08-01 21:59:26 +0000439 int fd;
blueswir17ccfb2e2008-09-14 06:45:34 +0000440 const char *tmpdir;
aurel320badc1e2008-03-10 00:05:34 +0000441 tmpdir = getenv("TMPDIR");
442 if (!tmpdir)
443 tmpdir = "/tmp";
Jim Meyeringeba25052012-05-28 09:27:54 +0200444 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
445 return -EOVERFLOW;
446 }
bellardea2384d2004-08-01 21:59:26 +0000447 fd = mkstemp(filename);
Dunrong Huangfe235a02012-09-05 21:26:22 +0800448 if (fd < 0) {
449 return -errno;
450 }
451 if (close(fd) != 0) {
452 unlink(filename);
Jim Meyeringeba25052012-05-28 09:27:54 +0200453 return -errno;
454 }
455 return 0;
bellardd5249392004-08-03 21:14:23 +0000456#endif
Jim Meyeringeba25052012-05-28 09:27:54 +0200457}
bellardea2384d2004-08-01 21:59:26 +0000458
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200459/*
460 * Detect host devices. By convention, /dev/cdrom[N] is always
461 * recognized as a host CDROM.
462 */
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200463static BlockDriver *find_hdev_driver(const char *filename)
464{
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200465 int score_max = 0, score;
466 BlockDriver *drv = NULL, *d;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200467
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100468 QLIST_FOREACH(d, &bdrv_drivers, list) {
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200469 if (d->bdrv_probe_device) {
470 score = d->bdrv_probe_device(filename);
471 if (score > score_max) {
472 score_max = score;
473 drv = d;
474 }
475 }
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200476 }
477
Christoph Hellwig508c7cb2009-06-15 14:04:22 +0200478 return drv;
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200479}
Christoph Hellwigf3a5d3f2009-06-15 13:55:19 +0200480
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900481BlockDriver *bdrv_find_protocol(const char *filename)
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200482{
483 BlockDriver *drv1;
484 char protocol[128];
485 int len;
486 const char *p;
487
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200488 /* TODO Drivers without bdrv_file_open must be specified explicitly */
489
Christoph Hellwig39508e72010-06-23 12:25:17 +0200490 /*
491 * XXX(hch): we really should not let host device detection
492 * override an explicit protocol specification, but moving this
493 * later breaks access to device names with colons in them.
494 * Thanks to the brain-dead persistent naming schemes on udev-
495 * based Linux systems those actually are quite common.
496 */
497 drv1 = find_hdev_driver(filename);
498 if (drv1) {
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200499 return drv1;
500 }
Christoph Hellwig39508e72010-06-23 12:25:17 +0200501
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000502 if (!path_has_protocol(filename)) {
Christoph Hellwig39508e72010-06-23 12:25:17 +0200503 return bdrv_find_format("file");
504 }
Stefan Hajnoczi9e0b22f2010-12-09 11:53:00 +0000505 p = strchr(filename, ':');
506 assert(p != NULL);
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200507 len = p - filename;
508 if (len > sizeof(protocol) - 1)
509 len = sizeof(protocol) - 1;
510 memcpy(protocol, filename, len);
511 protocol[len] = '\0';
512 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
513 if (drv1->protocol_name &&
514 !strcmp(drv1->protocol_name, protocol)) {
515 return drv1;
516 }
517 }
518 return NULL;
519}
520
Stefan Weilc98ac352010-07-21 21:51:51 +0200521static int find_image_format(const char *filename, BlockDriver **pdrv)
bellardea2384d2004-08-01 21:59:26 +0000522{
bellard83f64092006-08-01 16:21:11 +0000523 int ret, score, score_max;
bellardea2384d2004-08-01 21:59:26 +0000524 BlockDriver *drv1, *drv;
bellard83f64092006-08-01 16:21:11 +0000525 uint8_t buf[2048];
526 BlockDriverState *bs;
ths3b46e622007-09-17 08:09:54 +0000527
Naphtali Spreif5edb012010-01-17 16:48:13 +0200528 ret = bdrv_file_open(&bs, filename, 0);
Stefan Weilc98ac352010-07-21 21:51:51 +0200529 if (ret < 0) {
530 *pdrv = NULL;
531 return ret;
532 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700533
Kevin Wolf08a00552010-06-01 18:37:31 +0200534 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
535 if (bs->sg || !bdrv_is_inserted(bs)) {
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700536 bdrv_delete(bs);
Stefan Weilc98ac352010-07-21 21:51:51 +0200537 drv = bdrv_find_format("raw");
538 if (!drv) {
539 ret = -ENOENT;
540 }
541 *pdrv = drv;
542 return ret;
Nicholas A. Bellinger1a396852010-05-27 08:56:28 -0700543 }
Nicholas Bellingerf8ea0b02010-05-17 09:45:57 -0700544
bellard83f64092006-08-01 16:21:11 +0000545 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
546 bdrv_delete(bs);
547 if (ret < 0) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200548 *pdrv = NULL;
549 return ret;
bellard83f64092006-08-01 16:21:11 +0000550 }
551
bellardea2384d2004-08-01 21:59:26 +0000552 score_max = 0;
Christoph Hellwig84a12e62010-04-07 22:30:24 +0200553 drv = NULL;
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +0100554 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
bellard83f64092006-08-01 16:21:11 +0000555 if (drv1->bdrv_probe) {
556 score = drv1->bdrv_probe(buf, ret, filename);
557 if (score > score_max) {
558 score_max = score;
559 drv = drv1;
560 }
bellardea2384d2004-08-01 21:59:26 +0000561 }
562 }
Stefan Weilc98ac352010-07-21 21:51:51 +0200563 if (!drv) {
564 ret = -ENOENT;
565 }
566 *pdrv = drv;
567 return ret;
bellardea2384d2004-08-01 21:59:26 +0000568}
569
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100570/**
571 * Set the current 'total_sectors' value
572 */
573static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
574{
575 BlockDriver *drv = bs->drv;
576
Nicholas Bellinger396759a2010-05-17 09:46:04 -0700577 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
578 if (bs->sg)
579 return 0;
580
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100581 /* query actual device if possible, otherwise just trust the hint */
582 if (drv->bdrv_getlength) {
583 int64_t length = drv->bdrv_getlength(bs);
584 if (length < 0) {
585 return length;
586 }
587 hint = length >> BDRV_SECTOR_BITS;
588 }
589
590 bs->total_sectors = hint;
591 return 0;
592}
593
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100594/**
595 * Set open flags for a given cache mode
596 *
597 * Return 0 on success, -1 if the cache mode was invalid.
598 */
599int bdrv_parse_cache_flags(const char *mode, int *flags)
600{
601 *flags &= ~BDRV_O_CACHE_MASK;
602
603 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
604 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
Stefan Hajnoczi92196b22011-08-04 12:26:52 +0100605 } else if (!strcmp(mode, "directsync")) {
606 *flags |= BDRV_O_NOCACHE;
Stefan Hajnoczic3993cd2011-08-04 12:26:51 +0100607 } else if (!strcmp(mode, "writeback")) {
608 *flags |= BDRV_O_CACHE_WB;
609 } else if (!strcmp(mode, "unsafe")) {
610 *flags |= BDRV_O_CACHE_WB;
611 *flags |= BDRV_O_NO_FLUSH;
612 } else if (!strcmp(mode, "writethrough")) {
613 /* this is the default */
614 } else {
615 return -1;
616 }
617
618 return 0;
619}
620
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +0000621/**
622 * The copy-on-read flag is actually a reference count so multiple users may
623 * use the feature without worrying about clobbering its previous state.
624 * Copy-on-read stays enabled until all users have called to disable it.
625 */
626void bdrv_enable_copy_on_read(BlockDriverState *bs)
627{
628 bs->copy_on_read++;
629}
630
631void bdrv_disable_copy_on_read(BlockDriverState *bs)
632{
633 assert(bs->copy_on_read > 0);
634 bs->copy_on_read--;
635}
636
Kevin Wolf7b272452012-11-12 17:05:39 +0100637static int bdrv_open_flags(BlockDriverState *bs, int flags)
638{
639 int open_flags = flags | BDRV_O_CACHE_WB;
640
641 /*
642 * Clear flags that are internal to the block layer before opening the
643 * image.
644 */
645 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
646
647 /*
648 * Snapshots should be writable.
649 */
650 if (bs->is_temporary) {
651 open_flags |= BDRV_O_RDWR;
652 }
653
654 return open_flags;
655}
656
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200657/*
Kevin Wolf57915332010-04-14 15:24:50 +0200658 * Common part for opening disk images and files
659 */
660static int bdrv_open_common(BlockDriverState *bs, const char *filename,
661 int flags, BlockDriver *drv)
662{
663 int ret, open_flags;
664
665 assert(drv != NULL);
Paolo Bonzini64058752012-05-08 16:51:49 +0200666 assert(bs->file == NULL);
Kevin Wolf57915332010-04-14 15:24:50 +0200667
Stefan Hajnoczi28dcee12011-09-22 20:14:12 +0100668 trace_bdrv_open_common(bs, filename, flags, drv->format_name);
669
Kevin Wolf57915332010-04-14 15:24:50 +0200670 bs->open_flags = flags;
Kevin Wolf57915332010-04-14 15:24:50 +0200671 bs->buffer_alignment = 512;
672
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +0000673 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
674 if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
675 bdrv_enable_copy_on_read(bs);
676 }
677
Kevin Wolf57915332010-04-14 15:24:50 +0200678 pstrcpy(bs->filename, sizeof(bs->filename), filename);
679
680 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
681 return -ENOTSUP;
682 }
683
684 bs->drv = drv;
Anthony Liguori7267c092011-08-20 22:09:37 -0500685 bs->opaque = g_malloc0(drv->instance_size);
Kevin Wolf57915332010-04-14 15:24:50 +0200686
Stefan Hajnoczi03f541b2011-10-27 10:54:28 +0100687 bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
Kevin Wolf7b272452012-11-12 17:05:39 +0100688 open_flags = bdrv_open_flags(bs, flags);
Kevin Wolf57915332010-04-14 15:24:50 +0200689
Jeff Codybe028ad2012-09-20 15:13:17 -0400690 bs->read_only = !(open_flags & BDRV_O_RDWR);
Stefan Hajnoczie7c63792011-10-27 10:54:27 +0100691
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200692 /* Open the image, either directly or using a protocol */
693 if (drv->bdrv_file_open) {
694 ret = drv->bdrv_file_open(bs, filename, open_flags);
695 } else {
696 ret = bdrv_file_open(&bs->file, filename, open_flags);
697 if (ret >= 0) {
698 ret = drv->bdrv_open(bs, open_flags);
699 }
700 }
701
Kevin Wolf57915332010-04-14 15:24:50 +0200702 if (ret < 0) {
703 goto free_and_fail;
704 }
705
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100706 ret = refresh_total_sectors(bs, bs->total_sectors);
707 if (ret < 0) {
708 goto free_and_fail;
Kevin Wolf57915332010-04-14 15:24:50 +0200709 }
Stefan Hajnoczi51762282010-04-19 16:56:41 +0100710
Kevin Wolf57915332010-04-14 15:24:50 +0200711#ifndef _WIN32
712 if (bs->is_temporary) {
713 unlink(filename);
714 }
715#endif
716 return 0;
717
718free_and_fail:
Kevin Wolf66f82ce2010-04-14 14:17:38 +0200719 if (bs->file) {
720 bdrv_delete(bs->file);
721 bs->file = NULL;
722 }
Anthony Liguori7267c092011-08-20 22:09:37 -0500723 g_free(bs->opaque);
Kevin Wolf57915332010-04-14 15:24:50 +0200724 bs->opaque = NULL;
725 bs->drv = NULL;
726 return ret;
727}
728
729/*
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200730 * Opens a file using a protocol (file, host_device, nbd, ...)
731 */
bellard83f64092006-08-01 16:21:11 +0000732int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
bellardb3380822004-03-14 21:38:54 +0000733{
bellard83f64092006-08-01 16:21:11 +0000734 BlockDriverState *bs;
Christoph Hellwig6db95602010-04-05 16:53:57 +0200735 BlockDriver *drv;
bellard83f64092006-08-01 16:21:11 +0000736 int ret;
737
MORITA Kazutakab50cbab2010-05-26 11:35:36 +0900738 drv = bdrv_find_protocol(filename);
Christoph Hellwig6db95602010-04-05 16:53:57 +0200739 if (!drv) {
740 return -ENOENT;
741 }
742
bellard83f64092006-08-01 16:21:11 +0000743 bs = bdrv_new("");
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200744 ret = bdrv_open_common(bs, filename, flags, drv);
bellard83f64092006-08-01 16:21:11 +0000745 if (ret < 0) {
746 bdrv_delete(bs);
747 return ret;
bellard3b0d4f62005-10-30 18:30:10 +0000748 }
aliguori71d07702009-03-03 17:37:16 +0000749 bs->growable = 1;
bellard83f64092006-08-01 16:21:11 +0000750 *pbs = bs;
751 return 0;
bellardea2384d2004-08-01 21:59:26 +0000752}
bellardfc01f7e2003-06-30 10:03:06 +0000753
Paolo Bonzini9156df12012-10-18 16:49:17 +0200754int bdrv_open_backing_file(BlockDriverState *bs)
755{
756 char backing_filename[PATH_MAX];
757 int back_flags, ret;
758 BlockDriver *back_drv = NULL;
759
760 if (bs->backing_hd != NULL) {
761 return 0;
762 }
763
764 bs->open_flags &= ~BDRV_O_NO_BACKING;
765 if (bs->backing_file[0] == '\0') {
766 return 0;
767 }
768
769 bs->backing_hd = bdrv_new("");
770 bdrv_get_full_backing_filename(bs, backing_filename,
771 sizeof(backing_filename));
772
773 if (bs->backing_format[0] != '\0') {
774 back_drv = bdrv_find_format(bs->backing_format);
775 }
776
777 /* backing files always opened read-only */
778 back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
779
780 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
781 if (ret < 0) {
782 bdrv_delete(bs->backing_hd);
783 bs->backing_hd = NULL;
784 bs->open_flags |= BDRV_O_NO_BACKING;
785 return ret;
786 }
787 return 0;
788}
789
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200790/*
791 * Opens a disk image (raw, qcow2, vmdk, ...)
792 */
Kevin Wolfd6e90982010-03-31 14:40:27 +0200793int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
794 BlockDriver *drv)
bellardea2384d2004-08-01 21:59:26 +0000795{
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200796 int ret;
Stefan Weil89c9bc32012-11-22 07:25:48 +0100797 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
798 char tmp_filename[PATH_MAX + 1];
bellard712e7872005-04-28 21:09:32 +0000799
bellard83f64092006-08-01 16:21:11 +0000800 if (flags & BDRV_O_SNAPSHOT) {
bellardea2384d2004-08-01 21:59:26 +0000801 BlockDriverState *bs1;
802 int64_t total_size;
aliguori7c96d462008-09-12 17:54:13 +0000803 int is_protocol = 0;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200804 BlockDriver *bdrv_qcow2;
805 QEMUOptionParameter *options;
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200806 char backing_filename[PATH_MAX];
ths3b46e622007-09-17 08:09:54 +0000807
bellardea2384d2004-08-01 21:59:26 +0000808 /* if snapshot, we create a temporary backing file and open it
809 instead of opening 'filename' directly */
810
811 /* if there is a backing file, use it */
812 bs1 = bdrv_new("");
Kevin Wolfd6e90982010-03-31 14:40:27 +0200813 ret = bdrv_open(bs1, filename, 0, drv);
aliguori51d7c002009-03-05 23:00:29 +0000814 if (ret < 0) {
bellardea2384d2004-08-01 21:59:26 +0000815 bdrv_delete(bs1);
aliguori51d7c002009-03-05 23:00:29 +0000816 return ret;
bellardea2384d2004-08-01 21:59:26 +0000817 }
Jes Sorensen3e829902010-05-27 16:20:30 +0200818 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
aliguori7c96d462008-09-12 17:54:13 +0000819
820 if (bs1->drv && bs1->drv->protocol_name)
821 is_protocol = 1;
822
bellardea2384d2004-08-01 21:59:26 +0000823 bdrv_delete(bs1);
ths3b46e622007-09-17 08:09:54 +0000824
Jim Meyeringeba25052012-05-28 09:27:54 +0200825 ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
826 if (ret < 0) {
827 return ret;
828 }
aliguori7c96d462008-09-12 17:54:13 +0000829
830 /* Real path is meaningless for protocols */
831 if (is_protocol)
832 snprintf(backing_filename, sizeof(backing_filename),
833 "%s", filename);
Kirill A. Shutemov114cdfa2009-12-25 18:19:22 +0000834 else if (!realpath(filename, backing_filename))
835 return -errno;
aliguori7c96d462008-09-12 17:54:13 +0000836
Kevin Wolf91a073a2009-05-27 14:48:06 +0200837 bdrv_qcow2 = bdrv_find_format("qcow2");
838 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
839
Jes Sorensen3e829902010-05-27 16:20:30 +0200840 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
Kevin Wolf91a073a2009-05-27 14:48:06 +0200841 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
842 if (drv) {
843 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
844 drv->format_name);
845 }
846
847 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
Jan Kiszkad7487682010-04-29 18:24:50 +0200848 free_option_parameters(options);
aliguori51d7c002009-03-05 23:00:29 +0000849 if (ret < 0) {
850 return ret;
bellardea2384d2004-08-01 21:59:26 +0000851 }
Kevin Wolf91a073a2009-05-27 14:48:06 +0200852
bellardea2384d2004-08-01 21:59:26 +0000853 filename = tmp_filename;
Kevin Wolf91a073a2009-05-27 14:48:06 +0200854 drv = bdrv_qcow2;
bellardea2384d2004-08-01 21:59:26 +0000855 bs->is_temporary = 1;
856 }
bellard712e7872005-04-28 21:09:32 +0000857
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200858 /* Find the right image format driver */
Christoph Hellwig6db95602010-04-05 16:53:57 +0200859 if (!drv) {
Stefan Weilc98ac352010-07-21 21:51:51 +0200860 ret = find_image_format(filename, &drv);
aliguori51d7c002009-03-05 23:00:29 +0000861 }
Christoph Hellwig69873072010-01-20 18:13:25 +0100862
aliguori51d7c002009-03-05 23:00:29 +0000863 if (!drv) {
aliguori51d7c002009-03-05 23:00:29 +0000864 goto unlink_and_fail;
bellardea2384d2004-08-01 21:59:26 +0000865 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200866
Jeff Codybe028ad2012-09-20 15:13:17 -0400867 if (flags & BDRV_O_RDWR) {
868 flags |= BDRV_O_ALLOW_RDWR;
869 }
870
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200871 /* Open the image */
872 ret = bdrv_open_common(bs, filename, flags, drv);
873 if (ret < 0) {
Christoph Hellwig69873072010-01-20 18:13:25 +0100874 goto unlink_and_fail;
875 }
876
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200877 /* If there is a backing file, use it */
Paolo Bonzini9156df12012-10-18 16:49:17 +0200878 if ((flags & BDRV_O_NO_BACKING) == 0) {
879 ret = bdrv_open_backing_file(bs);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200880 if (ret < 0) {
881 bdrv_close(bs);
882 return ret;
883 }
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200884 }
885
886 if (!bdrv_key_required(bs)) {
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +0200887 bdrv_dev_change_media_cb(bs, true);
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200888 }
889
Zhi Yong Wu98f90db2011-11-08 13:00:14 +0800890 /* throttling disk I/O limits */
891 if (bs->io_limits_enabled) {
892 bdrv_io_limits_enable(bs);
893 }
894
Kevin Wolfb6ce07a2010-04-12 16:37:13 +0200895 return 0;
896
897unlink_and_fail:
898 if (bs->is_temporary) {
899 unlink(filename);
900 }
901 return ret;
902}
903
Jeff Codye971aa12012-09-20 15:13:19 -0400904typedef struct BlockReopenQueueEntry {
905 bool prepared;
906 BDRVReopenState state;
907 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
908} BlockReopenQueueEntry;
909
910/*
911 * Adds a BlockDriverState to a simple queue for an atomic, transactional
912 * reopen of multiple devices.
913 *
914 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
915 * already performed, or alternatively may be NULL a new BlockReopenQueue will
916 * be created and initialized. This newly created BlockReopenQueue should be
917 * passed back in for subsequent calls that are intended to be of the same
918 * atomic 'set'.
919 *
920 * bs is the BlockDriverState to add to the reopen queue.
921 *
922 * flags contains the open flags for the associated bs
923 *
924 * returns a pointer to bs_queue, which is either the newly allocated
925 * bs_queue, or the existing bs_queue being used.
926 *
927 */
928BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
929 BlockDriverState *bs, int flags)
930{
931 assert(bs != NULL);
932
933 BlockReopenQueueEntry *bs_entry;
934 if (bs_queue == NULL) {
935 bs_queue = g_new0(BlockReopenQueue, 1);
936 QSIMPLEQ_INIT(bs_queue);
937 }
938
939 if (bs->file) {
940 bdrv_reopen_queue(bs_queue, bs->file, flags);
941 }
942
943 bs_entry = g_new0(BlockReopenQueueEntry, 1);
944 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
945
946 bs_entry->state.bs = bs;
947 bs_entry->state.flags = flags;
948
949 return bs_queue;
950}
951
952/*
953 * Reopen multiple BlockDriverStates atomically & transactionally.
954 *
955 * The queue passed in (bs_queue) must have been built up previous
956 * via bdrv_reopen_queue().
957 *
958 * Reopens all BDS specified in the queue, with the appropriate
959 * flags. All devices are prepared for reopen, and failure of any
960 * device will cause all device changes to be abandonded, and intermediate
961 * data cleaned up.
962 *
963 * If all devices prepare successfully, then the changes are committed
964 * to all devices.
965 *
966 */
967int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
968{
969 int ret = -1;
970 BlockReopenQueueEntry *bs_entry, *next;
971 Error *local_err = NULL;
972
973 assert(bs_queue != NULL);
974
975 bdrv_drain_all();
976
977 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
978 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
979 error_propagate(errp, local_err);
980 goto cleanup;
981 }
982 bs_entry->prepared = true;
983 }
984
985 /* If we reach this point, we have success and just need to apply the
986 * changes
987 */
988 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
989 bdrv_reopen_commit(&bs_entry->state);
990 }
991
992 ret = 0;
993
994cleanup:
995 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
996 if (ret && bs_entry->prepared) {
997 bdrv_reopen_abort(&bs_entry->state);
998 }
999 g_free(bs_entry);
1000 }
1001 g_free(bs_queue);
1002 return ret;
1003}
1004
1005
1006/* Reopen a single BlockDriverState with the specified flags. */
1007int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1008{
1009 int ret = -1;
1010 Error *local_err = NULL;
1011 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1012
1013 ret = bdrv_reopen_multiple(queue, &local_err);
1014 if (local_err != NULL) {
1015 error_propagate(errp, local_err);
1016 }
1017 return ret;
1018}
1019
1020
1021/*
1022 * Prepares a BlockDriverState for reopen. All changes are staged in the
1023 * 'opaque' field of the BDRVReopenState, which is used and allocated by
1024 * the block driver layer .bdrv_reopen_prepare()
1025 *
1026 * bs is the BlockDriverState to reopen
1027 * flags are the new open flags
1028 * queue is the reopen queue
1029 *
1030 * Returns 0 on success, non-zero on error. On error errp will be set
1031 * as well.
1032 *
1033 * On failure, bdrv_reopen_abort() will be called to clean up any data.
1034 * It is the responsibility of the caller to then call the abort() or
1035 * commit() for any other BDS that have been left in a prepare() state
1036 *
1037 */
1038int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1039 Error **errp)
1040{
1041 int ret = -1;
1042 Error *local_err = NULL;
1043 BlockDriver *drv;
1044
1045 assert(reopen_state != NULL);
1046 assert(reopen_state->bs->drv != NULL);
1047 drv = reopen_state->bs->drv;
1048
1049 /* if we are to stay read-only, do not allow permission change
1050 * to r/w */
1051 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1052 reopen_state->flags & BDRV_O_RDWR) {
1053 error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1054 reopen_state->bs->device_name);
1055 goto error;
1056 }
1057
1058
1059 ret = bdrv_flush(reopen_state->bs);
1060 if (ret) {
1061 error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1062 strerror(-ret));
1063 goto error;
1064 }
1065
1066 if (drv->bdrv_reopen_prepare) {
1067 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1068 if (ret) {
1069 if (local_err != NULL) {
1070 error_propagate(errp, local_err);
1071 } else {
1072 error_set(errp, QERR_OPEN_FILE_FAILED,
1073 reopen_state->bs->filename);
1074 }
1075 goto error;
1076 }
1077 } else {
1078 /* It is currently mandatory to have a bdrv_reopen_prepare()
1079 * handler for each supported drv. */
1080 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1081 drv->format_name, reopen_state->bs->device_name,
1082 "reopening of file");
1083 ret = -1;
1084 goto error;
1085 }
1086
1087 ret = 0;
1088
1089error:
1090 return ret;
1091}
1092
1093/*
1094 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1095 * makes them final by swapping the staging BlockDriverState contents into
1096 * the active BlockDriverState contents.
1097 */
1098void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1099{
1100 BlockDriver *drv;
1101
1102 assert(reopen_state != NULL);
1103 drv = reopen_state->bs->drv;
1104 assert(drv != NULL);
1105
1106 /* If there are any driver level actions to take */
1107 if (drv->bdrv_reopen_commit) {
1108 drv->bdrv_reopen_commit(reopen_state);
1109 }
1110
1111 /* set BDS specific flags now */
1112 reopen_state->bs->open_flags = reopen_state->flags;
1113 reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1114 BDRV_O_CACHE_WB);
1115 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1116}
1117
1118/*
1119 * Abort the reopen, and delete and free the staged changes in
1120 * reopen_state
1121 */
1122void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1123{
1124 BlockDriver *drv;
1125
1126 assert(reopen_state != NULL);
1127 drv = reopen_state->bs->drv;
1128 assert(drv != NULL);
1129
1130 if (drv->bdrv_reopen_abort) {
1131 drv->bdrv_reopen_abort(reopen_state);
1132 }
1133}
1134
1135
bellardfc01f7e2003-06-30 10:03:06 +00001136void bdrv_close(BlockDriverState *bs)
1137{
Liu Yuan80ccf932012-04-20 17:10:56 +08001138 bdrv_flush(bs);
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02001139 if (bs->job) {
1140 block_job_cancel_sync(bs->job);
1141 }
1142 bdrv_drain_all();
Paolo Bonzinid7d512f2012-08-23 11:20:36 +02001143 notifier_list_notify(&bs->close_notifiers, bs);
Kevin Wolf7094f122012-04-11 11:06:37 +02001144
Paolo Bonzini3cbc0022012-10-19 11:36:48 +02001145 if (bs->drv) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02001146 if (bs == bs_snapshots) {
1147 bs_snapshots = NULL;
1148 }
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +01001149 if (bs->backing_hd) {
bellardea2384d2004-08-01 21:59:26 +00001150 bdrv_delete(bs->backing_hd);
Stefan Hajnoczi557df6a2010-04-17 10:49:06 +01001151 bs->backing_hd = NULL;
1152 }
bellardea2384d2004-08-01 21:59:26 +00001153 bs->drv->bdrv_close(bs);
Anthony Liguori7267c092011-08-20 22:09:37 -05001154 g_free(bs->opaque);
bellardea2384d2004-08-01 21:59:26 +00001155#ifdef _WIN32
1156 if (bs->is_temporary) {
1157 unlink(bs->filename);
1158 }
bellard67b915a2004-03-31 23:37:16 +00001159#endif
bellardea2384d2004-08-01 21:59:26 +00001160 bs->opaque = NULL;
1161 bs->drv = NULL;
Stefan Hajnoczi53fec9d2011-11-28 16:08:47 +00001162 bs->copy_on_read = 0;
Paolo Bonzinia275fa42012-05-08 16:51:43 +02001163 bs->backing_file[0] = '\0';
1164 bs->backing_format[0] = '\0';
Paolo Bonzini64058752012-05-08 16:51:49 +02001165 bs->total_sectors = 0;
1166 bs->encrypted = 0;
1167 bs->valid_key = 0;
1168 bs->sg = 0;
1169 bs->growable = 0;
bellardb3380822004-03-14 21:38:54 +00001170
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001171 if (bs->file != NULL) {
Paolo Bonzini0ac93772012-05-08 16:51:44 +02001172 bdrv_delete(bs->file);
1173 bs->file = NULL;
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001174 }
bellardb3380822004-03-14 21:38:54 +00001175 }
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08001176
Pavel Hrdina9ca11152012-08-09 12:44:48 +02001177 bdrv_dev_change_media_cb(bs, false);
1178
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08001179 /*throttling disk I/O limits*/
1180 if (bs->io_limits_enabled) {
1181 bdrv_io_limits_disable(bs);
1182 }
bellardb3380822004-03-14 21:38:54 +00001183}
1184
MORITA Kazutaka2bc93fe2010-05-28 11:44:57 +09001185void bdrv_close_all(void)
1186{
1187 BlockDriverState *bs;
1188
1189 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1190 bdrv_close(bs);
1191 }
1192}
1193
Stefan Hajnoczi922453b2011-11-30 12:23:43 +00001194/*
1195 * Wait for pending requests to complete across all BlockDriverStates
1196 *
1197 * This function does not flush data to disk, use bdrv_flush_all() for that
1198 * after calling this function.
Zhi Yong Wu4c355d52012-04-12 14:00:57 +02001199 *
1200 * Note that completion of an asynchronous I/O operation can trigger any
1201 * number of other I/O operations on other devices---for example a coroutine
1202 * can be arbitrarily complex and a constant flow of I/O can come until the
1203 * coroutine is complete. Because of this, it is not possible to have a
1204 * function to drain a single device's I/O queue.
Stefan Hajnoczi922453b2011-11-30 12:23:43 +00001205 */
1206void bdrv_drain_all(void)
1207{
1208 BlockDriverState *bs;
Zhi Yong Wu4c355d52012-04-12 14:00:57 +02001209 bool busy;
Stefan Hajnoczi922453b2011-11-30 12:23:43 +00001210
Zhi Yong Wu4c355d52012-04-12 14:00:57 +02001211 do {
1212 busy = qemu_aio_wait();
1213
1214 /* FIXME: We do not have timer support here, so this is effectively
1215 * a busy wait.
1216 */
1217 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1218 if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
1219 qemu_co_queue_restart_all(&bs->throttled_reqs);
1220 busy = true;
1221 }
1222 }
1223 } while (busy);
Stefan Hajnoczi922453b2011-11-30 12:23:43 +00001224
1225 /* If requests are still pending there is a bug somewhere */
1226 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1227 assert(QLIST_EMPTY(&bs->tracked_requests));
1228 assert(qemu_co_queue_empty(&bs->throttled_reqs));
1229 }
1230}
1231
Ryan Harperd22b2f42011-03-29 20:51:47 -05001232/* make a BlockDriverState anonymous by removing from bdrv_state list.
1233 Also, NULL terminate the device_name to prevent double remove */
1234void bdrv_make_anon(BlockDriverState *bs)
1235{
1236 if (bs->device_name[0] != '\0') {
1237 QTAILQ_REMOVE(&bdrv_states, bs, list);
1238 }
1239 bs->device_name[0] = '\0';
1240}
1241
Paolo Bonzinie023b2e2012-05-08 16:51:41 +02001242static void bdrv_rebind(BlockDriverState *bs)
1243{
1244 if (bs->drv && bs->drv->bdrv_rebind) {
1245 bs->drv->bdrv_rebind(bs);
1246 }
1247}
1248
Paolo Bonzini4ddc07c2012-06-14 16:55:02 +02001249static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
1250 BlockDriverState *bs_src)
1251{
1252 /* move some fields that need to stay attached to the device */
1253 bs_dest->open_flags = bs_src->open_flags;
1254
1255 /* dev info */
1256 bs_dest->dev_ops = bs_src->dev_ops;
1257 bs_dest->dev_opaque = bs_src->dev_opaque;
1258 bs_dest->dev = bs_src->dev;
1259 bs_dest->buffer_alignment = bs_src->buffer_alignment;
1260 bs_dest->copy_on_read = bs_src->copy_on_read;
1261
1262 bs_dest->enable_write_cache = bs_src->enable_write_cache;
1263
1264 /* i/o timing parameters */
1265 bs_dest->slice_time = bs_src->slice_time;
1266 bs_dest->slice_start = bs_src->slice_start;
1267 bs_dest->slice_end = bs_src->slice_end;
1268 bs_dest->io_limits = bs_src->io_limits;
1269 bs_dest->io_base = bs_src->io_base;
1270 bs_dest->throttled_reqs = bs_src->throttled_reqs;
1271 bs_dest->block_timer = bs_src->block_timer;
1272 bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
1273
Paolo Bonzini4ddc07c2012-06-14 16:55:02 +02001274 /* r/w error */
1275 bs_dest->on_read_error = bs_src->on_read_error;
1276 bs_dest->on_write_error = bs_src->on_write_error;
1277
1278 /* i/o status */
1279 bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
1280 bs_dest->iostatus = bs_src->iostatus;
1281
1282 /* dirty bitmap */
1283 bs_dest->dirty_count = bs_src->dirty_count;
1284 bs_dest->dirty_bitmap = bs_src->dirty_bitmap;
1285
1286 /* job */
1287 bs_dest->in_use = bs_src->in_use;
1288 bs_dest->job = bs_src->job;
1289
1290 /* keep the same entry in bdrv_states */
1291 pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
1292 bs_src->device_name);
1293 bs_dest->list = bs_src->list;
1294}
1295
1296/*
1297 * Swap bs contents for two image chains while they are live,
1298 * while keeping required fields on the BlockDriverState that is
1299 * actually attached to a device.
1300 *
1301 * This will modify the BlockDriverState fields, and swap contents
1302 * between bs_new and bs_old. Both bs_new and bs_old are modified.
1303 *
1304 * bs_new is required to be anonymous.
1305 *
1306 * This function does not create any image files.
1307 */
1308void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
1309{
1310 BlockDriverState tmp;
1311
1312 /* bs_new must be anonymous and shouldn't have anything fancy enabled */
1313 assert(bs_new->device_name[0] == '\0');
1314 assert(bs_new->dirty_bitmap == NULL);
1315 assert(bs_new->job == NULL);
1316 assert(bs_new->dev == NULL);
1317 assert(bs_new->in_use == 0);
1318 assert(bs_new->io_limits_enabled == false);
1319 assert(bs_new->block_timer == NULL);
1320
1321 tmp = *bs_new;
1322 *bs_new = *bs_old;
1323 *bs_old = tmp;
1324
1325 /* there are some fields that should not be swapped, move them back */
1326 bdrv_move_feature_fields(&tmp, bs_old);
1327 bdrv_move_feature_fields(bs_old, bs_new);
1328 bdrv_move_feature_fields(bs_new, &tmp);
1329
1330 /* bs_new shouldn't be in bdrv_states even after the swap! */
1331 assert(bs_new->device_name[0] == '\0');
1332
1333 /* Check a few fields that should remain attached to the device */
1334 assert(bs_new->dev == NULL);
1335 assert(bs_new->job == NULL);
1336 assert(bs_new->in_use == 0);
1337 assert(bs_new->io_limits_enabled == false);
1338 assert(bs_new->block_timer == NULL);
1339
1340 bdrv_rebind(bs_new);
1341 bdrv_rebind(bs_old);
1342}
1343
Jeff Cody8802d1f2012-02-28 15:54:06 -05001344/*
1345 * Add new bs contents at the top of an image chain while the chain is
1346 * live, while keeping required fields on the top layer.
1347 *
1348 * This will modify the BlockDriverState fields, and swap contents
1349 * between bs_new and bs_top. Both bs_new and bs_top are modified.
1350 *
Jeff Codyf6801b82012-03-27 16:30:19 -04001351 * bs_new is required to be anonymous.
1352 *
Jeff Cody8802d1f2012-02-28 15:54:06 -05001353 * This function does not create any image files.
1354 */
1355void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
1356{
Paolo Bonzini4ddc07c2012-06-14 16:55:02 +02001357 bdrv_swap(bs_new, bs_top);
Jeff Cody8802d1f2012-02-28 15:54:06 -05001358
1359 /* The contents of 'tmp' will become bs_top, as we are
1360 * swapping bs_new and bs_top contents. */
Paolo Bonzini4ddc07c2012-06-14 16:55:02 +02001361 bs_top->backing_hd = bs_new;
1362 bs_top->open_flags &= ~BDRV_O_NO_BACKING;
1363 pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
1364 bs_new->filename);
1365 pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
1366 bs_new->drv ? bs_new->drv->format_name : "");
Jeff Cody8802d1f2012-02-28 15:54:06 -05001367}
1368
bellardb3380822004-03-14 21:38:54 +00001369void bdrv_delete(BlockDriverState *bs)
1370{
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001371 assert(!bs->dev);
Paolo Bonzini3e914652012-03-30 13:17:11 +02001372 assert(!bs->job);
1373 assert(!bs->in_use);
Markus Armbruster18846de2010-06-29 16:58:30 +02001374
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01001375 /* remove from list, if necessary */
Ryan Harperd22b2f42011-03-29 20:51:47 -05001376 bdrv_make_anon(bs);
aurel3234c6f052008-04-08 19:51:21 +00001377
bellardb3380822004-03-14 21:38:54 +00001378 bdrv_close(bs);
Kevin Wolf66f82ce2010-04-14 14:17:38 +02001379
Markus Armbrusterf9092b12010-06-25 10:33:39 +02001380 assert(bs != bs_snapshots);
Anthony Liguori7267c092011-08-20 22:09:37 -05001381 g_free(bs);
bellardfc01f7e2003-06-30 10:03:06 +00001382}
1383
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001384int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1385/* TODO change to DeviceState *dev when all users are qdevified */
Markus Armbruster18846de2010-06-29 16:58:30 +02001386{
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001387 if (bs->dev) {
Markus Armbruster18846de2010-06-29 16:58:30 +02001388 return -EBUSY;
1389 }
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001390 bs->dev = dev;
Luiz Capitulino28a72822011-09-26 17:43:50 -03001391 bdrv_iostatus_reset(bs);
Markus Armbruster18846de2010-06-29 16:58:30 +02001392 return 0;
1393}
1394
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001395/* TODO qdevified devices don't use this, remove when devices are qdevified */
1396void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
Markus Armbruster18846de2010-06-29 16:58:30 +02001397{
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001398 if (bdrv_attach_dev(bs, dev) < 0) {
1399 abort();
1400 }
1401}
1402
1403void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1404/* TODO change to DeviceState *dev when all users are qdevified */
1405{
1406 assert(bs->dev == dev);
1407 bs->dev = NULL;
Markus Armbruster0e49de52011-08-03 15:07:41 +02001408 bs->dev_ops = NULL;
1409 bs->dev_opaque = NULL;
Markus Armbruster29e05f22011-09-06 18:58:57 +02001410 bs->buffer_alignment = 512;
Markus Armbruster18846de2010-06-29 16:58:30 +02001411}
1412
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001413/* TODO change to return DeviceState * when all users are qdevified */
1414void *bdrv_get_attached_dev(BlockDriverState *bs)
Markus Armbruster18846de2010-06-29 16:58:30 +02001415{
Markus Armbrusterfa879d62011-08-03 15:07:40 +02001416 return bs->dev;
Markus Armbruster18846de2010-06-29 16:58:30 +02001417}
1418
Markus Armbruster0e49de52011-08-03 15:07:41 +02001419void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
1420 void *opaque)
1421{
1422 bs->dev_ops = ops;
1423 bs->dev_opaque = opaque;
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001424 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
1425 bs_snapshots = NULL;
1426 }
Markus Armbruster0e49de52011-08-03 15:07:41 +02001427}
1428
Paolo Bonzini32c81a42012-09-28 17:22:58 +02001429void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1430 enum MonitorEvent ev,
1431 BlockErrorAction action, bool is_read)
Luiz Capitulino329c0a42012-01-25 16:59:43 -02001432{
1433 QObject *data;
1434 const char *action_str;
1435
1436 switch (action) {
1437 case BDRV_ACTION_REPORT:
1438 action_str = "report";
1439 break;
1440 case BDRV_ACTION_IGNORE:
1441 action_str = "ignore";
1442 break;
1443 case BDRV_ACTION_STOP:
1444 action_str = "stop";
1445 break;
1446 default:
1447 abort();
1448 }
1449
1450 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1451 bdrv->device_name,
1452 action_str,
1453 is_read ? "read" : "write");
Paolo Bonzini32c81a42012-09-28 17:22:58 +02001454 monitor_protocol_event(ev, data);
Luiz Capitulino329c0a42012-01-25 16:59:43 -02001455
1456 qobject_decref(data);
1457}
1458
Luiz Capitulino6f382ed2012-02-14 13:41:13 -02001459static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
1460{
1461 QObject *data;
1462
1463 data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
1464 bdrv_get_device_name(bs), ejected);
1465 monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
1466
1467 qobject_decref(data);
1468}
1469
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +02001470static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
Markus Armbruster0e49de52011-08-03 15:07:41 +02001471{
Markus Armbruster145feb12011-08-03 15:07:42 +02001472 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
Luiz Capitulino6f382ed2012-02-14 13:41:13 -02001473 bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +02001474 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
Luiz Capitulino6f382ed2012-02-14 13:41:13 -02001475 if (tray_was_closed) {
1476 /* tray open */
1477 bdrv_emit_qmp_eject_event(bs, true);
1478 }
1479 if (load) {
1480 /* tray close */
1481 bdrv_emit_qmp_eject_event(bs, false);
1482 }
Markus Armbruster145feb12011-08-03 15:07:42 +02001483 }
1484}
1485
Markus Armbruster2c6942f2011-09-06 18:58:51 +02001486bool bdrv_dev_has_removable_media(BlockDriverState *bs)
1487{
1488 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
1489}
1490
Paolo Bonzini025ccaa2011-11-07 17:50:13 +01001491void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1492{
1493 if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1494 bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1495 }
1496}
1497
Markus Armbrustere4def802011-09-06 18:58:53 +02001498bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1499{
1500 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1501 return bs->dev_ops->is_tray_open(bs->dev_opaque);
1502 }
1503 return false;
1504}
1505
Markus Armbruster145feb12011-08-03 15:07:42 +02001506static void bdrv_dev_resize_cb(BlockDriverState *bs)
1507{
1508 if (bs->dev_ops && bs->dev_ops->resize_cb) {
1509 bs->dev_ops->resize_cb(bs->dev_opaque);
Markus Armbruster0e49de52011-08-03 15:07:41 +02001510 }
1511}
1512
Markus Armbrusterf1076392011-09-06 18:58:46 +02001513bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1514{
1515 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1516 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1517 }
1518 return false;
1519}
1520
aliguorie97fc192009-04-21 23:11:50 +00001521/*
1522 * Run consistency checks on an image
1523 *
Kevin Wolfe076f332010-06-29 11:43:13 +02001524 * Returns 0 if the check could be completed (it doesn't mean that the image is
Stefan Weila1c72732011-04-28 17:20:38 +02001525 * free of errors) or -errno when an internal error occurred. The results of the
Kevin Wolfe076f332010-06-29 11:43:13 +02001526 * check are stored in res.
aliguorie97fc192009-04-21 23:11:50 +00001527 */
Kevin Wolf4534ff52012-05-11 16:07:02 +02001528int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
aliguorie97fc192009-04-21 23:11:50 +00001529{
1530 if (bs->drv->bdrv_check == NULL) {
1531 return -ENOTSUP;
1532 }
1533
Kevin Wolfe076f332010-06-29 11:43:13 +02001534 memset(res, 0, sizeof(*res));
Kevin Wolf4534ff52012-05-11 16:07:02 +02001535 return bs->drv->bdrv_check(bs, res, fix);
aliguorie97fc192009-04-21 23:11:50 +00001536}
1537
Kevin Wolf8a426612010-07-16 17:17:01 +02001538#define COMMIT_BUF_SECTORS 2048
1539
bellard33e39632003-07-06 17:15:21 +00001540/* commit COW file into the raw image */
1541int bdrv_commit(BlockDriverState *bs)
1542{
bellard19cb3732006-08-19 11:45:59 +00001543 BlockDriver *drv = bs->drv;
Kevin Wolf8a426612010-07-16 17:17:01 +02001544 int64_t sector, total_sectors;
1545 int n, ro, open_flags;
Jeff Cody0bce5972012-09-20 15:13:34 -04001546 int ret = 0;
Kevin Wolf8a426612010-07-16 17:17:01 +02001547 uint8_t *buf;
Jim Meyeringc2cba3d2012-10-04 13:09:46 +02001548 char filename[PATH_MAX];
bellard33e39632003-07-06 17:15:21 +00001549
bellard19cb3732006-08-19 11:45:59 +00001550 if (!drv)
1551 return -ENOMEDIUM;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +02001552
1553 if (!bs->backing_hd) {
1554 return -ENOTSUP;
bellard33e39632003-07-06 17:15:21 +00001555 }
1556
Stefan Hajnoczi2d3735d2012-01-18 14:40:41 +00001557 if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
1558 return -EBUSY;
1559 }
1560
Naphtali Sprei4dca4b62010-02-14 13:39:18 +02001561 ro = bs->backing_hd->read_only;
Jim Meyeringc2cba3d2012-10-04 13:09:46 +02001562 /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1563 pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +02001564 open_flags = bs->backing_hd->open_flags;
1565
1566 if (ro) {
Jeff Cody0bce5972012-09-20 15:13:34 -04001567 if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
1568 return -EACCES;
Naphtali Sprei4dca4b62010-02-14 13:39:18 +02001569 }
bellard33e39632003-07-06 17:15:21 +00001570 }
bellardea2384d2004-08-01 21:59:26 +00001571
Jan Kiszka6ea44302009-11-30 18:21:19 +01001572 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
Anthony Liguori7267c092011-08-20 22:09:37 -05001573 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
bellardea2384d2004-08-01 21:59:26 +00001574
Kevin Wolf8a426612010-07-16 17:17:01 +02001575 for (sector = 0; sector < total_sectors; sector += n) {
Stefan Hajnoczi05c4af52011-11-14 12:44:18 +00001576 if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
Kevin Wolf8a426612010-07-16 17:17:01 +02001577
1578 if (bdrv_read(bs, sector, buf, n) != 0) {
1579 ret = -EIO;
1580 goto ro_cleanup;
1581 }
1582
1583 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
1584 ret = -EIO;
1585 goto ro_cleanup;
1586 }
bellardea2384d2004-08-01 21:59:26 +00001587 }
1588 }
bellard95389c82005-12-18 18:28:15 +00001589
Christoph Hellwig1d449522010-01-17 12:32:30 +01001590 if (drv->bdrv_make_empty) {
1591 ret = drv->bdrv_make_empty(bs);
1592 bdrv_flush(bs);
1593 }
bellard95389c82005-12-18 18:28:15 +00001594
Christoph Hellwig3f5075a2010-01-12 13:49:23 +01001595 /*
1596 * Make sure all data we wrote to the backing device is actually
1597 * stable on disk.
1598 */
1599 if (bs->backing_hd)
1600 bdrv_flush(bs->backing_hd);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +02001601
1602ro_cleanup:
Anthony Liguori7267c092011-08-20 22:09:37 -05001603 g_free(buf);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +02001604
1605 if (ro) {
Jeff Cody0bce5972012-09-20 15:13:34 -04001606 /* ignoring error return here */
1607 bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
Naphtali Sprei4dca4b62010-02-14 13:39:18 +02001608 }
1609
Christoph Hellwig1d449522010-01-17 12:32:30 +01001610 return ret;
bellard33e39632003-07-06 17:15:21 +00001611}
1612
Stefan Hajnoczie8877492012-03-05 18:10:11 +00001613int bdrv_commit_all(void)
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +02001614{
1615 BlockDriverState *bs;
1616
1617 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Stefan Hajnoczie8877492012-03-05 18:10:11 +00001618 int ret = bdrv_commit(bs);
1619 if (ret < 0) {
1620 return ret;
1621 }
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +02001622 }
Stefan Hajnoczie8877492012-03-05 18:10:11 +00001623 return 0;
Markus Armbruster6ab4b5a2010-06-02 18:55:18 +02001624}
1625
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00001626struct BdrvTrackedRequest {
1627 BlockDriverState *bs;
1628 int64_t sector_num;
1629 int nb_sectors;
1630 bool is_write;
1631 QLIST_ENTRY(BdrvTrackedRequest) list;
Stefan Hajnoczi5f8b6492011-11-30 12:23:42 +00001632 Coroutine *co; /* owner, used for deadlock detection */
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001633 CoQueue wait_queue; /* coroutines blocked on this request */
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00001634};
1635
1636/**
1637 * Remove an active request from the tracked requests list
1638 *
1639 * This function should be called when a tracked request is completing.
1640 */
1641static void tracked_request_end(BdrvTrackedRequest *req)
1642{
1643 QLIST_REMOVE(req, list);
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001644 qemu_co_queue_restart_all(&req->wait_queue);
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00001645}
1646
1647/**
1648 * Add an active request to the tracked requests list
1649 */
1650static void tracked_request_begin(BdrvTrackedRequest *req,
1651 BlockDriverState *bs,
1652 int64_t sector_num,
1653 int nb_sectors, bool is_write)
1654{
1655 *req = (BdrvTrackedRequest){
1656 .bs = bs,
1657 .sector_num = sector_num,
1658 .nb_sectors = nb_sectors,
1659 .is_write = is_write,
Stefan Hajnoczi5f8b6492011-11-30 12:23:42 +00001660 .co = qemu_coroutine_self(),
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00001661 };
1662
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001663 qemu_co_queue_init(&req->wait_queue);
1664
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00001665 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1666}
1667
Stefan Hajnoczid83947a2011-11-23 11:47:56 +00001668/**
1669 * Round a region to cluster boundaries
1670 */
1671static void round_to_clusters(BlockDriverState *bs,
1672 int64_t sector_num, int nb_sectors,
1673 int64_t *cluster_sector_num,
1674 int *cluster_nb_sectors)
1675{
1676 BlockDriverInfo bdi;
1677
1678 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1679 *cluster_sector_num = sector_num;
1680 *cluster_nb_sectors = nb_sectors;
1681 } else {
1682 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1683 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1684 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1685 nb_sectors, c);
1686 }
1687}
1688
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001689static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1690 int64_t sector_num, int nb_sectors) {
Stefan Hajnoczid83947a2011-11-23 11:47:56 +00001691 /* aaaa bbbb */
1692 if (sector_num >= req->sector_num + req->nb_sectors) {
1693 return false;
1694 }
1695 /* bbbb aaaa */
1696 if (req->sector_num >= sector_num + nb_sectors) {
1697 return false;
1698 }
1699 return true;
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001700}
1701
1702static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1703 int64_t sector_num, int nb_sectors)
1704{
1705 BdrvTrackedRequest *req;
Stefan Hajnoczid83947a2011-11-23 11:47:56 +00001706 int64_t cluster_sector_num;
1707 int cluster_nb_sectors;
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001708 bool retry;
1709
Stefan Hajnoczid83947a2011-11-23 11:47:56 +00001710 /* If we touch the same cluster it counts as an overlap. This guarantees
1711 * that allocating writes will be serialized and not race with each other
1712 * for the same cluster. For example, in copy-on-read it ensures that the
1713 * CoR read and write operations are atomic and guest writes cannot
1714 * interleave between them.
1715 */
1716 round_to_clusters(bs, sector_num, nb_sectors,
1717 &cluster_sector_num, &cluster_nb_sectors);
1718
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001719 do {
1720 retry = false;
1721 QLIST_FOREACH(req, &bs->tracked_requests, list) {
Stefan Hajnoczid83947a2011-11-23 11:47:56 +00001722 if (tracked_request_overlaps(req, cluster_sector_num,
1723 cluster_nb_sectors)) {
Stefan Hajnoczi5f8b6492011-11-30 12:23:42 +00001724 /* Hitting this means there was a reentrant request, for
1725 * example, a block driver issuing nested requests. This must
1726 * never happen since it means deadlock.
1727 */
1728 assert(qemu_coroutine_self() != req->co);
1729
Stefan Hajnoczif4658282011-11-17 13:40:29 +00001730 qemu_co_queue_wait(&req->wait_queue);
1731 retry = true;
1732 break;
1733 }
1734 }
1735 } while (retry);
1736}
1737
Kevin Wolf756e6732010-01-12 12:55:17 +01001738/*
1739 * Return values:
1740 * 0 - success
1741 * -EINVAL - backing format specified, but no file
1742 * -ENOSPC - can't update the backing file because no space is left in the
1743 * image file header
1744 * -ENOTSUP - format driver doesn't support changing the backing file
1745 */
1746int bdrv_change_backing_file(BlockDriverState *bs,
1747 const char *backing_file, const char *backing_fmt)
1748{
1749 BlockDriver *drv = bs->drv;
Paolo Bonzini469ef352012-04-12 14:01:02 +02001750 int ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01001751
Paolo Bonzini5f377792012-04-12 14:01:01 +02001752 /* Backing file format doesn't make sense without a backing file */
1753 if (backing_fmt && !backing_file) {
1754 return -EINVAL;
1755 }
1756
Kevin Wolf756e6732010-01-12 12:55:17 +01001757 if (drv->bdrv_change_backing_file != NULL) {
Paolo Bonzini469ef352012-04-12 14:01:02 +02001758 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
Kevin Wolf756e6732010-01-12 12:55:17 +01001759 } else {
Paolo Bonzini469ef352012-04-12 14:01:02 +02001760 ret = -ENOTSUP;
Kevin Wolf756e6732010-01-12 12:55:17 +01001761 }
Paolo Bonzini469ef352012-04-12 14:01:02 +02001762
1763 if (ret == 0) {
1764 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1765 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1766 }
1767 return ret;
Kevin Wolf756e6732010-01-12 12:55:17 +01001768}
1769
Jeff Cody6ebdcee2012-09-27 13:29:12 -04001770/*
1771 * Finds the image layer in the chain that has 'bs' as its backing file.
1772 *
1773 * active is the current topmost image.
1774 *
1775 * Returns NULL if bs is not found in active's image chain,
1776 * or if active == bs.
1777 */
1778BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
1779 BlockDriverState *bs)
1780{
1781 BlockDriverState *overlay = NULL;
1782 BlockDriverState *intermediate;
1783
1784 assert(active != NULL);
1785 assert(bs != NULL);
1786
1787 /* if bs is the same as active, then by definition it has no overlay
1788 */
1789 if (active == bs) {
1790 return NULL;
1791 }
1792
1793 intermediate = active;
1794 while (intermediate->backing_hd) {
1795 if (intermediate->backing_hd == bs) {
1796 overlay = intermediate;
1797 break;
1798 }
1799 intermediate = intermediate->backing_hd;
1800 }
1801
1802 return overlay;
1803}
1804
1805typedef struct BlkIntermediateStates {
1806 BlockDriverState *bs;
1807 QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
1808} BlkIntermediateStates;
1809
1810
1811/*
1812 * Drops images above 'base' up to and including 'top', and sets the image
1813 * above 'top' to have base as its backing file.
1814 *
1815 * Requires that the overlay to 'top' is opened r/w, so that the backing file
1816 * information in 'bs' can be properly updated.
1817 *
1818 * E.g., this will convert the following chain:
1819 * bottom <- base <- intermediate <- top <- active
1820 *
1821 * to
1822 *
1823 * bottom <- base <- active
1824 *
1825 * It is allowed for bottom==base, in which case it converts:
1826 *
1827 * base <- intermediate <- top <- active
1828 *
1829 * to
1830 *
1831 * base <- active
1832 *
1833 * Error conditions:
1834 * if active == top, that is considered an error
1835 *
1836 */
1837int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
1838 BlockDriverState *base)
1839{
1840 BlockDriverState *intermediate;
1841 BlockDriverState *base_bs = NULL;
1842 BlockDriverState *new_top_bs = NULL;
1843 BlkIntermediateStates *intermediate_state, *next;
1844 int ret = -EIO;
1845
1846 QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
1847 QSIMPLEQ_INIT(&states_to_delete);
1848
1849 if (!top->drv || !base->drv) {
1850 goto exit;
1851 }
1852
1853 new_top_bs = bdrv_find_overlay(active, top);
1854
1855 if (new_top_bs == NULL) {
1856 /* we could not find the image above 'top', this is an error */
1857 goto exit;
1858 }
1859
1860 /* special case of new_top_bs->backing_hd already pointing to base - nothing
1861 * to do, no intermediate images */
1862 if (new_top_bs->backing_hd == base) {
1863 ret = 0;
1864 goto exit;
1865 }
1866
1867 intermediate = top;
1868
1869 /* now we will go down through the list, and add each BDS we find
1870 * into our deletion queue, until we hit the 'base'
1871 */
1872 while (intermediate) {
1873 intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
1874 intermediate_state->bs = intermediate;
1875 QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
1876
1877 if (intermediate->backing_hd == base) {
1878 base_bs = intermediate->backing_hd;
1879 break;
1880 }
1881 intermediate = intermediate->backing_hd;
1882 }
1883 if (base_bs == NULL) {
1884 /* something went wrong, we did not end at the base. safely
1885 * unravel everything, and exit with error */
1886 goto exit;
1887 }
1888
1889 /* success - we can delete the intermediate states, and link top->base */
1890 ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
1891 base_bs->drv ? base_bs->drv->format_name : "");
1892 if (ret) {
1893 goto exit;
1894 }
1895 new_top_bs->backing_hd = base_bs;
1896
1897
1898 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
1899 /* so that bdrv_close() does not recursively close the chain */
1900 intermediate_state->bs->backing_hd = NULL;
1901 bdrv_delete(intermediate_state->bs);
1902 }
1903 ret = 0;
1904
1905exit:
1906 QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
1907 g_free(intermediate_state);
1908 }
1909 return ret;
1910}
1911
1912
aliguori71d07702009-03-03 17:37:16 +00001913static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1914 size_t size)
1915{
1916 int64_t len;
1917
1918 if (!bdrv_is_inserted(bs))
1919 return -ENOMEDIUM;
1920
1921 if (bs->growable)
1922 return 0;
1923
1924 len = bdrv_getlength(bs);
1925
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02001926 if (offset < 0)
1927 return -EIO;
1928
1929 if ((offset > len) || (len - offset < size))
aliguori71d07702009-03-03 17:37:16 +00001930 return -EIO;
1931
1932 return 0;
1933}
1934
1935static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1936 int nb_sectors)
1937{
Jes Sorenseneb5a3162010-05-27 16:20:31 +02001938 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1939 nb_sectors * BDRV_SECTOR_SIZE);
aliguori71d07702009-03-03 17:37:16 +00001940}
1941
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +01001942typedef struct RwCo {
1943 BlockDriverState *bs;
1944 int64_t sector_num;
1945 int nb_sectors;
1946 QEMUIOVector *qiov;
1947 bool is_write;
1948 int ret;
1949} RwCo;
1950
1951static void coroutine_fn bdrv_rw_co_entry(void *opaque)
1952{
1953 RwCo *rwco = opaque;
1954
1955 if (!rwco->is_write) {
1956 rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00001957 rwco->nb_sectors, rwco->qiov, 0);
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +01001958 } else {
1959 rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00001960 rwco->nb_sectors, rwco->qiov, 0);
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +01001961 }
1962}
1963
1964/*
1965 * Process a synchronous request using coroutines
1966 */
1967static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
1968 int nb_sectors, bool is_write)
1969{
1970 QEMUIOVector qiov;
1971 struct iovec iov = {
1972 .iov_base = (void *)buf,
1973 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1974 };
1975 Coroutine *co;
1976 RwCo rwco = {
1977 .bs = bs,
1978 .sector_num = sector_num,
1979 .nb_sectors = nb_sectors,
1980 .qiov = &qiov,
1981 .is_write = is_write,
1982 .ret = NOT_DONE,
1983 };
1984
1985 qemu_iovec_init_external(&qiov, &iov, 1);
1986
Zhi Yong Wu498e3862012-04-02 18:59:34 +08001987 /**
1988 * In sync call context, when the vcpu is blocked, this throttling timer
1989 * will not fire; so the I/O throttling function has to be disabled here
1990 * if it has been enabled.
1991 */
1992 if (bs->io_limits_enabled) {
1993 fprintf(stderr, "Disabling I/O throttling on '%s' due "
1994 "to synchronous I/O.\n", bdrv_get_device_name(bs));
1995 bdrv_io_limits_disable(bs);
1996 }
1997
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +01001998 if (qemu_in_coroutine()) {
1999 /* Fast-path if already in coroutine context */
2000 bdrv_rw_co_entry(&rwco);
2001 } else {
2002 co = qemu_coroutine_create(bdrv_rw_co_entry);
2003 qemu_coroutine_enter(co, &rwco);
2004 while (rwco.ret == NOT_DONE) {
2005 qemu_aio_wait();
2006 }
2007 }
2008 return rwco.ret;
2009}
2010
bellard19cb3732006-08-19 11:45:59 +00002011/* return < 0 if error. See bdrv_write() for the return codes */
ths5fafdf22007-09-16 21:08:06 +00002012int bdrv_read(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00002013 uint8_t *buf, int nb_sectors)
2014{
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +01002015 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
bellardfc01f7e2003-06-30 10:03:06 +00002016}
2017
Markus Armbruster07d27a42012-06-29 17:34:29 +02002018/* Just like bdrv_read(), but with I/O throttling temporarily disabled */
2019int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
2020 uint8_t *buf, int nb_sectors)
2021{
2022 bool enabled;
2023 int ret;
2024
2025 enabled = bs->io_limits_enabled;
2026 bs->io_limits_enabled = false;
2027 ret = bdrv_read(bs, 0, buf, 1);
2028 bs->io_limits_enabled = enabled;
2029 return ret;
2030}
2031
Paolo Bonzini71df14f2012-04-12 14:01:04 +02002032#define BITS_PER_LONG (sizeof(unsigned long) * 8)
2033
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002034static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002035 int nb_sectors, int dirty)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002036{
2037 int64_t start, end;
Jan Kiszkac6d22832009-11-30 18:21:20 +01002038 unsigned long val, idx, bit;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002039
Jan Kiszka6ea44302009-11-30 18:21:19 +01002040 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkac6d22832009-11-30 18:21:20 +01002041 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002042
2043 for (; start <= end; start++) {
Paolo Bonzini71df14f2012-04-12 14:01:04 +02002044 idx = start / BITS_PER_LONG;
2045 bit = start % BITS_PER_LONG;
Jan Kiszkac6d22832009-11-30 18:21:20 +01002046 val = bs->dirty_bitmap[idx];
2047 if (dirty) {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02002048 if (!(val & (1UL << bit))) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02002049 bs->dirty_count++;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02002050 val |= 1UL << bit;
Liran Schouraaa0eb72010-01-26 10:31:48 +02002051 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01002052 } else {
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02002053 if (val & (1UL << bit)) {
Liran Schouraaa0eb72010-01-26 10:31:48 +02002054 bs->dirty_count--;
Marcelo Tosatti6d59fec2010-11-08 17:02:54 -02002055 val &= ~(1UL << bit);
Liran Schouraaa0eb72010-01-26 10:31:48 +02002056 }
Jan Kiszkac6d22832009-11-30 18:21:20 +01002057 }
2058 bs->dirty_bitmap[idx] = val;
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02002059 }
2060}
2061
ths5fafdf22007-09-16 21:08:06 +00002062/* Return < 0 if error. Important errors are:
bellard19cb3732006-08-19 11:45:59 +00002063 -EIO generic I/O error (may happen for all errors)
2064 -ENOMEDIUM No media inserted.
2065 -EINVAL Invalid sector number or nb_sectors
2066 -EACCES Trying to write a read-only device
2067*/
ths5fafdf22007-09-16 21:08:06 +00002068int bdrv_write(BlockDriverState *bs, int64_t sector_num,
bellardfc01f7e2003-06-30 10:03:06 +00002069 const uint8_t *buf, int nb_sectors)
2070{
Stefan Hajnoczi1c9805a2011-10-13 13:08:22 +01002071 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
bellard83f64092006-08-01 16:21:11 +00002072}
2073
aliguorieda578e2009-03-12 19:57:16 +00002074int bdrv_pread(BlockDriverState *bs, int64_t offset,
2075 void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00002076{
Jan Kiszka6ea44302009-11-30 18:21:19 +01002077 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00002078 int len, nb_sectors, count;
2079 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002080 int ret;
bellard83f64092006-08-01 16:21:11 +00002081
2082 count = count1;
2083 /* first read to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01002084 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00002085 if (len > count)
2086 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01002087 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00002088 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002089 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2090 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01002091 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
bellard83f64092006-08-01 16:21:11 +00002092 count -= len;
2093 if (count == 0)
2094 return count1;
2095 sector_num++;
2096 buf += len;
2097 }
2098
2099 /* read the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01002100 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00002101 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002102 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
2103 return ret;
bellard83f64092006-08-01 16:21:11 +00002104 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01002105 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00002106 buf += len;
2107 count -= len;
2108 }
2109
2110 /* add data from the last sector */
2111 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002112 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2113 return ret;
bellard83f64092006-08-01 16:21:11 +00002114 memcpy(buf, tmp_buf, count);
2115 }
2116 return count1;
2117}
2118
aliguorieda578e2009-03-12 19:57:16 +00002119int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
2120 const void *buf, int count1)
bellard83f64092006-08-01 16:21:11 +00002121{
Jan Kiszka6ea44302009-11-30 18:21:19 +01002122 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
bellard83f64092006-08-01 16:21:11 +00002123 int len, nb_sectors, count;
2124 int64_t sector_num;
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002125 int ret;
bellard83f64092006-08-01 16:21:11 +00002126
2127 count = count1;
2128 /* first write to align to sector start */
Jan Kiszka6ea44302009-11-30 18:21:19 +01002129 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
bellard83f64092006-08-01 16:21:11 +00002130 if (len > count)
2131 len = count;
Jan Kiszka6ea44302009-11-30 18:21:19 +01002132 sector_num = offset >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00002133 if (len > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002134 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2135 return ret;
Jan Kiszka6ea44302009-11-30 18:21:19 +01002136 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002137 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2138 return ret;
bellard83f64092006-08-01 16:21:11 +00002139 count -= len;
2140 if (count == 0)
2141 return count1;
2142 sector_num++;
2143 buf += len;
2144 }
2145
2146 /* write the sectors "in place" */
Jan Kiszka6ea44302009-11-30 18:21:19 +01002147 nb_sectors = count >> BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00002148 if (nb_sectors > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002149 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
2150 return ret;
bellard83f64092006-08-01 16:21:11 +00002151 sector_num += nb_sectors;
Jan Kiszka6ea44302009-11-30 18:21:19 +01002152 len = nb_sectors << BDRV_SECTOR_BITS;
bellard83f64092006-08-01 16:21:11 +00002153 buf += len;
2154 count -= len;
2155 }
2156
2157 /* add data from the last sector */
2158 if (count > 0) {
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002159 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
2160 return ret;
bellard83f64092006-08-01 16:21:11 +00002161 memcpy(tmp_buf, buf, count);
Kevin Wolf9a8c4cc2010-01-20 15:03:02 +01002162 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
2163 return ret;
bellard83f64092006-08-01 16:21:11 +00002164 }
2165 return count1;
2166}
bellard83f64092006-08-01 16:21:11 +00002167
Kevin Wolff08145f2010-06-16 16:38:15 +02002168/*
2169 * Writes to the file and ensures that no writes are reordered across this
2170 * request (acts as a barrier)
2171 *
2172 * Returns 0 on success, -errno in error cases.
2173 */
2174int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2175 const void *buf, int count)
2176{
2177 int ret;
2178
2179 ret = bdrv_pwrite(bs, offset, buf, count);
2180 if (ret < 0) {
2181 return ret;
2182 }
2183
Paolo Bonzinif05fa4a2012-06-06 00:04:49 +02002184 /* No flush needed for cache modes that already do it */
2185 if (bs->enable_write_cache) {
Kevin Wolff08145f2010-06-16 16:38:15 +02002186 bdrv_flush(bs);
2187 }
2188
2189 return 0;
2190}
2191
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002192static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
Stefan Hajnocziab185922011-11-17 13:40:31 +00002193 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2194{
2195 /* Perform I/O through a temporary buffer so that users who scribble over
2196 * their read buffer while the operation is in progress do not end up
2197 * modifying the image file. This is critical for zero-copy guest I/O
2198 * where anything might happen inside guest memory.
2199 */
2200 void *bounce_buffer;
2201
Stefan Hajnoczi79c053b2012-02-07 13:27:26 +00002202 BlockDriver *drv = bs->drv;
Stefan Hajnocziab185922011-11-17 13:40:31 +00002203 struct iovec iov;
2204 QEMUIOVector bounce_qiov;
2205 int64_t cluster_sector_num;
2206 int cluster_nb_sectors;
2207 size_t skip_bytes;
2208 int ret;
2209
2210 /* Cover entire cluster so no additional backing file I/O is required when
2211 * allocating cluster in the image file.
2212 */
2213 round_to_clusters(bs, sector_num, nb_sectors,
2214 &cluster_sector_num, &cluster_nb_sectors);
2215
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002216 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2217 cluster_sector_num, cluster_nb_sectors);
Stefan Hajnocziab185922011-11-17 13:40:31 +00002218
2219 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2220 iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2221 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2222
Stefan Hajnoczi79c053b2012-02-07 13:27:26 +00002223 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2224 &bounce_qiov);
Stefan Hajnocziab185922011-11-17 13:40:31 +00002225 if (ret < 0) {
2226 goto err;
2227 }
2228
Stefan Hajnoczi79c053b2012-02-07 13:27:26 +00002229 if (drv->bdrv_co_write_zeroes &&
2230 buffer_is_zero(bounce_buffer, iov.iov_len)) {
Kevin Wolf621f0582012-03-20 15:12:58 +01002231 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
2232 cluster_nb_sectors);
Stefan Hajnoczi79c053b2012-02-07 13:27:26 +00002233 } else {
Paolo Bonzinif05fa4a2012-06-06 00:04:49 +02002234 /* This does not change the data on the disk, it is not necessary
2235 * to flush even in cache=writethrough mode.
2236 */
Stefan Hajnoczi79c053b2012-02-07 13:27:26 +00002237 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
Stefan Hajnocziab185922011-11-17 13:40:31 +00002238 &bounce_qiov);
Stefan Hajnoczi79c053b2012-02-07 13:27:26 +00002239 }
2240
Stefan Hajnocziab185922011-11-17 13:40:31 +00002241 if (ret < 0) {
2242 /* It might be okay to ignore write errors for guest requests. If this
2243 * is a deliberate copy-on-read then we don't want to ignore the error.
2244 * Simply report it in all cases.
2245 */
2246 goto err;
2247 }
2248
2249 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
Michael Tokarev03396142012-06-07 20:17:55 +04002250 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2251 nb_sectors * BDRV_SECTOR_SIZE);
Stefan Hajnocziab185922011-11-17 13:40:31 +00002252
2253err:
2254 qemu_vfree(bounce_buffer);
2255 return ret;
2256}
2257
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002258/*
2259 * Handle a read request in coroutine context
2260 */
2261static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002262 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2263 BdrvRequestFlags flags)
Kevin Wolfda1fa912011-07-14 17:27:13 +02002264{
2265 BlockDriver *drv = bs->drv;
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002266 BdrvTrackedRequest req;
2267 int ret;
Kevin Wolfda1fa912011-07-14 17:27:13 +02002268
Kevin Wolfda1fa912011-07-14 17:27:13 +02002269 if (!drv) {
2270 return -ENOMEDIUM;
2271 }
2272 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2273 return -EIO;
2274 }
2275
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08002276 /* throttling disk read I/O */
2277 if (bs->io_limits_enabled) {
2278 bdrv_io_limits_intercept(bs, false, nb_sectors);
2279 }
2280
Stefan Hajnoczif4658282011-11-17 13:40:29 +00002281 if (bs->copy_on_read) {
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002282 flags |= BDRV_REQ_COPY_ON_READ;
2283 }
2284 if (flags & BDRV_REQ_COPY_ON_READ) {
2285 bs->copy_on_read_in_flight++;
2286 }
2287
2288 if (bs->copy_on_read_in_flight) {
Stefan Hajnoczif4658282011-11-17 13:40:29 +00002289 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2290 }
2291
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002292 tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
Stefan Hajnocziab185922011-11-17 13:40:31 +00002293
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002294 if (flags & BDRV_REQ_COPY_ON_READ) {
Stefan Hajnocziab185922011-11-17 13:40:31 +00002295 int pnum;
2296
2297 ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2298 if (ret < 0) {
2299 goto out;
2300 }
2301
2302 if (!ret || pnum != nb_sectors) {
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002303 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
Stefan Hajnocziab185922011-11-17 13:40:31 +00002304 goto out;
2305 }
2306 }
2307
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002308 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
Stefan Hajnocziab185922011-11-17 13:40:31 +00002309
2310out:
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002311 tracked_request_end(&req);
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002312
2313 if (flags & BDRV_REQ_COPY_ON_READ) {
2314 bs->copy_on_read_in_flight--;
2315 }
2316
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002317 return ret;
Kevin Wolfda1fa912011-07-14 17:27:13 +02002318}
2319
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002320int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
Kevin Wolfda1fa912011-07-14 17:27:13 +02002321 int nb_sectors, QEMUIOVector *qiov)
2322{
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002323 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
Kevin Wolfda1fa912011-07-14 17:27:13 +02002324
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002325 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2326}
2327
2328int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2329 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2330{
2331 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2332
2333 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2334 BDRV_REQ_COPY_ON_READ);
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002335}
2336
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00002337static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2338 int64_t sector_num, int nb_sectors)
2339{
2340 BlockDriver *drv = bs->drv;
2341 QEMUIOVector qiov;
2342 struct iovec iov;
2343 int ret;
2344
Kevin Wolf621f0582012-03-20 15:12:58 +01002345 /* TODO Emulate only part of misaligned requests instead of letting block
2346 * drivers return -ENOTSUP and emulate everything */
2347
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00002348 /* First try the efficient write zeroes operation */
2349 if (drv->bdrv_co_write_zeroes) {
Kevin Wolf621f0582012-03-20 15:12:58 +01002350 ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2351 if (ret != -ENOTSUP) {
2352 return ret;
2353 }
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00002354 }
2355
2356 /* Fall back to bounce buffer if write zeroes is unsupported */
2357 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2358 iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2359 memset(iov.iov_base, 0, iov.iov_len);
2360 qemu_iovec_init_external(&qiov, &iov, 1);
2361
2362 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2363
2364 qemu_vfree(iov.iov_base);
2365 return ret;
2366}
2367
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002368/*
2369 * Handle a write request in coroutine context
2370 */
2371static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00002372 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2373 BdrvRequestFlags flags)
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002374{
2375 BlockDriver *drv = bs->drv;
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002376 BdrvTrackedRequest req;
Stefan Hajnoczi6b7cb242011-10-13 13:08:24 +01002377 int ret;
Kevin Wolfda1fa912011-07-14 17:27:13 +02002378
2379 if (!bs->drv) {
2380 return -ENOMEDIUM;
2381 }
2382 if (bs->read_only) {
2383 return -EACCES;
2384 }
2385 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2386 return -EIO;
2387 }
2388
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08002389 /* throttling disk write I/O */
2390 if (bs->io_limits_enabled) {
2391 bdrv_io_limits_intercept(bs, true, nb_sectors);
2392 }
2393
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00002394 if (bs->copy_on_read_in_flight) {
Stefan Hajnoczif4658282011-11-17 13:40:29 +00002395 wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2396 }
2397
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002398 tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2399
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00002400 if (flags & BDRV_REQ_ZERO_WRITE) {
2401 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2402 } else {
2403 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2404 }
Stefan Hajnoczi6b7cb242011-10-13 13:08:24 +01002405
Paolo Bonzinif05fa4a2012-06-06 00:04:49 +02002406 if (ret == 0 && !bs->enable_write_cache) {
2407 ret = bdrv_co_flush(bs);
2408 }
2409
Kevin Wolfda1fa912011-07-14 17:27:13 +02002410 if (bs->dirty_bitmap) {
Paolo Bonzini1755da12012-10-18 16:49:18 +02002411 bdrv_set_dirty(bs, sector_num, nb_sectors);
Kevin Wolfda1fa912011-07-14 17:27:13 +02002412 }
2413
2414 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2415 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2416 }
2417
Stefan Hajnoczidbffbdc2011-11-17 13:40:27 +00002418 tracked_request_end(&req);
2419
Stefan Hajnoczi6b7cb242011-10-13 13:08:24 +01002420 return ret;
Kevin Wolfda1fa912011-07-14 17:27:13 +02002421}
2422
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002423int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2424 int nb_sectors, QEMUIOVector *qiov)
2425{
2426 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2427
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00002428 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2429}
2430
2431int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2432 int64_t sector_num, int nb_sectors)
2433{
2434 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2435
2436 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2437 BDRV_REQ_ZERO_WRITE);
Stefan Hajnoczic5fbe572011-10-05 17:17:03 +01002438}
2439
bellard83f64092006-08-01 16:21:11 +00002440/**
bellard83f64092006-08-01 16:21:11 +00002441 * Truncate file to 'offset' bytes (needed only for file protocols)
2442 */
2443int bdrv_truncate(BlockDriverState *bs, int64_t offset)
2444{
2445 BlockDriver *drv = bs->drv;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01002446 int ret;
bellard83f64092006-08-01 16:21:11 +00002447 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002448 return -ENOMEDIUM;
bellard83f64092006-08-01 16:21:11 +00002449 if (!drv->bdrv_truncate)
2450 return -ENOTSUP;
Naphtali Sprei59f26892009-10-26 16:25:16 +02002451 if (bs->read_only)
2452 return -EACCES;
Marcelo Tosatti85916752011-01-26 12:12:35 -02002453 if (bdrv_in_use(bs))
2454 return -EBUSY;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01002455 ret = drv->bdrv_truncate(bs, offset);
2456 if (ret == 0) {
2457 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
Markus Armbruster145feb12011-08-03 15:07:42 +02002458 bdrv_dev_resize_cb(bs);
Stefan Hajnoczi51762282010-04-19 16:56:41 +01002459 }
2460 return ret;
bellard83f64092006-08-01 16:21:11 +00002461}
2462
2463/**
Fam Zheng4a1d5e12011-07-12 19:56:39 +08002464 * Length of a allocated file in bytes. Sparse files are counted by actual
2465 * allocated space. Return < 0 if error or unknown.
2466 */
2467int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
2468{
2469 BlockDriver *drv = bs->drv;
2470 if (!drv) {
2471 return -ENOMEDIUM;
2472 }
2473 if (drv->bdrv_get_allocated_file_size) {
2474 return drv->bdrv_get_allocated_file_size(bs);
2475 }
2476 if (bs->file) {
2477 return bdrv_get_allocated_file_size(bs->file);
2478 }
2479 return -ENOTSUP;
2480}
2481
2482/**
bellard83f64092006-08-01 16:21:11 +00002483 * Length of a file in bytes. Return < 0 if error or unknown.
2484 */
2485int64_t bdrv_getlength(BlockDriverState *bs)
2486{
2487 BlockDriver *drv = bs->drv;
2488 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002489 return -ENOMEDIUM;
Stefan Hajnoczi51762282010-04-19 16:56:41 +01002490
Markus Armbruster2c6942f2011-09-06 18:58:51 +02002491 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01002492 if (drv->bdrv_getlength) {
2493 return drv->bdrv_getlength(bs);
2494 }
bellard83f64092006-08-01 16:21:11 +00002495 }
Stefan Hajnoczi46a4e4e2011-03-29 20:04:41 +01002496 return bs->total_sectors * BDRV_SECTOR_SIZE;
bellardfc01f7e2003-06-30 10:03:06 +00002497}
2498
bellard19cb3732006-08-19 11:45:59 +00002499/* return 0 as number of sectors if no device present or error */
ths96b8f132007-12-17 01:35:20 +00002500void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
bellardfc01f7e2003-06-30 10:03:06 +00002501{
bellard19cb3732006-08-19 11:45:59 +00002502 int64_t length;
2503 length = bdrv_getlength(bs);
2504 if (length < 0)
2505 length = 0;
2506 else
Jan Kiszka6ea44302009-11-30 18:21:19 +01002507 length = length >> BDRV_SECTOR_BITS;
bellard19cb3732006-08-19 11:45:59 +00002508 *nb_sectors_ptr = length;
bellardfc01f7e2003-06-30 10:03:06 +00002509}
bellardcf989512004-02-16 21:56:36 +00002510
Zhi Yong Wu0563e192011-11-03 16:57:25 +08002511/* throttling disk io limits */
2512void bdrv_set_io_limits(BlockDriverState *bs,
2513 BlockIOLimit *io_limits)
2514{
2515 bs->io_limits = *io_limits;
2516 bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
2517}
2518
Paolo Bonziniff06f5f2012-09-28 17:22:54 +02002519void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2520 BlockdevOnError on_write_error)
Markus Armbrusterabd7f682010-06-02 18:55:17 +02002521{
2522 bs->on_read_error = on_read_error;
2523 bs->on_write_error = on_write_error;
2524}
2525
Paolo Bonzini1ceee0d2012-09-28 17:22:56 +02002526BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
Markus Armbrusterabd7f682010-06-02 18:55:17 +02002527{
2528 return is_read ? bs->on_read_error : bs->on_write_error;
2529}
2530
Paolo Bonzini3e1caa52012-09-28 17:22:57 +02002531BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
2532{
2533 BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
2534
2535 switch (on_err) {
2536 case BLOCKDEV_ON_ERROR_ENOSPC:
2537 return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
2538 case BLOCKDEV_ON_ERROR_STOP:
2539 return BDRV_ACTION_STOP;
2540 case BLOCKDEV_ON_ERROR_REPORT:
2541 return BDRV_ACTION_REPORT;
2542 case BLOCKDEV_ON_ERROR_IGNORE:
2543 return BDRV_ACTION_IGNORE;
2544 default:
2545 abort();
2546 }
2547}
2548
2549/* This is done by device models because, while the block layer knows
2550 * about the error, it does not know whether an operation comes from
2551 * the device or the block layer (from a job, for example).
2552 */
2553void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
2554 bool is_read, int error)
2555{
2556 assert(error >= 0);
Paolo Bonzini32c81a42012-09-28 17:22:58 +02002557 bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
Paolo Bonzini3e1caa52012-09-28 17:22:57 +02002558 if (action == BDRV_ACTION_STOP) {
2559 vm_stop(RUN_STATE_IO_ERROR);
2560 bdrv_iostatus_set_err(bs, error);
2561 }
2562}
2563
bellardb3380822004-03-14 21:38:54 +00002564int bdrv_is_read_only(BlockDriverState *bs)
2565{
2566 return bs->read_only;
2567}
2568
ths985a03b2007-12-24 16:10:43 +00002569int bdrv_is_sg(BlockDriverState *bs)
2570{
2571 return bs->sg;
2572}
2573
Christoph Hellwige900a7b2009-09-04 19:01:15 +02002574int bdrv_enable_write_cache(BlockDriverState *bs)
2575{
2576 return bs->enable_write_cache;
2577}
2578
Paolo Bonzini425b0142012-06-06 00:04:52 +02002579void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2580{
2581 bs->enable_write_cache = wce;
Jeff Cody55b110f2012-09-20 15:13:18 -04002582
2583 /* so a reopen() will preserve wce */
2584 if (wce) {
2585 bs->open_flags |= BDRV_O_CACHE_WB;
2586 } else {
2587 bs->open_flags &= ~BDRV_O_CACHE_WB;
2588 }
Paolo Bonzini425b0142012-06-06 00:04:52 +02002589}
2590
bellardea2384d2004-08-01 21:59:26 +00002591int bdrv_is_encrypted(BlockDriverState *bs)
2592{
2593 if (bs->backing_hd && bs->backing_hd->encrypted)
2594 return 1;
2595 return bs->encrypted;
2596}
2597
aliguoric0f4ce72009-03-05 23:01:01 +00002598int bdrv_key_required(BlockDriverState *bs)
2599{
2600 BlockDriverState *backing_hd = bs->backing_hd;
2601
2602 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2603 return 1;
2604 return (bs->encrypted && !bs->valid_key);
2605}
2606
bellardea2384d2004-08-01 21:59:26 +00002607int bdrv_set_key(BlockDriverState *bs, const char *key)
2608{
2609 int ret;
2610 if (bs->backing_hd && bs->backing_hd->encrypted) {
2611 ret = bdrv_set_key(bs->backing_hd, key);
2612 if (ret < 0)
2613 return ret;
2614 if (!bs->encrypted)
2615 return 0;
2616 }
Shahar Havivifd04a2a2010-03-06 00:26:13 +02002617 if (!bs->encrypted) {
2618 return -EINVAL;
2619 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2620 return -ENOMEDIUM;
2621 }
aliguoric0f4ce72009-03-05 23:01:01 +00002622 ret = bs->drv->bdrv_set_key(bs, key);
aliguoribb5fc202009-03-05 23:01:15 +00002623 if (ret < 0) {
2624 bs->valid_key = 0;
2625 } else if (!bs->valid_key) {
2626 bs->valid_key = 1;
2627 /* call the change callback now, we skipped it on open */
Markus Armbruster7d4b4ba2011-09-06 18:58:59 +02002628 bdrv_dev_change_media_cb(bs, true);
aliguoribb5fc202009-03-05 23:01:15 +00002629 }
aliguoric0f4ce72009-03-05 23:01:01 +00002630 return ret;
bellardea2384d2004-08-01 21:59:26 +00002631}
2632
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02002633const char *bdrv_get_format_name(BlockDriverState *bs)
bellardea2384d2004-08-01 21:59:26 +00002634{
Markus Armbrusterf8d6bba2012-06-13 10:11:48 +02002635 return bs->drv ? bs->drv->format_name : NULL;
bellardea2384d2004-08-01 21:59:26 +00002636}
2637
ths5fafdf22007-09-16 21:08:06 +00002638void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
bellardea2384d2004-08-01 21:59:26 +00002639 void *opaque)
2640{
2641 BlockDriver *drv;
2642
Stefan Hajnoczi8a22f022010-04-13 10:29:33 +01002643 QLIST_FOREACH(drv, &bdrv_drivers, list) {
bellardea2384d2004-08-01 21:59:26 +00002644 it(opaque, drv->format_name);
2645 }
2646}
2647
bellardb3380822004-03-14 21:38:54 +00002648BlockDriverState *bdrv_find(const char *name)
2649{
2650 BlockDriverState *bs;
2651
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002652 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2653 if (!strcmp(name, bs->device_name)) {
bellardb3380822004-03-14 21:38:54 +00002654 return bs;
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002655 }
bellardb3380822004-03-14 21:38:54 +00002656 }
2657 return NULL;
2658}
2659
Markus Armbruster2f399b02010-06-02 18:55:20 +02002660BlockDriverState *bdrv_next(BlockDriverState *bs)
2661{
2662 if (!bs) {
2663 return QTAILQ_FIRST(&bdrv_states);
2664 }
2665 return QTAILQ_NEXT(bs, list);
2666}
2667
aliguori51de9762009-03-05 23:00:43 +00002668void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
bellard81d09122004-07-14 17:21:37 +00002669{
2670 BlockDriverState *bs;
2671
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002672 QTAILQ_FOREACH(bs, &bdrv_states, list) {
aliguori51de9762009-03-05 23:00:43 +00002673 it(opaque, bs);
bellard81d09122004-07-14 17:21:37 +00002674 }
2675}
2676
bellardea2384d2004-08-01 21:59:26 +00002677const char *bdrv_get_device_name(BlockDriverState *bs)
2678{
2679 return bs->device_name;
2680}
2681
Markus Armbrusterc8433282012-06-05 16:49:24 +02002682int bdrv_get_flags(BlockDriverState *bs)
2683{
2684 return bs->open_flags;
2685}
2686
aliguoric6ca28d2008-10-06 13:55:43 +00002687void bdrv_flush_all(void)
2688{
2689 BlockDriverState *bs;
2690
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002691 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Paolo Bonzini29cdb252012-03-12 18:26:01 +01002692 bdrv_flush(bs);
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002693 }
aliguoric6ca28d2008-10-06 13:55:43 +00002694}
2695
Kevin Wolff2feebb2010-04-14 17:30:35 +02002696int bdrv_has_zero_init(BlockDriverState *bs)
2697{
2698 assert(bs->drv);
2699
Kevin Wolf336c1c12010-07-28 11:26:29 +02002700 if (bs->drv->bdrv_has_zero_init) {
2701 return bs->drv->bdrv_has_zero_init(bs);
Kevin Wolff2feebb2010-04-14 17:30:35 +02002702 }
2703
2704 return 1;
2705}
2706
Stefan Hajnoczi376ae3f2011-11-14 12:44:19 +00002707typedef struct BdrvCoIsAllocatedData {
2708 BlockDriverState *bs;
2709 int64_t sector_num;
2710 int nb_sectors;
2711 int *pnum;
2712 int ret;
2713 bool done;
2714} BdrvCoIsAllocatedData;
2715
thsf58c7b32008-06-05 21:53:49 +00002716/*
2717 * Returns true iff the specified sector is present in the disk image. Drivers
2718 * not implementing the functionality are assumed to not support backing files,
2719 * hence all their sectors are reported as allocated.
2720 *
Stefan Hajnoczibd9533e2011-11-29 13:49:51 +00002721 * If 'sector_num' is beyond the end of the disk image the return value is 0
2722 * and 'pnum' is set to 0.
2723 *
thsf58c7b32008-06-05 21:53:49 +00002724 * 'pnum' is set to the number of sectors (including and immediately following
2725 * the specified sector) that are known to be in the same
2726 * allocated/unallocated state.
2727 *
Stefan Hajnoczibd9533e2011-11-29 13:49:51 +00002728 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
2729 * beyond the end of the disk image it will be clamped.
thsf58c7b32008-06-05 21:53:49 +00002730 */
Stefan Hajnoczi060f51c2011-11-14 12:44:26 +00002731int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2732 int nb_sectors, int *pnum)
thsf58c7b32008-06-05 21:53:49 +00002733{
Stefan Hajnoczibd9533e2011-11-29 13:49:51 +00002734 int64_t n;
2735
2736 if (sector_num >= bs->total_sectors) {
2737 *pnum = 0;
2738 return 0;
2739 }
2740
2741 n = bs->total_sectors - sector_num;
2742 if (n < nb_sectors) {
2743 nb_sectors = n;
2744 }
2745
Stefan Hajnoczi6aebab12011-11-14 12:44:25 +00002746 if (!bs->drv->bdrv_co_is_allocated) {
Stefan Hajnoczibd9533e2011-11-29 13:49:51 +00002747 *pnum = nb_sectors;
thsf58c7b32008-06-05 21:53:49 +00002748 return 1;
2749 }
Stefan Hajnoczi6aebab12011-11-14 12:44:25 +00002750
Stefan Hajnoczi060f51c2011-11-14 12:44:26 +00002751 return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2752}
2753
2754/* Coroutine wrapper for bdrv_is_allocated() */
2755static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2756{
2757 BdrvCoIsAllocatedData *data = opaque;
2758 BlockDriverState *bs = data->bs;
2759
2760 data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2761 data->pnum);
2762 data->done = true;
2763}
2764
2765/*
2766 * Synchronous wrapper around bdrv_co_is_allocated().
2767 *
2768 * See bdrv_co_is_allocated() for details.
2769 */
2770int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2771 int *pnum)
2772{
Stefan Hajnoczi6aebab12011-11-14 12:44:25 +00002773 Coroutine *co;
2774 BdrvCoIsAllocatedData data = {
2775 .bs = bs,
2776 .sector_num = sector_num,
2777 .nb_sectors = nb_sectors,
2778 .pnum = pnum,
2779 .done = false,
2780 };
2781
2782 co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
2783 qemu_coroutine_enter(co, &data);
2784 while (!data.done) {
2785 qemu_aio_wait();
2786 }
2787 return data.ret;
thsf58c7b32008-06-05 21:53:49 +00002788}
2789
Paolo Bonzini188a7bb2012-05-08 16:52:01 +02002790/*
2791 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2792 *
2793 * Return true if the given sector is allocated in any image between
2794 * BASE and TOP (inclusive). BASE can be NULL to check if the given
2795 * sector is allocated in any image of the chain. Return false otherwise.
2796 *
2797 * 'pnum' is set to the number of sectors (including and immediately following
2798 * the specified sector) that are known to be in the same
2799 * allocated/unallocated state.
2800 *
2801 */
2802int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
2803 BlockDriverState *base,
2804 int64_t sector_num,
2805 int nb_sectors, int *pnum)
2806{
2807 BlockDriverState *intermediate;
2808 int ret, n = nb_sectors;
2809
2810 intermediate = top;
2811 while (intermediate && intermediate != base) {
2812 int pnum_inter;
2813 ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
2814 &pnum_inter);
2815 if (ret < 0) {
2816 return ret;
2817 } else if (ret) {
2818 *pnum = pnum_inter;
2819 return 1;
2820 }
2821
2822 /*
2823 * [sector_num, nb_sectors] is unallocated on top but intermediate
2824 * might have
2825 *
2826 * [sector_num+x, nr_sectors] allocated.
2827 */
2828 if (n > pnum_inter) {
2829 n = pnum_inter;
2830 }
2831
2832 intermediate = intermediate->backing_hd;
2833 }
2834
2835 *pnum = n;
2836 return 0;
2837}
2838
Paolo Bonziniac84ada2012-10-18 16:49:15 +02002839BlockInfo *bdrv_query_info(BlockDriverState *bs)
2840{
2841 BlockInfo *info = g_malloc0(sizeof(*info));
2842 info->device = g_strdup(bs->device_name);
2843 info->type = g_strdup("unknown");
2844 info->locked = bdrv_dev_is_medium_locked(bs);
2845 info->removable = bdrv_dev_has_removable_media(bs);
2846
2847 if (bdrv_dev_has_removable_media(bs)) {
2848 info->has_tray_open = true;
2849 info->tray_open = bdrv_dev_is_tray_open(bs);
2850 }
2851
2852 if (bdrv_iostatus_is_enabled(bs)) {
2853 info->has_io_status = true;
2854 info->io_status = bs->iostatus;
2855 }
2856
Paolo Bonzinib9a9b3a2012-08-01 15:23:44 +02002857 if (bs->dirty_bitmap) {
2858 info->has_dirty = true;
2859 info->dirty = g_malloc0(sizeof(*info->dirty));
2860 info->dirty->count = bdrv_get_dirty_count(bs) *
2861 BDRV_SECTORS_PER_DIRTY_CHUNK * BDRV_SECTOR_SIZE;
2862 }
2863
Paolo Bonziniac84ada2012-10-18 16:49:15 +02002864 if (bs->drv) {
2865 info->has_inserted = true;
2866 info->inserted = g_malloc0(sizeof(*info->inserted));
2867 info->inserted->file = g_strdup(bs->filename);
2868 info->inserted->ro = bs->read_only;
2869 info->inserted->drv = g_strdup(bs->drv->format_name);
2870 info->inserted->encrypted = bs->encrypted;
2871 info->inserted->encryption_key_missing = bdrv_key_required(bs);
2872
2873 if (bs->backing_file[0]) {
2874 info->inserted->has_backing_file = true;
2875 info->inserted->backing_file = g_strdup(bs->backing_file);
2876 }
2877
2878 info->inserted->backing_file_depth = bdrv_get_backing_file_depth(bs);
2879
2880 if (bs->io_limits_enabled) {
2881 info->inserted->bps =
2882 bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
2883 info->inserted->bps_rd =
2884 bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
2885 info->inserted->bps_wr =
2886 bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
2887 info->inserted->iops =
2888 bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
2889 info->inserted->iops_rd =
2890 bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
2891 info->inserted->iops_wr =
2892 bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
2893 }
2894 }
2895 return info;
2896}
2897
Luiz Capitulinob2023812011-09-21 17:16:47 -03002898BlockInfoList *qmp_query_block(Error **errp)
bellardb3380822004-03-14 21:38:54 +00002899{
Paolo Bonziniac84ada2012-10-18 16:49:15 +02002900 BlockInfoList *head = NULL, **p_next = &head;
bellardb3380822004-03-14 21:38:54 +00002901 BlockDriverState *bs;
2902
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002903 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinob2023812011-09-21 17:16:47 -03002904 BlockInfoList *info = g_malloc0(sizeof(*info));
Paolo Bonziniac84ada2012-10-18 16:49:15 +02002905 info->value = bdrv_query_info(bs);
Luiz Capitulinod15e5462009-12-10 17:16:06 -02002906
Paolo Bonziniac84ada2012-10-18 16:49:15 +02002907 *p_next = info;
2908 p_next = &info->next;
bellardb3380822004-03-14 21:38:54 +00002909 }
Luiz Capitulinod15e5462009-12-10 17:16:06 -02002910
Luiz Capitulinob2023812011-09-21 17:16:47 -03002911 return head;
bellardb3380822004-03-14 21:38:54 +00002912}
thsa36e69d2007-12-02 05:18:19 +00002913
Paolo Bonzini9887b612012-10-18 16:49:16 +02002914BlockStats *bdrv_query_stats(const BlockDriverState *bs)
thsa36e69d2007-12-02 05:18:19 +00002915{
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002916 BlockStats *s;
Luiz Capitulino218a5362009-12-10 17:16:07 -02002917
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002918 s = g_malloc0(sizeof(*s));
Luiz Capitulino218a5362009-12-10 17:16:07 -02002919
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002920 if (bs->device_name[0]) {
2921 s->has_device = true;
2922 s->device = g_strdup(bs->device_name);
Kevin Wolf294cc352010-04-28 14:34:01 +02002923 }
2924
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002925 s->stats = g_malloc0(sizeof(*s->stats));
2926 s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
2927 s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
2928 s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
2929 s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
2930 s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
2931 s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
2932 s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
2933 s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
2934 s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
2935
Kevin Wolf294cc352010-04-28 14:34:01 +02002936 if (bs->file) {
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002937 s->has_parent = true;
Paolo Bonzini9887b612012-10-18 16:49:16 +02002938 s->parent = bdrv_query_stats(bs->file);
Kevin Wolf294cc352010-04-28 14:34:01 +02002939 }
2940
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002941 return s;
Kevin Wolf294cc352010-04-28 14:34:01 +02002942}
2943
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002944BlockStatsList *qmp_query_blockstats(Error **errp)
Luiz Capitulino218a5362009-12-10 17:16:07 -02002945{
Paolo Bonzini9887b612012-10-18 16:49:16 +02002946 BlockStatsList *head = NULL, **p_next = &head;
thsa36e69d2007-12-02 05:18:19 +00002947 BlockDriverState *bs;
2948
Stefan Hajnoczi1b7bdbc2010-04-10 07:02:42 +01002949 QTAILQ_FOREACH(bs, &bdrv_states, list) {
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002950 BlockStatsList *info = g_malloc0(sizeof(*info));
Paolo Bonzini9887b612012-10-18 16:49:16 +02002951 info->value = bdrv_query_stats(bs);
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002952
Paolo Bonzini9887b612012-10-18 16:49:16 +02002953 *p_next = info;
2954 p_next = &info->next;
thsa36e69d2007-12-02 05:18:19 +00002955 }
Luiz Capitulino218a5362009-12-10 17:16:07 -02002956
Luiz Capitulinof11f57e2011-09-22 15:56:36 -03002957 return head;
thsa36e69d2007-12-02 05:18:19 +00002958}
bellardea2384d2004-08-01 21:59:26 +00002959
aliguori045df332009-03-05 23:00:48 +00002960const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2961{
2962 if (bs->backing_hd && bs->backing_hd->encrypted)
2963 return bs->backing_file;
2964 else if (bs->encrypted)
2965 return bs->filename;
2966 else
2967 return NULL;
2968}
2969
ths5fafdf22007-09-16 21:08:06 +00002970void bdrv_get_backing_filename(BlockDriverState *bs,
bellard83f64092006-08-01 16:21:11 +00002971 char *filename, int filename_size)
bellardea2384d2004-08-01 21:59:26 +00002972{
Kevin Wolf3574c602011-10-26 11:02:11 +02002973 pstrcpy(filename, filename_size, bs->backing_file);
bellardea2384d2004-08-01 21:59:26 +00002974}
2975
ths5fafdf22007-09-16 21:08:06 +00002976int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
bellardfaea38e2006-08-05 21:31:00 +00002977 const uint8_t *buf, int nb_sectors)
2978{
2979 BlockDriver *drv = bs->drv;
2980 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002981 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002982 if (!drv->bdrv_write_compressed)
2983 return -ENOTSUP;
Kevin Wolffbb7b4e2009-05-08 14:47:24 +02002984 if (bdrv_check_request(bs, sector_num, nb_sectors))
2985 return -EIO;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002986
Paolo Bonzini1755da12012-10-18 16:49:18 +02002987 assert(!bs->dirty_bitmap);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01002988
bellardfaea38e2006-08-05 21:31:00 +00002989 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2990}
ths3b46e622007-09-17 08:09:54 +00002991
bellardfaea38e2006-08-05 21:31:00 +00002992int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2993{
2994 BlockDriver *drv = bs->drv;
2995 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00002996 return -ENOMEDIUM;
bellardfaea38e2006-08-05 21:31:00 +00002997 if (!drv->bdrv_get_info)
2998 return -ENOTSUP;
2999 memset(bdi, 0, sizeof(*bdi));
3000 return drv->bdrv_get_info(bs, bdi);
3001}
3002
Christoph Hellwig45566e92009-07-10 23:11:57 +02003003int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
3004 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00003005{
3006 BlockDriver *drv = bs->drv;
3007 if (!drv)
3008 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09003009 if (drv->bdrv_save_vmstate)
3010 return drv->bdrv_save_vmstate(bs, buf, pos, size);
3011 if (bs->file)
3012 return bdrv_save_vmstate(bs->file, buf, pos, size);
3013 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00003014}
3015
Christoph Hellwig45566e92009-07-10 23:11:57 +02003016int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
3017 int64_t pos, int size)
aliguori178e08a2009-04-05 19:10:55 +00003018{
3019 BlockDriver *drv = bs->drv;
3020 if (!drv)
3021 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09003022 if (drv->bdrv_load_vmstate)
3023 return drv->bdrv_load_vmstate(bs, buf, pos, size);
3024 if (bs->file)
3025 return bdrv_load_vmstate(bs->file, buf, pos, size);
3026 return -ENOTSUP;
aliguori178e08a2009-04-05 19:10:55 +00003027}
3028
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003029void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
3030{
3031 BlockDriver *drv = bs->drv;
3032
3033 if (!drv || !drv->bdrv_debug_event) {
3034 return;
3035 }
3036
Blue Swirl0ed8b6f2012-07-08 06:56:53 +00003037 drv->bdrv_debug_event(bs, event);
Kevin Wolf8b9b0cc2010-03-15 17:27:00 +01003038
3039}
3040
bellardfaea38e2006-08-05 21:31:00 +00003041/**************************************************************/
3042/* handling of snapshots */
3043
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03003044int bdrv_can_snapshot(BlockDriverState *bs)
3045{
3046 BlockDriver *drv = bs->drv;
Markus Armbruster07b70bf2011-08-03 15:08:11 +02003047 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
Miguel Di Ciurcio Filhofeeee5a2010-06-08 10:40:55 -03003048 return 0;
3049 }
3050
3051 if (!drv->bdrv_snapshot_create) {
3052 if (bs->file != NULL) {
3053 return bdrv_can_snapshot(bs->file);
3054 }
3055 return 0;
3056 }
3057
3058 return 1;
3059}
3060
Blue Swirl199630b2010-07-25 20:49:34 +00003061int bdrv_is_snapshot(BlockDriverState *bs)
3062{
3063 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3064}
3065
Markus Armbrusterf9092b12010-06-25 10:33:39 +02003066BlockDriverState *bdrv_snapshots(void)
3067{
3068 BlockDriverState *bs;
3069
Markus Armbruster3ac906f2010-07-01 09:30:38 +02003070 if (bs_snapshots) {
Markus Armbrusterf9092b12010-06-25 10:33:39 +02003071 return bs_snapshots;
Markus Armbruster3ac906f2010-07-01 09:30:38 +02003072 }
Markus Armbrusterf9092b12010-06-25 10:33:39 +02003073
3074 bs = NULL;
3075 while ((bs = bdrv_next(bs))) {
3076 if (bdrv_can_snapshot(bs)) {
Markus Armbruster3ac906f2010-07-01 09:30:38 +02003077 bs_snapshots = bs;
3078 return bs;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02003079 }
3080 }
3081 return NULL;
Markus Armbrusterf9092b12010-06-25 10:33:39 +02003082}
3083
ths5fafdf22007-09-16 21:08:06 +00003084int bdrv_snapshot_create(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00003085 QEMUSnapshotInfo *sn_info)
3086{
3087 BlockDriver *drv = bs->drv;
3088 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003089 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09003090 if (drv->bdrv_snapshot_create)
3091 return drv->bdrv_snapshot_create(bs, sn_info);
3092 if (bs->file)
3093 return bdrv_snapshot_create(bs->file, sn_info);
3094 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00003095}
3096
ths5fafdf22007-09-16 21:08:06 +00003097int bdrv_snapshot_goto(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00003098 const char *snapshot_id)
3099{
3100 BlockDriver *drv = bs->drv;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09003101 int ret, open_ret;
3102
bellardfaea38e2006-08-05 21:31:00 +00003103 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003104 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09003105 if (drv->bdrv_snapshot_goto)
3106 return drv->bdrv_snapshot_goto(bs, snapshot_id);
3107
3108 if (bs->file) {
3109 drv->bdrv_close(bs);
3110 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
3111 open_ret = drv->bdrv_open(bs, bs->open_flags);
3112 if (open_ret < 0) {
3113 bdrv_delete(bs->file);
3114 bs->drv = NULL;
3115 return open_ret;
3116 }
3117 return ret;
3118 }
3119
3120 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00003121}
3122
3123int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
3124{
3125 BlockDriver *drv = bs->drv;
3126 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003127 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09003128 if (drv->bdrv_snapshot_delete)
3129 return drv->bdrv_snapshot_delete(bs, snapshot_id);
3130 if (bs->file)
3131 return bdrv_snapshot_delete(bs->file, snapshot_id);
3132 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00003133}
3134
ths5fafdf22007-09-16 21:08:06 +00003135int bdrv_snapshot_list(BlockDriverState *bs,
bellardfaea38e2006-08-05 21:31:00 +00003136 QEMUSnapshotInfo **psn_info)
3137{
3138 BlockDriver *drv = bs->drv;
3139 if (!drv)
bellard19cb3732006-08-19 11:45:59 +00003140 return -ENOMEDIUM;
MORITA Kazutaka7cdb1f62010-05-28 11:44:58 +09003141 if (drv->bdrv_snapshot_list)
3142 return drv->bdrv_snapshot_list(bs, psn_info);
3143 if (bs->file)
3144 return bdrv_snapshot_list(bs->file, psn_info);
3145 return -ENOTSUP;
bellardfaea38e2006-08-05 21:31:00 +00003146}
3147
edison51ef6722010-09-21 19:58:41 -07003148int bdrv_snapshot_load_tmp(BlockDriverState *bs,
3149 const char *snapshot_name)
3150{
3151 BlockDriver *drv = bs->drv;
3152 if (!drv) {
3153 return -ENOMEDIUM;
3154 }
3155 if (!bs->read_only) {
3156 return -EINVAL;
3157 }
3158 if (drv->bdrv_snapshot_load_tmp) {
3159 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
3160 }
3161 return -ENOTSUP;
3162}
3163
Jeff Codyb1b1d782012-10-16 15:49:09 -04003164/* backing_file can either be relative, or absolute, or a protocol. If it is
3165 * relative, it must be relative to the chain. So, passing in bs->filename
3166 * from a BDS as backing_file should not be done, as that may be relative to
3167 * the CWD rather than the chain. */
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003168BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3169 const char *backing_file)
3170{
Jeff Codyb1b1d782012-10-16 15:49:09 -04003171 char *filename_full = NULL;
3172 char *backing_file_full = NULL;
3173 char *filename_tmp = NULL;
3174 int is_protocol = 0;
3175 BlockDriverState *curr_bs = NULL;
3176 BlockDriverState *retval = NULL;
3177
3178 if (!bs || !bs->drv || !backing_file) {
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003179 return NULL;
3180 }
3181
Jeff Codyb1b1d782012-10-16 15:49:09 -04003182 filename_full = g_malloc(PATH_MAX);
3183 backing_file_full = g_malloc(PATH_MAX);
3184 filename_tmp = g_malloc(PATH_MAX);
3185
3186 is_protocol = path_has_protocol(backing_file);
3187
3188 for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3189
3190 /* If either of the filename paths is actually a protocol, then
3191 * compare unmodified paths; otherwise make paths relative */
3192 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3193 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3194 retval = curr_bs->backing_hd;
3195 break;
3196 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003197 } else {
Jeff Codyb1b1d782012-10-16 15:49:09 -04003198 /* If not an absolute filename path, make it relative to the current
3199 * image's filename path */
3200 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3201 backing_file);
3202
3203 /* We are going to compare absolute pathnames */
3204 if (!realpath(filename_tmp, filename_full)) {
3205 continue;
3206 }
3207
3208 /* We need to make sure the backing filename we are comparing against
3209 * is relative to the current image filename (or absolute) */
3210 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3211 curr_bs->backing_file);
3212
3213 if (!realpath(filename_tmp, backing_file_full)) {
3214 continue;
3215 }
3216
3217 if (strcmp(backing_file_full, filename_full) == 0) {
3218 retval = curr_bs->backing_hd;
3219 break;
3220 }
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003221 }
3222 }
3223
Jeff Codyb1b1d782012-10-16 15:49:09 -04003224 g_free(filename_full);
3225 g_free(backing_file_full);
3226 g_free(filename_tmp);
3227 return retval;
Marcelo Tosattie8a6bb92012-01-18 14:40:51 +00003228}
3229
Benoît Canetf198fd12012-08-02 10:22:47 +02003230int bdrv_get_backing_file_depth(BlockDriverState *bs)
3231{
3232 if (!bs->drv) {
3233 return 0;
3234 }
3235
3236 if (!bs->backing_hd) {
3237 return 0;
3238 }
3239
3240 return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3241}
3242
Jeff Cody79fac562012-09-27 13:29:15 -04003243BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3244{
3245 BlockDriverState *curr_bs = NULL;
3246
3247 if (!bs) {
3248 return NULL;
3249 }
3250
3251 curr_bs = bs;
3252
3253 while (curr_bs->backing_hd) {
3254 curr_bs = curr_bs->backing_hd;
3255 }
3256 return curr_bs;
3257}
3258
bellardfaea38e2006-08-05 21:31:00 +00003259#define NB_SUFFIXES 4
3260
3261char *get_human_readable_size(char *buf, int buf_size, int64_t size)
3262{
3263 static const char suffixes[NB_SUFFIXES] = "KMGT";
3264 int64_t base;
3265 int i;
3266
3267 if (size <= 999) {
3268 snprintf(buf, buf_size, "%" PRId64, size);
3269 } else {
3270 base = 1024;
3271 for(i = 0; i < NB_SUFFIXES; i++) {
3272 if (size < (10 * base)) {
ths5fafdf22007-09-16 21:08:06 +00003273 snprintf(buf, buf_size, "%0.1f%c",
bellardfaea38e2006-08-05 21:31:00 +00003274 (double)size / base,
3275 suffixes[i]);
3276 break;
3277 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
ths5fafdf22007-09-16 21:08:06 +00003278 snprintf(buf, buf_size, "%" PRId64 "%c",
bellardfaea38e2006-08-05 21:31:00 +00003279 ((size + (base >> 1)) / base),
3280 suffixes[i]);
3281 break;
3282 }
3283 base = base * 1024;
3284 }
3285 }
3286 return buf;
3287}
3288
3289char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
3290{
3291 char buf1[128], date_buf[128], clock_buf[128];
bellard3b9f94e2007-01-07 17:27:07 +00003292#ifdef _WIN32
3293 struct tm *ptm;
3294#else
bellardfaea38e2006-08-05 21:31:00 +00003295 struct tm tm;
bellard3b9f94e2007-01-07 17:27:07 +00003296#endif
bellardfaea38e2006-08-05 21:31:00 +00003297 time_t ti;
3298 int64_t secs;
3299
3300 if (!sn) {
ths5fafdf22007-09-16 21:08:06 +00003301 snprintf(buf, buf_size,
3302 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00003303 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
3304 } else {
3305 ti = sn->date_sec;
bellard3b9f94e2007-01-07 17:27:07 +00003306#ifdef _WIN32
3307 ptm = localtime(&ti);
3308 strftime(date_buf, sizeof(date_buf),
3309 "%Y-%m-%d %H:%M:%S", ptm);
3310#else
bellardfaea38e2006-08-05 21:31:00 +00003311 localtime_r(&ti, &tm);
3312 strftime(date_buf, sizeof(date_buf),
3313 "%Y-%m-%d %H:%M:%S", &tm);
bellard3b9f94e2007-01-07 17:27:07 +00003314#endif
bellardfaea38e2006-08-05 21:31:00 +00003315 secs = sn->vm_clock_nsec / 1000000000;
3316 snprintf(clock_buf, sizeof(clock_buf),
3317 "%02d:%02d:%02d.%03d",
3318 (int)(secs / 3600),
3319 (int)((secs / 60) % 60),
ths5fafdf22007-09-16 21:08:06 +00003320 (int)(secs % 60),
bellardfaea38e2006-08-05 21:31:00 +00003321 (int)((sn->vm_clock_nsec / 1000000) % 1000));
3322 snprintf(buf, buf_size,
ths5fafdf22007-09-16 21:08:06 +00003323 "%-10s%-20s%7s%20s%15s",
bellardfaea38e2006-08-05 21:31:00 +00003324 sn->id_str, sn->name,
3325 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
3326 date_buf,
3327 clock_buf);
3328 }
3329 return buf;
3330}
3331
bellard83f64092006-08-01 16:21:11 +00003332/**************************************************************/
3333/* async I/Os */
3334
aliguori3b69e4b2009-01-22 16:59:24 +00003335BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
aliguorif141eaf2009-04-07 18:43:24 +00003336 QEMUIOVector *qiov, int nb_sectors,
aliguori3b69e4b2009-01-22 16:59:24 +00003337 BlockDriverCompletionFunc *cb, void *opaque)
3338{
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01003339 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3340
Stefan Hajnoczib2a61372011-10-13 13:08:23 +01003341 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
Stefan Hajnoczi8c5873d2011-10-13 21:09:28 +01003342 cb, opaque, false);
bellard83f64092006-08-01 16:21:11 +00003343}
3344
aliguorif141eaf2009-04-07 18:43:24 +00003345BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3346 QEMUIOVector *qiov, int nb_sectors,
3347 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00003348{
Stefan Hajnoczibbf0a442010-10-05 14:28:53 +01003349 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3350
Stefan Hajnoczi1a6e1152011-10-13 13:08:25 +01003351 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
Stefan Hajnoczi8c5873d2011-10-13 21:09:28 +01003352 cb, opaque, true);
bellard83f64092006-08-01 16:21:11 +00003353}
3354
Kevin Wolf40b4f532009-09-09 17:53:37 +02003355
3356typedef struct MultiwriteCB {
3357 int error;
3358 int num_requests;
3359 int num_callbacks;
3360 struct {
3361 BlockDriverCompletionFunc *cb;
3362 void *opaque;
3363 QEMUIOVector *free_qiov;
Kevin Wolf40b4f532009-09-09 17:53:37 +02003364 } callbacks[];
3365} MultiwriteCB;
3366
3367static void multiwrite_user_cb(MultiwriteCB *mcb)
3368{
3369 int i;
3370
3371 for (i = 0; i < mcb->num_callbacks; i++) {
3372 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
Stefan Hajnoczi1e1ea482010-04-21 20:35:45 +01003373 if (mcb->callbacks[i].free_qiov) {
3374 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
3375 }
Anthony Liguori7267c092011-08-20 22:09:37 -05003376 g_free(mcb->callbacks[i].free_qiov);
Kevin Wolf40b4f532009-09-09 17:53:37 +02003377 }
3378}
3379
3380static void multiwrite_cb(void *opaque, int ret)
3381{
3382 MultiwriteCB *mcb = opaque;
3383
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01003384 trace_multiwrite_cb(mcb, ret);
3385
Kevin Wolfcb6d3ca2010-04-01 22:48:44 +02003386 if (ret < 0 && !mcb->error) {
Kevin Wolf40b4f532009-09-09 17:53:37 +02003387 mcb->error = ret;
Kevin Wolf40b4f532009-09-09 17:53:37 +02003388 }
3389
3390 mcb->num_requests--;
3391 if (mcb->num_requests == 0) {
Kevin Wolfde189a12010-07-01 16:08:51 +02003392 multiwrite_user_cb(mcb);
Anthony Liguori7267c092011-08-20 22:09:37 -05003393 g_free(mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02003394 }
3395}
3396
3397static int multiwrite_req_compare(const void *a, const void *b)
3398{
Christoph Hellwig77be4362010-05-19 20:53:10 +02003399 const BlockRequest *req1 = a, *req2 = b;
3400
3401 /*
3402 * Note that we can't simply subtract req2->sector from req1->sector
3403 * here as that could overflow the return value.
3404 */
3405 if (req1->sector > req2->sector) {
3406 return 1;
3407 } else if (req1->sector < req2->sector) {
3408 return -1;
3409 } else {
3410 return 0;
3411 }
Kevin Wolf40b4f532009-09-09 17:53:37 +02003412}
3413
3414/*
3415 * Takes a bunch of requests and tries to merge them. Returns the number of
3416 * requests that remain after merging.
3417 */
3418static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
3419 int num_reqs, MultiwriteCB *mcb)
3420{
3421 int i, outidx;
3422
3423 // Sort requests by start sector
3424 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
3425
3426 // Check if adjacent requests touch the same clusters. If so, combine them,
3427 // filling up gaps with zero sectors.
3428 outidx = 0;
3429 for (i = 1; i < num_reqs; i++) {
3430 int merge = 0;
3431 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
3432
Paolo Bonzinib6a127a2012-02-21 16:43:52 +01003433 // Handle exactly sequential writes and overlapping writes.
Kevin Wolf40b4f532009-09-09 17:53:37 +02003434 if (reqs[i].sector <= oldreq_last) {
3435 merge = 1;
3436 }
3437
Christoph Hellwige2a305f2010-01-26 14:49:08 +01003438 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3439 merge = 0;
3440 }
3441
Kevin Wolf40b4f532009-09-09 17:53:37 +02003442 if (merge) {
3443 size_t size;
Anthony Liguori7267c092011-08-20 22:09:37 -05003444 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
Kevin Wolf40b4f532009-09-09 17:53:37 +02003445 qemu_iovec_init(qiov,
3446 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
3447
3448 // Add the first request to the merged one. If the requests are
3449 // overlapping, drop the last sectors of the first request.
3450 size = (reqs[i].sector - reqs[outidx].sector) << 9;
Michael Tokarev1b093c42012-03-12 21:28:06 +04003451 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
Kevin Wolf40b4f532009-09-09 17:53:37 +02003452
Paolo Bonzinib6a127a2012-02-21 16:43:52 +01003453 // We should need to add any zeros between the two requests
3454 assert (reqs[i].sector <= oldreq_last);
Kevin Wolf40b4f532009-09-09 17:53:37 +02003455
3456 // Add the second request
Michael Tokarev1b093c42012-03-12 21:28:06 +04003457 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
Kevin Wolf40b4f532009-09-09 17:53:37 +02003458
Kevin Wolfcbf1dff2010-05-21 11:09:42 +02003459 reqs[outidx].nb_sectors = qiov->size >> 9;
Kevin Wolf40b4f532009-09-09 17:53:37 +02003460 reqs[outidx].qiov = qiov;
3461
3462 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
3463 } else {
3464 outidx++;
3465 reqs[outidx].sector = reqs[i].sector;
3466 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
3467 reqs[outidx].qiov = reqs[i].qiov;
3468 }
3469 }
3470
3471 return outidx + 1;
3472}
3473
3474/*
3475 * Submit multiple AIO write requests at once.
3476 *
3477 * On success, the function returns 0 and all requests in the reqs array have
3478 * been submitted. In error case this function returns -1, and any of the
3479 * requests may or may not be submitted yet. In particular, this means that the
3480 * callback will be called for some of the requests, for others it won't. The
3481 * caller must check the error field of the BlockRequest to wait for the right
3482 * callbacks (if error != 0, no callback will be called).
3483 *
3484 * The implementation may modify the contents of the reqs array, e.g. to merge
3485 * requests. However, the fields opaque and error are left unmodified as they
3486 * are used to signal failure for a single request to the caller.
3487 */
3488int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
3489{
Kevin Wolf40b4f532009-09-09 17:53:37 +02003490 MultiwriteCB *mcb;
3491 int i;
3492
Ryan Harper301db7c2011-03-07 10:01:04 -06003493 /* don't submit writes if we don't have a medium */
3494 if (bs->drv == NULL) {
3495 for (i = 0; i < num_reqs; i++) {
3496 reqs[i].error = -ENOMEDIUM;
3497 }
3498 return -1;
3499 }
3500
Kevin Wolf40b4f532009-09-09 17:53:37 +02003501 if (num_reqs == 0) {
3502 return 0;
3503 }
3504
3505 // Create MultiwriteCB structure
Anthony Liguori7267c092011-08-20 22:09:37 -05003506 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
Kevin Wolf40b4f532009-09-09 17:53:37 +02003507 mcb->num_requests = 0;
3508 mcb->num_callbacks = num_reqs;
3509
3510 for (i = 0; i < num_reqs; i++) {
3511 mcb->callbacks[i].cb = reqs[i].cb;
3512 mcb->callbacks[i].opaque = reqs[i].opaque;
3513 }
3514
3515 // Check for mergable requests
3516 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
3517
Stefan Hajnoczi6d519a52010-05-22 18:15:08 +01003518 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
3519
Paolo Bonzinidf9309f2011-11-14 17:50:50 +01003520 /* Run the aio requests. */
3521 mcb->num_requests = num_reqs;
Kevin Wolf40b4f532009-09-09 17:53:37 +02003522 for (i = 0; i < num_reqs; i++) {
Paolo Bonziniad54ae82011-11-30 09:12:30 +01003523 bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
Kevin Wolf40b4f532009-09-09 17:53:37 +02003524 reqs[i].nb_sectors, multiwrite_cb, mcb);
Kevin Wolf40b4f532009-09-09 17:53:37 +02003525 }
3526
3527 return 0;
Kevin Wolf40b4f532009-09-09 17:53:37 +02003528}
3529
bellard83f64092006-08-01 16:21:11 +00003530void bdrv_aio_cancel(BlockDriverAIOCB *acb)
pbrookce1a14d2006-08-07 02:38:06 +00003531{
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003532 acb->aiocb_info->cancel(acb);
bellard83f64092006-08-01 16:21:11 +00003533}
3534
Zhi Yong Wu98f90db2011-11-08 13:00:14 +08003535/* block I/O throttling */
3536static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
3537 bool is_write, double elapsed_time, uint64_t *wait)
3538{
3539 uint64_t bps_limit = 0;
3540 double bytes_limit, bytes_base, bytes_res;
3541 double slice_time, wait_time;
3542
3543 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
3544 bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3545 } else if (bs->io_limits.bps[is_write]) {
3546 bps_limit = bs->io_limits.bps[is_write];
3547 } else {
3548 if (wait) {
3549 *wait = 0;
3550 }
3551
3552 return false;
3553 }
3554
3555 slice_time = bs->slice_end - bs->slice_start;
3556 slice_time /= (NANOSECONDS_PER_SECOND);
3557 bytes_limit = bps_limit * slice_time;
3558 bytes_base = bs->nr_bytes[is_write] - bs->io_base.bytes[is_write];
3559 if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
3560 bytes_base += bs->nr_bytes[!is_write] - bs->io_base.bytes[!is_write];
3561 }
3562
3563 /* bytes_base: the bytes of data which have been read/written; and
3564 * it is obtained from the history statistic info.
3565 * bytes_res: the remaining bytes of data which need to be read/written.
3566 * (bytes_base + bytes_res) / bps_limit: used to calcuate
3567 * the total time for completing reading/writting all data.
3568 */
3569 bytes_res = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
3570
3571 if (bytes_base + bytes_res <= bytes_limit) {
3572 if (wait) {
3573 *wait = 0;
3574 }
3575
3576 return false;
3577 }
3578
3579 /* Calc approx time to dispatch */
3580 wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
3581
3582 /* When the I/O rate at runtime exceeds the limits,
3583 * bs->slice_end need to be extended in order that the current statistic
3584 * info can be kept until the timer fire, so it is increased and tuned
3585 * based on the result of experiment.
3586 */
3587 bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
3588 bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
3589 if (wait) {
3590 *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
3591 }
3592
3593 return true;
3594}
3595
3596static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
3597 double elapsed_time, uint64_t *wait)
3598{
3599 uint64_t iops_limit = 0;
3600 double ios_limit, ios_base;
3601 double slice_time, wait_time;
3602
3603 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
3604 iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3605 } else if (bs->io_limits.iops[is_write]) {
3606 iops_limit = bs->io_limits.iops[is_write];
3607 } else {
3608 if (wait) {
3609 *wait = 0;
3610 }
3611
3612 return false;
3613 }
3614
3615 slice_time = bs->slice_end - bs->slice_start;
3616 slice_time /= (NANOSECONDS_PER_SECOND);
3617 ios_limit = iops_limit * slice_time;
3618 ios_base = bs->nr_ops[is_write] - bs->io_base.ios[is_write];
3619 if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
3620 ios_base += bs->nr_ops[!is_write] - bs->io_base.ios[!is_write];
3621 }
3622
3623 if (ios_base + 1 <= ios_limit) {
3624 if (wait) {
3625 *wait = 0;
3626 }
3627
3628 return false;
3629 }
3630
3631 /* Calc approx time to dispatch */
3632 wait_time = (ios_base + 1) / iops_limit;
3633 if (wait_time > elapsed_time) {
3634 wait_time = wait_time - elapsed_time;
3635 } else {
3636 wait_time = 0;
3637 }
3638
3639 bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
3640 bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
3641 if (wait) {
3642 *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
3643 }
3644
3645 return true;
3646}
3647
3648static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
3649 bool is_write, int64_t *wait)
3650{
3651 int64_t now, max_wait;
3652 uint64_t bps_wait = 0, iops_wait = 0;
3653 double elapsed_time;
3654 int bps_ret, iops_ret;
3655
3656 now = qemu_get_clock_ns(vm_clock);
3657 if ((bs->slice_start < now)
3658 && (bs->slice_end > now)) {
3659 bs->slice_end = now + bs->slice_time;
3660 } else {
3661 bs->slice_time = 5 * BLOCK_IO_SLICE_TIME;
3662 bs->slice_start = now;
3663 bs->slice_end = now + bs->slice_time;
3664
3665 bs->io_base.bytes[is_write] = bs->nr_bytes[is_write];
3666 bs->io_base.bytes[!is_write] = bs->nr_bytes[!is_write];
3667
3668 bs->io_base.ios[is_write] = bs->nr_ops[is_write];
3669 bs->io_base.ios[!is_write] = bs->nr_ops[!is_write];
3670 }
3671
3672 elapsed_time = now - bs->slice_start;
3673 elapsed_time /= (NANOSECONDS_PER_SECOND);
3674
3675 bps_ret = bdrv_exceed_bps_limits(bs, nb_sectors,
3676 is_write, elapsed_time, &bps_wait);
3677 iops_ret = bdrv_exceed_iops_limits(bs, is_write,
3678 elapsed_time, &iops_wait);
3679 if (bps_ret || iops_ret) {
3680 max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
3681 if (wait) {
3682 *wait = max_wait;
3683 }
3684
3685 now = qemu_get_clock_ns(vm_clock);
3686 if (bs->slice_end < now + max_wait) {
3687 bs->slice_end = now + max_wait;
3688 }
3689
3690 return true;
3691 }
3692
3693 if (wait) {
3694 *wait = 0;
3695 }
3696
3697 return false;
3698}
pbrookce1a14d2006-08-07 02:38:06 +00003699
bellard83f64092006-08-01 16:21:11 +00003700/**************************************************************/
3701/* async block device emulation */
3702
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02003703typedef struct BlockDriverAIOCBSync {
3704 BlockDriverAIOCB common;
3705 QEMUBH *bh;
3706 int ret;
3707 /* vector translation state */
3708 QEMUIOVector *qiov;
3709 uint8_t *bounce;
3710 int is_write;
3711} BlockDriverAIOCBSync;
3712
3713static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3714{
Kevin Wolfb666d232010-05-05 11:44:39 +02003715 BlockDriverAIOCBSync *acb =
3716 container_of(blockacb, BlockDriverAIOCBSync, common);
Dor Laor6a7ad292009-06-01 12:07:23 +03003717 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03003718 acb->bh = NULL;
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02003719 qemu_aio_release(acb);
3720}
3721
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003722static const AIOCBInfo bdrv_em_aiocb_info = {
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02003723 .aiocb_size = sizeof(BlockDriverAIOCBSync),
3724 .cancel = bdrv_aio_cancel_em,
3725};
3726
bellard83f64092006-08-01 16:21:11 +00003727static void bdrv_aio_bh_cb(void *opaque)
bellardbeac80c2006-06-26 20:08:57 +00003728{
pbrookce1a14d2006-08-07 02:38:06 +00003729 BlockDriverAIOCBSync *acb = opaque;
aliguorif141eaf2009-04-07 18:43:24 +00003730
aliguorif141eaf2009-04-07 18:43:24 +00003731 if (!acb->is_write)
Michael Tokarev03396142012-06-07 20:17:55 +04003732 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
aliguoriceb42de2009-04-07 18:43:28 +00003733 qemu_vfree(acb->bounce);
pbrookce1a14d2006-08-07 02:38:06 +00003734 acb->common.cb(acb->common.opaque, acb->ret);
Dor Laor6a7ad292009-06-01 12:07:23 +03003735 qemu_bh_delete(acb->bh);
Avi Kivity36afc452009-06-23 16:20:36 +03003736 acb->bh = NULL;
pbrookce1a14d2006-08-07 02:38:06 +00003737 qemu_aio_release(acb);
bellardbeac80c2006-06-26 20:08:57 +00003738}
bellardbeac80c2006-06-26 20:08:57 +00003739
aliguorif141eaf2009-04-07 18:43:24 +00003740static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3741 int64_t sector_num,
3742 QEMUIOVector *qiov,
3743 int nb_sectors,
3744 BlockDriverCompletionFunc *cb,
3745 void *opaque,
3746 int is_write)
3747
bellardea2384d2004-08-01 21:59:26 +00003748{
pbrookce1a14d2006-08-07 02:38:06 +00003749 BlockDriverAIOCBSync *acb;
pbrookce1a14d2006-08-07 02:38:06 +00003750
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003751 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
aliguorif141eaf2009-04-07 18:43:24 +00003752 acb->is_write = is_write;
3753 acb->qiov = qiov;
aliguorie268ca52009-04-22 20:20:00 +00003754 acb->bounce = qemu_blockalign(bs, qiov->size);
Paolo Bonzini3f3aace2011-11-14 17:50:54 +01003755 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
aliguorif141eaf2009-04-07 18:43:24 +00003756
3757 if (is_write) {
Michael Tokarevd5e6b162012-06-07 20:21:06 +04003758 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
Stefan Hajnoczi1ed20ac2011-10-13 13:08:21 +01003759 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
aliguorif141eaf2009-04-07 18:43:24 +00003760 } else {
Stefan Hajnoczi1ed20ac2011-10-13 13:08:21 +01003761 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
aliguorif141eaf2009-04-07 18:43:24 +00003762 }
3763
pbrookce1a14d2006-08-07 02:38:06 +00003764 qemu_bh_schedule(acb->bh);
aliguorif141eaf2009-04-07 18:43:24 +00003765
pbrookce1a14d2006-08-07 02:38:06 +00003766 return &acb->common;
pbrook7a6cba62006-06-04 11:39:07 +00003767}
3768
aliguorif141eaf2009-04-07 18:43:24 +00003769static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3770 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
pbrookce1a14d2006-08-07 02:38:06 +00003771 BlockDriverCompletionFunc *cb, void *opaque)
bellard83f64092006-08-01 16:21:11 +00003772{
aliguorif141eaf2009-04-07 18:43:24 +00003773 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
bellard83f64092006-08-01 16:21:11 +00003774}
3775
aliguorif141eaf2009-04-07 18:43:24 +00003776static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3777 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3778 BlockDriverCompletionFunc *cb, void *opaque)
3779{
3780 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3781}
3782
Kevin Wolf68485422011-06-30 10:05:46 +02003783
3784typedef struct BlockDriverAIOCBCoroutine {
3785 BlockDriverAIOCB common;
3786 BlockRequest req;
3787 bool is_write;
Kevin Wolfd318aea2012-11-13 16:35:08 +01003788 bool *done;
Kevin Wolf68485422011-06-30 10:05:46 +02003789 QEMUBH* bh;
3790} BlockDriverAIOCBCoroutine;
3791
3792static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
3793{
Kevin Wolfd318aea2012-11-13 16:35:08 +01003794 BlockDriverAIOCBCoroutine *acb =
3795 container_of(blockacb, BlockDriverAIOCBCoroutine, common);
3796 bool done = false;
3797
3798 acb->done = &done;
3799 while (!done) {
3800 qemu_aio_wait();
3801 }
Kevin Wolf68485422011-06-30 10:05:46 +02003802}
3803
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003804static const AIOCBInfo bdrv_em_co_aiocb_info = {
Kevin Wolf68485422011-06-30 10:05:46 +02003805 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
3806 .cancel = bdrv_aio_co_cancel_em,
3807};
3808
Paolo Bonzini35246a62011-10-14 10:41:29 +02003809static void bdrv_co_em_bh(void *opaque)
Kevin Wolf68485422011-06-30 10:05:46 +02003810{
3811 BlockDriverAIOCBCoroutine *acb = opaque;
3812
3813 acb->common.cb(acb->common.opaque, acb->req.error);
Kevin Wolfd318aea2012-11-13 16:35:08 +01003814
3815 if (acb->done) {
3816 *acb->done = true;
3817 }
3818
Kevin Wolf68485422011-06-30 10:05:46 +02003819 qemu_bh_delete(acb->bh);
3820 qemu_aio_release(acb);
3821}
3822
Stefan Hajnoczib2a61372011-10-13 13:08:23 +01003823/* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3824static void coroutine_fn bdrv_co_do_rw(void *opaque)
3825{
3826 BlockDriverAIOCBCoroutine *acb = opaque;
3827 BlockDriverState *bs = acb->common.bs;
3828
3829 if (!acb->is_write) {
3830 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
Stefan Hajnoczi470c0502012-01-18 14:40:42 +00003831 acb->req.nb_sectors, acb->req.qiov, 0);
Stefan Hajnoczib2a61372011-10-13 13:08:23 +01003832 } else {
3833 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
Stefan Hajnoczif08f2dd2012-02-07 13:27:25 +00003834 acb->req.nb_sectors, acb->req.qiov, 0);
Stefan Hajnoczib2a61372011-10-13 13:08:23 +01003835 }
3836
Paolo Bonzini35246a62011-10-14 10:41:29 +02003837 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
Stefan Hajnoczib2a61372011-10-13 13:08:23 +01003838 qemu_bh_schedule(acb->bh);
3839}
3840
Kevin Wolf68485422011-06-30 10:05:46 +02003841static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
3842 int64_t sector_num,
3843 QEMUIOVector *qiov,
3844 int nb_sectors,
3845 BlockDriverCompletionFunc *cb,
3846 void *opaque,
Stefan Hajnoczi8c5873d2011-10-13 21:09:28 +01003847 bool is_write)
Kevin Wolf68485422011-06-30 10:05:46 +02003848{
3849 Coroutine *co;
3850 BlockDriverAIOCBCoroutine *acb;
3851
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003852 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
Kevin Wolf68485422011-06-30 10:05:46 +02003853 acb->req.sector = sector_num;
3854 acb->req.nb_sectors = nb_sectors;
3855 acb->req.qiov = qiov;
3856 acb->is_write = is_write;
Kevin Wolfd318aea2012-11-13 16:35:08 +01003857 acb->done = NULL;
Kevin Wolf68485422011-06-30 10:05:46 +02003858
Stefan Hajnoczi8c5873d2011-10-13 21:09:28 +01003859 co = qemu_coroutine_create(bdrv_co_do_rw);
Kevin Wolf68485422011-06-30 10:05:46 +02003860 qemu_coroutine_enter(co, acb);
3861
3862 return &acb->common;
3863}
3864
Paolo Bonzini07f07612011-10-17 12:32:12 +02003865static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02003866{
Paolo Bonzini07f07612011-10-17 12:32:12 +02003867 BlockDriverAIOCBCoroutine *acb = opaque;
3868 BlockDriverState *bs = acb->common.bs;
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02003869
Paolo Bonzini07f07612011-10-17 12:32:12 +02003870 acb->req.error = bdrv_co_flush(bs);
3871 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02003872 qemu_bh_schedule(acb->bh);
Christoph Hellwigb2e12bc2009-09-04 19:01:49 +02003873}
3874
Paolo Bonzini07f07612011-10-17 12:32:12 +02003875BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
Alexander Graf016f5cf2010-05-26 17:51:49 +02003876 BlockDriverCompletionFunc *cb, void *opaque)
3877{
Paolo Bonzini07f07612011-10-17 12:32:12 +02003878 trace_bdrv_aio_flush(bs, opaque);
Alexander Graf016f5cf2010-05-26 17:51:49 +02003879
Paolo Bonzini07f07612011-10-17 12:32:12 +02003880 Coroutine *co;
3881 BlockDriverAIOCBCoroutine *acb;
Alexander Graf016f5cf2010-05-26 17:51:49 +02003882
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003883 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
Kevin Wolfd318aea2012-11-13 16:35:08 +01003884 acb->done = NULL;
3885
Paolo Bonzini07f07612011-10-17 12:32:12 +02003886 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
3887 qemu_coroutine_enter(co, acb);
Alexander Graf016f5cf2010-05-26 17:51:49 +02003888
Alexander Graf016f5cf2010-05-26 17:51:49 +02003889 return &acb->common;
3890}
3891
Paolo Bonzini4265d622011-10-17 12:32:14 +02003892static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
3893{
3894 BlockDriverAIOCBCoroutine *acb = opaque;
3895 BlockDriverState *bs = acb->common.bs;
3896
3897 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
3898 acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3899 qemu_bh_schedule(acb->bh);
3900}
3901
3902BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
3903 int64_t sector_num, int nb_sectors,
3904 BlockDriverCompletionFunc *cb, void *opaque)
3905{
3906 Coroutine *co;
3907 BlockDriverAIOCBCoroutine *acb;
3908
3909 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
3910
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003911 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
Paolo Bonzini4265d622011-10-17 12:32:14 +02003912 acb->req.sector = sector_num;
3913 acb->req.nb_sectors = nb_sectors;
Kevin Wolfd318aea2012-11-13 16:35:08 +01003914 acb->done = NULL;
Paolo Bonzini4265d622011-10-17 12:32:14 +02003915 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
3916 qemu_coroutine_enter(co, acb);
3917
3918 return &acb->common;
3919}
3920
bellardea2384d2004-08-01 21:59:26 +00003921void bdrv_init(void)
3922{
Anthony Liguori5efa9d52009-05-09 17:03:42 -05003923 module_call_init(MODULE_INIT_BLOCK);
bellardea2384d2004-08-01 21:59:26 +00003924}
pbrookce1a14d2006-08-07 02:38:06 +00003925
Markus Armbrustereb852012009-10-27 18:41:44 +01003926void bdrv_init_with_whitelist(void)
3927{
3928 use_bdrv_whitelist = 1;
3929 bdrv_init();
3930}
3931
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003932void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
Christoph Hellwigc16b5a22009-05-25 12:37:32 +02003933 BlockDriverCompletionFunc *cb, void *opaque)
aliguori6bbff9a2009-03-20 18:25:59 +00003934{
pbrookce1a14d2006-08-07 02:38:06 +00003935 BlockDriverAIOCB *acb;
3936
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003937 acb = g_slice_alloc(aiocb_info->aiocb_size);
3938 acb->aiocb_info = aiocb_info;
pbrookce1a14d2006-08-07 02:38:06 +00003939 acb->bs = bs;
3940 acb->cb = cb;
3941 acb->opaque = opaque;
3942 return acb;
3943}
3944
3945void qemu_aio_release(void *p)
3946{
Stefan Hajnoczid37c9752012-10-31 16:34:36 +01003947 BlockDriverAIOCB *acb = p;
Stefan Hajnoczid7331be2012-10-31 16:34:37 +01003948 g_slice_free1(acb->aiocb_info->aiocb_size, acb);
pbrookce1a14d2006-08-07 02:38:06 +00003949}
bellard19cb3732006-08-19 11:45:59 +00003950
3951/**************************************************************/
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003952/* Coroutine block device emulation */
3953
3954typedef struct CoroutineIOCompletion {
3955 Coroutine *coroutine;
3956 int ret;
3957} CoroutineIOCompletion;
3958
3959static void bdrv_co_io_em_complete(void *opaque, int ret)
3960{
3961 CoroutineIOCompletion *co = opaque;
3962
3963 co->ret = ret;
3964 qemu_coroutine_enter(co->coroutine, NULL);
3965}
3966
3967static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
3968 int nb_sectors, QEMUIOVector *iov,
3969 bool is_write)
3970{
3971 CoroutineIOCompletion co = {
3972 .coroutine = qemu_coroutine_self(),
3973 };
3974 BlockDriverAIOCB *acb;
3975
3976 if (is_write) {
Stefan Hajnoczia652d162011-10-05 17:17:02 +01003977 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
3978 bdrv_co_io_em_complete, &co);
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003979 } else {
Stefan Hajnoczia652d162011-10-05 17:17:02 +01003980 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
3981 bdrv_co_io_em_complete, &co);
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003982 }
3983
Stefan Hajnoczi59370aa2011-09-30 17:34:58 +01003984 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
Kevin Wolff9f05dc2011-07-15 13:50:26 +02003985 if (!acb) {
3986 return -EIO;
3987 }
3988 qemu_coroutine_yield();
3989
3990 return co.ret;
3991}
3992
3993static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3994 int64_t sector_num, int nb_sectors,
3995 QEMUIOVector *iov)
3996{
3997 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3998}
3999
4000static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4001 int64_t sector_num, int nb_sectors,
4002 QEMUIOVector *iov)
4003{
4004 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4005}
4006
Paolo Bonzini07f07612011-10-17 12:32:12 +02004007static void coroutine_fn bdrv_flush_co_entry(void *opaque)
Kevin Wolfe7a8a782011-07-15 16:05:00 +02004008{
Paolo Bonzini07f07612011-10-17 12:32:12 +02004009 RwCo *rwco = opaque;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02004010
Paolo Bonzini07f07612011-10-17 12:32:12 +02004011 rwco->ret = bdrv_co_flush(rwco->bs);
4012}
4013
4014int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
4015{
Kevin Wolfeb489bb2011-11-10 18:10:11 +01004016 int ret;
4017
Paolo Bonzini29cdb252012-03-12 18:26:01 +01004018 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
Paolo Bonzini07f07612011-10-17 12:32:12 +02004019 return 0;
Kevin Wolfeb489bb2011-11-10 18:10:11 +01004020 }
4021
Kevin Wolfca716362011-11-10 18:13:59 +01004022 /* Write back cached data to the OS even with cache=unsafe */
Kevin Wolfeb489bb2011-11-10 18:10:11 +01004023 if (bs->drv->bdrv_co_flush_to_os) {
4024 ret = bs->drv->bdrv_co_flush_to_os(bs);
4025 if (ret < 0) {
4026 return ret;
4027 }
4028 }
4029
Kevin Wolfca716362011-11-10 18:13:59 +01004030 /* But don't actually force it to the disk with cache=unsafe */
4031 if (bs->open_flags & BDRV_O_NO_FLUSH) {
Kevin Wolfd4c82322012-08-15 12:52:45 +02004032 goto flush_parent;
Kevin Wolfca716362011-11-10 18:13:59 +01004033 }
4034
Kevin Wolfeb489bb2011-11-10 18:10:11 +01004035 if (bs->drv->bdrv_co_flush_to_disk) {
Paolo Bonzini29cdb252012-03-12 18:26:01 +01004036 ret = bs->drv->bdrv_co_flush_to_disk(bs);
Paolo Bonzini07f07612011-10-17 12:32:12 +02004037 } else if (bs->drv->bdrv_aio_flush) {
4038 BlockDriverAIOCB *acb;
4039 CoroutineIOCompletion co = {
4040 .coroutine = qemu_coroutine_self(),
4041 };
4042
4043 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
4044 if (acb == NULL) {
Paolo Bonzini29cdb252012-03-12 18:26:01 +01004045 ret = -EIO;
Paolo Bonzini07f07612011-10-17 12:32:12 +02004046 } else {
4047 qemu_coroutine_yield();
Paolo Bonzini29cdb252012-03-12 18:26:01 +01004048 ret = co.ret;
Paolo Bonzini07f07612011-10-17 12:32:12 +02004049 }
Paolo Bonzini07f07612011-10-17 12:32:12 +02004050 } else {
4051 /*
4052 * Some block drivers always operate in either writethrough or unsafe
4053 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
4054 * know how the server works (because the behaviour is hardcoded or
4055 * depends on server-side configuration), so we can't ensure that
4056 * everything is safe on disk. Returning an error doesn't work because
4057 * that would break guests even if the server operates in writethrough
4058 * mode.
4059 *
4060 * Let's hope the user knows what he's doing.
4061 */
Paolo Bonzini29cdb252012-03-12 18:26:01 +01004062 ret = 0;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02004063 }
Paolo Bonzini29cdb252012-03-12 18:26:01 +01004064 if (ret < 0) {
4065 return ret;
4066 }
4067
4068 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
4069 * in the case of cache=unsafe, so there are no useless flushes.
4070 */
Kevin Wolfd4c82322012-08-15 12:52:45 +02004071flush_parent:
Paolo Bonzini29cdb252012-03-12 18:26:01 +01004072 return bdrv_co_flush(bs->file);
Paolo Bonzini07f07612011-10-17 12:32:12 +02004073}
4074
Anthony Liguori0f154232011-11-14 15:09:45 -06004075void bdrv_invalidate_cache(BlockDriverState *bs)
4076{
4077 if (bs->drv && bs->drv->bdrv_invalidate_cache) {
4078 bs->drv->bdrv_invalidate_cache(bs);
4079 }
4080}
4081
4082void bdrv_invalidate_cache_all(void)
4083{
4084 BlockDriverState *bs;
4085
4086 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4087 bdrv_invalidate_cache(bs);
4088 }
4089}
4090
Benoît Canet07789262012-03-23 08:36:49 +01004091void bdrv_clear_incoming_migration_all(void)
4092{
4093 BlockDriverState *bs;
4094
4095 QTAILQ_FOREACH(bs, &bdrv_states, list) {
4096 bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
4097 }
4098}
4099
Paolo Bonzini07f07612011-10-17 12:32:12 +02004100int bdrv_flush(BlockDriverState *bs)
4101{
4102 Coroutine *co;
4103 RwCo rwco = {
4104 .bs = bs,
4105 .ret = NOT_DONE,
4106 };
4107
4108 if (qemu_in_coroutine()) {
4109 /* Fast-path if already in coroutine context */
4110 bdrv_flush_co_entry(&rwco);
4111 } else {
4112 co = qemu_coroutine_create(bdrv_flush_co_entry);
4113 qemu_coroutine_enter(co, &rwco);
4114 while (rwco.ret == NOT_DONE) {
4115 qemu_aio_wait();
4116 }
4117 }
4118
4119 return rwco.ret;
Kevin Wolfe7a8a782011-07-15 16:05:00 +02004120}
4121
Paolo Bonzini4265d622011-10-17 12:32:14 +02004122static void coroutine_fn bdrv_discard_co_entry(void *opaque)
4123{
4124 RwCo *rwco = opaque;
4125
4126 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
4127}
4128
4129int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
4130 int nb_sectors)
4131{
4132 if (!bs->drv) {
4133 return -ENOMEDIUM;
4134 } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
4135 return -EIO;
4136 } else if (bs->read_only) {
4137 return -EROFS;
4138 } else if (bs->drv->bdrv_co_discard) {
4139 return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
4140 } else if (bs->drv->bdrv_aio_discard) {
4141 BlockDriverAIOCB *acb;
4142 CoroutineIOCompletion co = {
4143 .coroutine = qemu_coroutine_self(),
4144 };
4145
4146 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
4147 bdrv_co_io_em_complete, &co);
4148 if (acb == NULL) {
4149 return -EIO;
4150 } else {
4151 qemu_coroutine_yield();
4152 return co.ret;
4153 }
Paolo Bonzini4265d622011-10-17 12:32:14 +02004154 } else {
4155 return 0;
4156 }
4157}
4158
4159int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
4160{
4161 Coroutine *co;
4162 RwCo rwco = {
4163 .bs = bs,
4164 .sector_num = sector_num,
4165 .nb_sectors = nb_sectors,
4166 .ret = NOT_DONE,
4167 };
4168
4169 if (qemu_in_coroutine()) {
4170 /* Fast-path if already in coroutine context */
4171 bdrv_discard_co_entry(&rwco);
4172 } else {
4173 co = qemu_coroutine_create(bdrv_discard_co_entry);
4174 qemu_coroutine_enter(co, &rwco);
4175 while (rwco.ret == NOT_DONE) {
4176 qemu_aio_wait();
4177 }
4178 }
4179
4180 return rwco.ret;
4181}
4182
Kevin Wolff9f05dc2011-07-15 13:50:26 +02004183/**************************************************************/
bellard19cb3732006-08-19 11:45:59 +00004184/* removable device support */
4185
4186/**
4187 * Return TRUE if the media is present
4188 */
4189int bdrv_is_inserted(BlockDriverState *bs)
4190{
4191 BlockDriver *drv = bs->drv;
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02004192
bellard19cb3732006-08-19 11:45:59 +00004193 if (!drv)
4194 return 0;
4195 if (!drv->bdrv_is_inserted)
Markus Armbrustera1aff5b2011-09-06 18:58:41 +02004196 return 1;
4197 return drv->bdrv_is_inserted(bs);
bellard19cb3732006-08-19 11:45:59 +00004198}
4199
4200/**
Markus Armbruster8e49ca42011-08-03 15:08:08 +02004201 * Return whether the media changed since the last call to this
4202 * function, or -ENOTSUP if we don't know. Most drivers don't know.
bellard19cb3732006-08-19 11:45:59 +00004203 */
4204int bdrv_media_changed(BlockDriverState *bs)
4205{
4206 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00004207
Markus Armbruster8e49ca42011-08-03 15:08:08 +02004208 if (drv && drv->bdrv_media_changed) {
4209 return drv->bdrv_media_changed(bs);
4210 }
4211 return -ENOTSUP;
bellard19cb3732006-08-19 11:45:59 +00004212}
4213
4214/**
4215 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4216 */
Luiz Capitulinof36f3942012-02-03 16:24:53 -02004217void bdrv_eject(BlockDriverState *bs, bool eject_flag)
bellard19cb3732006-08-19 11:45:59 +00004218{
4219 BlockDriver *drv = bs->drv;
bellard19cb3732006-08-19 11:45:59 +00004220
Markus Armbruster822e1cd2011-07-20 18:23:42 +02004221 if (drv && drv->bdrv_eject) {
4222 drv->bdrv_eject(bs, eject_flag);
bellard19cb3732006-08-19 11:45:59 +00004223 }
Luiz Capitulino6f382ed2012-02-14 13:41:13 -02004224
4225 if (bs->device_name[0] != '\0') {
4226 bdrv_emit_qmp_eject_event(bs, eject_flag);
4227 }
bellard19cb3732006-08-19 11:45:59 +00004228}
4229
bellard19cb3732006-08-19 11:45:59 +00004230/**
4231 * Lock or unlock the media (if it is locked, the user won't be able
4232 * to eject it manually).
4233 */
Markus Armbruster025e8492011-09-06 18:58:47 +02004234void bdrv_lock_medium(BlockDriverState *bs, bool locked)
bellard19cb3732006-08-19 11:45:59 +00004235{
4236 BlockDriver *drv = bs->drv;
4237
Markus Armbruster025e8492011-09-06 18:58:47 +02004238 trace_bdrv_lock_medium(bs, locked);
Stefan Hajnoczib8c6d092011-03-29 20:04:40 +01004239
Markus Armbruster025e8492011-09-06 18:58:47 +02004240 if (drv && drv->bdrv_lock_medium) {
4241 drv->bdrv_lock_medium(bs, locked);
bellard19cb3732006-08-19 11:45:59 +00004242 }
4243}
ths985a03b2007-12-24 16:10:43 +00004244
4245/* needed for generic scsi interface */
4246
4247int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4248{
4249 BlockDriver *drv = bs->drv;
4250
4251 if (drv && drv->bdrv_ioctl)
4252 return drv->bdrv_ioctl(bs, req, buf);
4253 return -ENOTSUP;
4254}
aliguori7d780662009-03-12 19:57:08 +00004255
aliguori221f7152009-03-28 17:28:41 +00004256BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4257 unsigned long int req, void *buf,
4258 BlockDriverCompletionFunc *cb, void *opaque)
aliguori7d780662009-03-12 19:57:08 +00004259{
aliguori221f7152009-03-28 17:28:41 +00004260 BlockDriver *drv = bs->drv;
aliguori7d780662009-03-12 19:57:08 +00004261
aliguori221f7152009-03-28 17:28:41 +00004262 if (drv && drv->bdrv_aio_ioctl)
4263 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4264 return NULL;
aliguori7d780662009-03-12 19:57:08 +00004265}
aliguorie268ca52009-04-22 20:20:00 +00004266
Markus Armbruster7b6f9302011-09-06 18:58:56 +02004267void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
4268{
4269 bs->buffer_alignment = align;
4270}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02004271
aliguorie268ca52009-04-22 20:20:00 +00004272void *qemu_blockalign(BlockDriverState *bs, size_t size)
4273{
4274 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4275}
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02004276
4277void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
4278{
4279 int64_t bitmap_size;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01004280
Liran Schouraaa0eb72010-01-26 10:31:48 +02004281 bs->dirty_count = 0;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01004282 if (enable) {
Jan Kiszkac6d22832009-11-30 18:21:20 +01004283 if (!bs->dirty_bitmap) {
4284 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
Paolo Bonzini71df14f2012-04-12 14:01:04 +02004285 BDRV_SECTORS_PER_DIRTY_CHUNK * BITS_PER_LONG - 1;
4286 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * BITS_PER_LONG;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01004287
Paolo Bonzini71df14f2012-04-12 14:01:04 +02004288 bs->dirty_bitmap = g_new0(unsigned long, bitmap_size);
Jan Kiszkaa55eb922009-11-30 18:21:19 +01004289 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02004290 } else {
Jan Kiszkac6d22832009-11-30 18:21:20 +01004291 if (bs->dirty_bitmap) {
Anthony Liguori7267c092011-08-20 22:09:37 -05004292 g_free(bs->dirty_bitmap);
Jan Kiszkac6d22832009-11-30 18:21:20 +01004293 bs->dirty_bitmap = NULL;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01004294 }
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02004295 }
4296}
4297
4298int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
4299{
Jan Kiszka6ea44302009-11-30 18:21:19 +01004300 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
Jan Kiszkaa55eb922009-11-30 18:21:19 +01004301
Jan Kiszkac6d22832009-11-30 18:21:20 +01004302 if (bs->dirty_bitmap &&
4303 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
Paolo Bonzini1755da12012-10-18 16:49:18 +02004304 return !!(bs->dirty_bitmap[chunk / BITS_PER_LONG] &
4305 (1UL << (chunk % BITS_PER_LONG)));
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02004306 } else {
4307 return 0;
4308 }
4309}
4310
Paolo Bonzini1755da12012-10-18 16:49:18 +02004311int64_t bdrv_get_next_dirty(BlockDriverState *bs, int64_t sector)
4312{
4313 int64_t chunk;
4314 int bit, elem;
4315
4316 /* Avoid an infinite loop. */
4317 assert(bs->dirty_count > 0);
4318
4319 sector = (sector | (BDRV_SECTORS_PER_DIRTY_CHUNK - 1)) + 1;
4320 chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
4321
4322 QEMU_BUILD_BUG_ON(sizeof(bs->dirty_bitmap[0]) * 8 != BITS_PER_LONG);
4323 elem = chunk / BITS_PER_LONG;
4324 bit = chunk % BITS_PER_LONG;
4325 for (;;) {
4326 if (sector >= bs->total_sectors) {
4327 sector = 0;
4328 bit = elem = 0;
4329 }
4330 if (bit == 0 && bs->dirty_bitmap[elem] == 0) {
4331 sector += BDRV_SECTORS_PER_DIRTY_CHUNK * BITS_PER_LONG;
4332 elem++;
4333 } else {
4334 if (bs->dirty_bitmap[elem] & (1UL << bit)) {
4335 return sector;
4336 }
4337 sector += BDRV_SECTORS_PER_DIRTY_CHUNK;
4338 if (++bit == BITS_PER_LONG) {
4339 bit = 0;
4340 elem++;
4341 }
4342 }
4343 }
4344}
4345
4346void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
4347 int nr_sectors)
4348{
4349 set_dirty_bitmap(bs, cur_sector, nr_sectors, 1);
4350}
4351
Jan Kiszkaa55eb922009-11-30 18:21:19 +01004352void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
4353 int nr_sectors)
lirans@il.ibm.com7cd1e322009-11-02 15:40:41 +02004354{
4355 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
4356}
Liran Schouraaa0eb72010-01-26 10:31:48 +02004357
4358int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4359{
4360 return bs->dirty_count;
4361}
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004362
Marcelo Tosattidb593f22011-01-26 12:12:34 -02004363void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4364{
4365 assert(bs->in_use != in_use);
4366 bs->in_use = in_use;
4367}
4368
4369int bdrv_in_use(BlockDriverState *bs)
4370{
4371 return bs->in_use;
4372}
4373
Luiz Capitulino28a72822011-09-26 17:43:50 -03004374void bdrv_iostatus_enable(BlockDriverState *bs)
4375{
Luiz Capitulinod6bf2792011-10-14 17:11:23 -03004376 bs->iostatus_enabled = true;
Luiz Capitulino58e21ef2011-10-14 17:22:24 -03004377 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
Luiz Capitulino28a72822011-09-26 17:43:50 -03004378}
4379
4380/* The I/O status is only enabled if the drive explicitly
4381 * enables it _and_ the VM is configured to stop on errors */
4382bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
4383{
Luiz Capitulinod6bf2792011-10-14 17:11:23 -03004384 return (bs->iostatus_enabled &&
Paolo Bonzini92aa5c62012-09-28 17:22:55 +02004385 (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
4386 bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
4387 bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
Luiz Capitulino28a72822011-09-26 17:43:50 -03004388}
4389
4390void bdrv_iostatus_disable(BlockDriverState *bs)
4391{
Luiz Capitulinod6bf2792011-10-14 17:11:23 -03004392 bs->iostatus_enabled = false;
Luiz Capitulino28a72822011-09-26 17:43:50 -03004393}
4394
4395void bdrv_iostatus_reset(BlockDriverState *bs)
4396{
4397 if (bdrv_iostatus_is_enabled(bs)) {
Luiz Capitulino58e21ef2011-10-14 17:22:24 -03004398 bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
Paolo Bonzini3bd293c2012-10-18 16:49:27 +02004399 if (bs->job) {
4400 block_job_iostatus_reset(bs->job);
4401 }
Luiz Capitulino28a72822011-09-26 17:43:50 -03004402 }
4403}
4404
Luiz Capitulino28a72822011-09-26 17:43:50 -03004405void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
4406{
Paolo Bonzini3e1caa52012-09-28 17:22:57 +02004407 assert(bdrv_iostatus_is_enabled(bs));
4408 if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
Luiz Capitulino58e21ef2011-10-14 17:22:24 -03004409 bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
4410 BLOCK_DEVICE_IO_STATUS_FAILED;
Luiz Capitulino28a72822011-09-26 17:43:50 -03004411 }
4412}
4413
Christoph Hellwiga597e792011-08-25 08:26:01 +02004414void
4415bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4416 enum BlockAcctType type)
4417{
4418 assert(type < BDRV_MAX_IOTYPE);
4419
4420 cookie->bytes = bytes;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02004421 cookie->start_time_ns = get_clock();
Christoph Hellwiga597e792011-08-25 08:26:01 +02004422 cookie->type = type;
4423}
4424
4425void
4426bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4427{
4428 assert(cookie->type < BDRV_MAX_IOTYPE);
4429
4430 bs->nr_bytes[cookie->type] += cookie->bytes;
4431 bs->nr_ops[cookie->type]++;
Christoph Hellwigc488c7f2011-08-25 08:26:10 +02004432 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
Christoph Hellwiga597e792011-08-25 08:26:01 +02004433}
4434
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004435int bdrv_img_create(const char *filename, const char *fmt,
4436 const char *base_filename, const char *base_fmt,
4437 char *options, uint64_t img_size, int flags)
4438{
4439 QEMUOptionParameter *param = NULL, *create_options = NULL;
Kevin Wolfd2208942011-06-01 14:03:31 +02004440 QEMUOptionParameter *backing_fmt, *backing_file, *size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004441 BlockDriverState *bs = NULL;
4442 BlockDriver *drv, *proto_drv;
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00004443 BlockDriver *backing_drv = NULL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004444 int ret = 0;
4445
4446 /* Find driver and parse its options */
4447 drv = bdrv_find_format(fmt);
4448 if (!drv) {
4449 error_report("Unknown file format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01004450 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004451 goto out;
4452 }
4453
4454 proto_drv = bdrv_find_protocol(filename);
4455 if (!proto_drv) {
4456 error_report("Unknown protocol '%s'", filename);
Jes Sorensen4f70f242010-12-16 13:52:18 +01004457 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004458 goto out;
4459 }
4460
4461 create_options = append_option_parameters(create_options,
4462 drv->create_options);
4463 create_options = append_option_parameters(create_options,
4464 proto_drv->create_options);
4465
4466 /* Create parameter list with default values */
4467 param = parse_option_parameters("", create_options, param);
4468
4469 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4470
4471 /* Parse -o options */
4472 if (options) {
4473 param = parse_option_parameters(options, create_options, param);
4474 if (param == NULL) {
4475 error_report("Invalid options for file format '%s'.", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01004476 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004477 goto out;
4478 }
4479 }
4480
4481 if (base_filename) {
4482 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4483 base_filename)) {
4484 error_report("Backing file not supported for file format '%s'",
4485 fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01004486 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004487 goto out;
4488 }
4489 }
4490
4491 if (base_fmt) {
4492 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
4493 error_report("Backing file format not supported for file "
4494 "format '%s'", fmt);
Jes Sorensen4f70f242010-12-16 13:52:18 +01004495 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004496 goto out;
4497 }
4498 }
4499
Jes Sorensen792da932010-12-16 13:52:17 +01004500 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4501 if (backing_file && backing_file->value.s) {
4502 if (!strcmp(filename, backing_file->value.s)) {
4503 error_report("Error: Trying to create an image with the "
4504 "same filename as the backing file");
Jes Sorensen4f70f242010-12-16 13:52:18 +01004505 ret = -EINVAL;
Jes Sorensen792da932010-12-16 13:52:17 +01004506 goto out;
4507 }
4508 }
4509
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004510 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4511 if (backing_fmt && backing_fmt->value.s) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00004512 backing_drv = bdrv_find_format(backing_fmt->value.s);
4513 if (!backing_drv) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004514 error_report("Unknown backing file format '%s'",
4515 backing_fmt->value.s);
Jes Sorensen4f70f242010-12-16 13:52:18 +01004516 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004517 goto out;
4518 }
4519 }
4520
4521 // The size for the image must always be specified, with one exception:
4522 // If we are using a backing file, we can obtain the size from there
Kevin Wolfd2208942011-06-01 14:03:31 +02004523 size = get_option_parameter(param, BLOCK_OPT_SIZE);
4524 if (size && size->value.n == -1) {
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004525 if (backing_file && backing_file->value.s) {
4526 uint64_t size;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004527 char buf[32];
Paolo Bonzini63090da2012-04-12 14:01:03 +02004528 int back_flags;
4529
4530 /* backing files always opened read-only */
4531 back_flags =
4532 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004533
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004534 bs = bdrv_new("");
4535
Paolo Bonzini63090da2012-04-12 14:01:03 +02004536 ret = bdrv_open(bs, backing_file->value.s, back_flags, backing_drv);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004537 if (ret < 0) {
Stefan Hajnoczi96df67d2011-01-24 09:32:20 +00004538 error_report("Could not open '%s'", backing_file->value.s);
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004539 goto out;
4540 }
4541 bdrv_get_geometry(bs, &size);
4542 size *= 512;
4543
4544 snprintf(buf, sizeof(buf), "%" PRId64, size);
4545 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4546 } else {
4547 error_report("Image creation needs a size parameter");
Jes Sorensen4f70f242010-12-16 13:52:18 +01004548 ret = -EINVAL;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004549 goto out;
4550 }
4551 }
4552
4553 printf("Formatting '%s', fmt=%s ", filename, fmt);
4554 print_option_parameters(param);
4555 puts("");
4556
4557 ret = bdrv_create(drv, filename, param);
4558
4559 if (ret < 0) {
4560 if (ret == -ENOTSUP) {
4561 error_report("Formatting or formatting option not supported for "
4562 "file format '%s'", fmt);
4563 } else if (ret == -EFBIG) {
4564 error_report("The image size is too large for file format '%s'",
4565 fmt);
4566 } else {
4567 error_report("%s: error while creating %s: %s", filename, fmt,
4568 strerror(-ret));
4569 }
4570 }
4571
4572out:
4573 free_option_parameters(create_options);
4574 free_option_parameters(param);
4575
4576 if (bs) {
4577 bdrv_delete(bs);
4578 }
Jes Sorensen4f70f242010-12-16 13:52:18 +01004579
4580 return ret;
Jes Sorensenf88e1a42010-12-16 13:52:15 +01004581}