Statistics
| Branch: | Revision:

root / block.c @ 68485420

History | View | Annotate | Download (85 kB)

1
/*
2
 * QEMU System Emulator block driver
3
 *
4
 * Copyright (c) 2003 Fabrice Bellard
5
 *
6
 * 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
 */
24
#include "config-host.h"
25
#include "qemu-common.h"
26
#include "trace.h"
27
#include "monitor.h"
28
#include "block_int.h"
29
#include "module.h"
30
#include "qemu-objects.h"
31
#include "qemu-coroutine.h"
32

    
33
#ifdef CONFIG_BSD
34
#include <sys/types.h>
35
#include <sys/stat.h>
36
#include <sys/ioctl.h>
37
#include <sys/queue.h>
38
#ifndef __DragonFly__
39
#include <sys/disk.h>
40
#endif
41
#endif
42

    
43
#ifdef _WIN32
44
#include <windows.h>
45
#endif
46

    
47
static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
48
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
49
        BlockDriverCompletionFunc *cb, void *opaque);
50
static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
51
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
52
        BlockDriverCompletionFunc *cb, void *opaque);
53
static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
54
        BlockDriverCompletionFunc *cb, void *opaque);
55
static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
56
        BlockDriverCompletionFunc *cb, void *opaque);
57
static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
58
                        uint8_t *buf, int nb_sectors);
59
static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
60
                         const uint8_t *buf, int nb_sectors);
61
static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
62
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63
        BlockDriverCompletionFunc *cb, void *opaque);
64
static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
65
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66
        BlockDriverCompletionFunc *cb, void *opaque);
67

    
68
static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
69
    QTAILQ_HEAD_INITIALIZER(bdrv_states);
70

    
71
static QLIST_HEAD(, BlockDriver) bdrv_drivers =
72
    QLIST_HEAD_INITIALIZER(bdrv_drivers);
73

    
74
/* The device to use for VM snapshots */
75
static BlockDriverState *bs_snapshots;
76

    
77
/* If non-zero, use only whitelisted block drivers */
78
static int use_bdrv_whitelist;
79

    
80
#ifdef _WIN32
81
static int is_windows_drive_prefix(const char *filename)
82
{
83
    return (((filename[0] >= 'a' && filename[0] <= 'z') ||
84
             (filename[0] >= 'A' && filename[0] <= 'Z')) &&
85
            filename[1] == ':');
86
}
87

    
88
int is_windows_drive(const char *filename)
89
{
90
    if (is_windows_drive_prefix(filename) &&
91
        filename[2] == '\0')
92
        return 1;
93
    if (strstart(filename, "\\\\.\\", NULL) ||
94
        strstart(filename, "//./", NULL))
95
        return 1;
96
    return 0;
97
}
98
#endif
99

    
100
/* check if the path starts with "<protocol>:" */
101
static int path_has_protocol(const char *path)
102
{
103
#ifdef _WIN32
104
    if (is_windows_drive(path) ||
105
        is_windows_drive_prefix(path)) {
106
        return 0;
107
    }
108
#endif
109

    
110
    return strchr(path, ':') != NULL;
111
}
112

    
113
int path_is_absolute(const char *path)
114
{
115
    const char *p;
116
#ifdef _WIN32
117
    /* specific case for names like: "\\.\d:" */
118
    if (*path == '/' || *path == '\\')
119
        return 1;
120
#endif
121
    p = strchr(path, ':');
122
    if (p)
123
        p++;
124
    else
125
        p = path;
126
#ifdef _WIN32
127
    return (*p == '/' || *p == '\\');
128
#else
129
    return (*p == '/');
130
#endif
131
}
132

    
133
/* if filename is absolute, just copy it to dest. Otherwise, build a
134
   path to it by considering it is relative to base_path. URL are
135
   supported. */
136
void path_combine(char *dest, int dest_size,
137
                  const char *base_path,
138
                  const char *filename)
139
{
140
    const char *p, *p1;
141
    int len;
142

    
143
    if (dest_size <= 0)
144
        return;
145
    if (path_is_absolute(filename)) {
146
        pstrcpy(dest, dest_size, filename);
147
    } else {
148
        p = strchr(base_path, ':');
149
        if (p)
150
            p++;
151
        else
152
            p = base_path;
153
        p1 = strrchr(base_path, '/');
154
#ifdef _WIN32
155
        {
156
            const char *p2;
157
            p2 = strrchr(base_path, '\\');
158
            if (!p1 || p2 > p1)
159
                p1 = p2;
160
        }
161
#endif
162
        if (p1)
163
            p1++;
164
        else
165
            p1 = base_path;
166
        if (p1 > p)
167
            p = p1;
168
        len = p - base_path;
169
        if (len > dest_size - 1)
170
            len = dest_size - 1;
171
        memcpy(dest, base_path, len);
172
        dest[len] = '\0';
173
        pstrcat(dest, dest_size, filename);
174
    }
175
}
176

    
177
void bdrv_register(BlockDriver *bdrv)
178
{
179
    if (bdrv->bdrv_co_readv) {
180
        /* Emulate AIO by coroutines, and sync by AIO */
181
        bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
182
        bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
183
        bdrv->bdrv_read = bdrv_read_em;
184
        bdrv->bdrv_write = bdrv_write_em;
185
     } else if (!bdrv->bdrv_aio_readv) {
186
        /* add AIO emulation layer */
187
        bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
188
        bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
189
    } else if (!bdrv->bdrv_read) {
190
        /* add synchronous IO emulation layer */
191
        bdrv->bdrv_read = bdrv_read_em;
192
        bdrv->bdrv_write = bdrv_write_em;
193
    }
194

    
195
    if (!bdrv->bdrv_aio_flush)
196
        bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
197

    
198
    QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
199
}
200

    
201
/* create a new block device (by default it is empty) */
202
BlockDriverState *bdrv_new(const char *device_name)
203
{
204
    BlockDriverState *bs;
205

    
206
    bs = qemu_mallocz(sizeof(BlockDriverState));
207
    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
208
    if (device_name[0] != '\0') {
209
        QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
210
    }
211
    return bs;
212
}
213

    
214
BlockDriver *bdrv_find_format(const char *format_name)
215
{
216
    BlockDriver *drv1;
217
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
218
        if (!strcmp(drv1->format_name, format_name)) {
219
            return drv1;
220
        }
221
    }
222
    return NULL;
223
}
224

    
225
static int bdrv_is_whitelisted(BlockDriver *drv)
226
{
227
    static const char *whitelist[] = {
228
        CONFIG_BDRV_WHITELIST
229
    };
230
    const char **p;
231

    
232
    if (!whitelist[0])
233
        return 1;               /* no whitelist, anything goes */
234

    
235
    for (p = whitelist; *p; p++) {
236
        if (!strcmp(drv->format_name, *p)) {
237
            return 1;
238
        }
239
    }
240
    return 0;
241
}
242

    
243
BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
244
{
245
    BlockDriver *drv = bdrv_find_format(format_name);
246
    return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
247
}
248

    
249
int bdrv_create(BlockDriver *drv, const char* filename,
250
    QEMUOptionParameter *options)
251
{
252
    if (!drv->bdrv_create)
253
        return -ENOTSUP;
254

    
255
    return drv->bdrv_create(filename, options);
256
}
257

    
258
int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
259
{
260
    BlockDriver *drv;
261

    
262
    drv = bdrv_find_protocol(filename);
263
    if (drv == NULL) {
264
        return -ENOENT;
265
    }
266

    
267
    return bdrv_create(drv, filename, options);
268
}
269

    
270
#ifdef _WIN32
271
void get_tmp_filename(char *filename, int size)
272
{
273
    char temp_dir[MAX_PATH];
274

    
275
    GetTempPath(MAX_PATH, temp_dir);
276
    GetTempFileName(temp_dir, "qem", 0, filename);
277
}
278
#else
279
void get_tmp_filename(char *filename, int size)
280
{
281
    int fd;
282
    const char *tmpdir;
283
    /* XXX: race condition possible */
284
    tmpdir = getenv("TMPDIR");
285
    if (!tmpdir)
286
        tmpdir = "/tmp";
287
    snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
288
    fd = mkstemp(filename);
289
    close(fd);
290
}
291
#endif
292

    
293
/*
294
 * Detect host devices. By convention, /dev/cdrom[N] is always
295
 * recognized as a host CDROM.
296
 */
297
static BlockDriver *find_hdev_driver(const char *filename)
298
{
299
    int score_max = 0, score;
300
    BlockDriver *drv = NULL, *d;
301

    
302
    QLIST_FOREACH(d, &bdrv_drivers, list) {
303
        if (d->bdrv_probe_device) {
304
            score = d->bdrv_probe_device(filename);
305
            if (score > score_max) {
306
                score_max = score;
307
                drv = d;
308
            }
309
        }
310
    }
311

    
312
    return drv;
313
}
314

    
315
BlockDriver *bdrv_find_protocol(const char *filename)
316
{
317
    BlockDriver *drv1;
318
    char protocol[128];
319
    int len;
320
    const char *p;
321

    
322
    /* TODO Drivers without bdrv_file_open must be specified explicitly */
323

    
324
    /*
325
     * XXX(hch): we really should not let host device detection
326
     * override an explicit protocol specification, but moving this
327
     * later breaks access to device names with colons in them.
328
     * Thanks to the brain-dead persistent naming schemes on udev-
329
     * based Linux systems those actually are quite common.
330
     */
331
    drv1 = find_hdev_driver(filename);
332
    if (drv1) {
333
        return drv1;
334
    }
335

    
336
    if (!path_has_protocol(filename)) {
337
        return bdrv_find_format("file");
338
    }
339
    p = strchr(filename, ':');
340
    assert(p != NULL);
341
    len = p - filename;
342
    if (len > sizeof(protocol) - 1)
343
        len = sizeof(protocol) - 1;
344
    memcpy(protocol, filename, len);
345
    protocol[len] = '\0';
346
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
347
        if (drv1->protocol_name &&
348
            !strcmp(drv1->protocol_name, protocol)) {
349
            return drv1;
350
        }
351
    }
352
    return NULL;
353
}
354

    
355
static int find_image_format(const char *filename, BlockDriver **pdrv)
356
{
357
    int ret, score, score_max;
358
    BlockDriver *drv1, *drv;
359
    uint8_t buf[2048];
360
    BlockDriverState *bs;
361

    
362
    ret = bdrv_file_open(&bs, filename, 0);
363
    if (ret < 0) {
364
        *pdrv = NULL;
365
        return ret;
366
    }
367

    
368
    /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
369
    if (bs->sg || !bdrv_is_inserted(bs)) {
370
        bdrv_delete(bs);
371
        drv = bdrv_find_format("raw");
372
        if (!drv) {
373
            ret = -ENOENT;
374
        }
375
        *pdrv = drv;
376
        return ret;
377
    }
378

    
379
    ret = bdrv_pread(bs, 0, buf, sizeof(buf));
380
    bdrv_delete(bs);
381
    if (ret < 0) {
382
        *pdrv = NULL;
383
        return ret;
384
    }
385

    
386
    score_max = 0;
387
    drv = NULL;
388
    QLIST_FOREACH(drv1, &bdrv_drivers, list) {
389
        if (drv1->bdrv_probe) {
390
            score = drv1->bdrv_probe(buf, ret, filename);
391
            if (score > score_max) {
392
                score_max = score;
393
                drv = drv1;
394
            }
395
        }
396
    }
397
    if (!drv) {
398
        ret = -ENOENT;
399
    }
400
    *pdrv = drv;
401
    return ret;
402
}
403

    
404
/**
405
 * Set the current 'total_sectors' value
406
 */
407
static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
408
{
409
    BlockDriver *drv = bs->drv;
410

    
411
    /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
412
    if (bs->sg)
413
        return 0;
414

    
415
    /* query actual device if possible, otherwise just trust the hint */
416
    if (drv->bdrv_getlength) {
417
        int64_t length = drv->bdrv_getlength(bs);
418
        if (length < 0) {
419
            return length;
420
        }
421
        hint = length >> BDRV_SECTOR_BITS;
422
    }
423

    
424
    bs->total_sectors = hint;
425
    return 0;
426
}
427

    
428
/*
429
 * Common part for opening disk images and files
430
 */
431
static int bdrv_open_common(BlockDriverState *bs, const char *filename,
432
    int flags, BlockDriver *drv)
433
{
434
    int ret, open_flags;
435

    
436
    assert(drv != NULL);
437

    
438
    bs->file = NULL;
439
    bs->total_sectors = 0;
440
    bs->encrypted = 0;
441
    bs->valid_key = 0;
442
    bs->open_flags = flags;
443
    /* buffer_alignment defaulted to 512, drivers can change this value */
444
    bs->buffer_alignment = 512;
445

    
446
    pstrcpy(bs->filename, sizeof(bs->filename), filename);
447

    
448
    if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
449
        return -ENOTSUP;
450
    }
451

    
452
    bs->drv = drv;
453
    bs->opaque = qemu_mallocz(drv->instance_size);
454

    
455
    if (flags & BDRV_O_CACHE_WB)
456
        bs->enable_write_cache = 1;
457

    
458
    /*
459
     * Clear flags that are internal to the block layer before opening the
460
     * image.
461
     */
462
    open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
463

    
464
    /*
465
     * Snapshots should be writable.
466
     */
467
    if (bs->is_temporary) {
468
        open_flags |= BDRV_O_RDWR;
469
    }
470

    
471
    /* Open the image, either directly or using a protocol */
472
    if (drv->bdrv_file_open) {
473
        ret = drv->bdrv_file_open(bs, filename, open_flags);
474
    } else {
475
        ret = bdrv_file_open(&bs->file, filename, open_flags);
476
        if (ret >= 0) {
477
            ret = drv->bdrv_open(bs, open_flags);
478
        }
479
    }
480

    
481
    if (ret < 0) {
482
        goto free_and_fail;
483
    }
484

    
485
    bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
486

    
487
    ret = refresh_total_sectors(bs, bs->total_sectors);
488
    if (ret < 0) {
489
        goto free_and_fail;
490
    }
491

    
492
#ifndef _WIN32
493
    if (bs->is_temporary) {
494
        unlink(filename);
495
    }
496
#endif
497
    return 0;
498

    
499
free_and_fail:
500
    if (bs->file) {
501
        bdrv_delete(bs->file);
502
        bs->file = NULL;
503
    }
504
    qemu_free(bs->opaque);
505
    bs->opaque = NULL;
506
    bs->drv = NULL;
507
    return ret;
508
}
509

    
510
/*
511
 * Opens a file using a protocol (file, host_device, nbd, ...)
512
 */
513
int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
514
{
515
    BlockDriverState *bs;
516
    BlockDriver *drv;
517
    int ret;
518

    
519
    drv = bdrv_find_protocol(filename);
520
    if (!drv) {
521
        return -ENOENT;
522
    }
523

    
524
    bs = bdrv_new("");
525
    ret = bdrv_open_common(bs, filename, flags, drv);
526
    if (ret < 0) {
527
        bdrv_delete(bs);
528
        return ret;
529
    }
530
    bs->growable = 1;
531
    *pbs = bs;
532
    return 0;
533
}
534

    
535
/*
536
 * Opens a disk image (raw, qcow2, vmdk, ...)
537
 */
538
int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
539
              BlockDriver *drv)
540
{
541
    int ret;
542

    
543
    if (flags & BDRV_O_SNAPSHOT) {
544
        BlockDriverState *bs1;
545
        int64_t total_size;
546
        int is_protocol = 0;
547
        BlockDriver *bdrv_qcow2;
548
        QEMUOptionParameter *options;
549
        char tmp_filename[PATH_MAX];
550
        char backing_filename[PATH_MAX];
551

    
552
        /* if snapshot, we create a temporary backing file and open it
553
           instead of opening 'filename' directly */
554

    
555
        /* if there is a backing file, use it */
556
        bs1 = bdrv_new("");
557
        ret = bdrv_open(bs1, filename, 0, drv);
558
        if (ret < 0) {
559
            bdrv_delete(bs1);
560
            return ret;
561
        }
562
        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
563

    
564
        if (bs1->drv && bs1->drv->protocol_name)
565
            is_protocol = 1;
566

    
567
        bdrv_delete(bs1);
568

    
569
        get_tmp_filename(tmp_filename, sizeof(tmp_filename));
570

    
571
        /* Real path is meaningless for protocols */
572
        if (is_protocol)
573
            snprintf(backing_filename, sizeof(backing_filename),
574
                     "%s", filename);
575
        else if (!realpath(filename, backing_filename))
576
            return -errno;
577

    
578
        bdrv_qcow2 = bdrv_find_format("qcow2");
579
        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
580

    
581
        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
582
        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
583
        if (drv) {
584
            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
585
                drv->format_name);
586
        }
587

    
588
        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
589
        free_option_parameters(options);
590
        if (ret < 0) {
591
            return ret;
592
        }
593

    
594
        filename = tmp_filename;
595
        drv = bdrv_qcow2;
596
        bs->is_temporary = 1;
597
    }
598

    
599
    /* Find the right image format driver */
600
    if (!drv) {
601
        ret = find_image_format(filename, &drv);
602
    }
603

    
604
    if (!drv) {
605
        goto unlink_and_fail;
606
    }
607

    
608
    /* Open the image */
609
    ret = bdrv_open_common(bs, filename, flags, drv);
610
    if (ret < 0) {
611
        goto unlink_and_fail;
612
    }
613

    
614
    /* If there is a backing file, use it */
615
    if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
616
        char backing_filename[PATH_MAX];
617
        int back_flags;
618
        BlockDriver *back_drv = NULL;
619

    
620
        bs->backing_hd = bdrv_new("");
621

    
622
        if (path_has_protocol(bs->backing_file)) {
623
            pstrcpy(backing_filename, sizeof(backing_filename),
624
                    bs->backing_file);
625
        } else {
626
            path_combine(backing_filename, sizeof(backing_filename),
627
                         filename, bs->backing_file);
628
        }
629

    
630
        if (bs->backing_format[0] != '\0') {
631
            back_drv = bdrv_find_format(bs->backing_format);
632
        }
633

    
634
        /* backing files always opened read-only */
635
        back_flags =
636
            flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
637

    
638
        ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
639
        if (ret < 0) {
640
            bdrv_close(bs);
641
            return ret;
642
        }
643
        if (bs->is_temporary) {
644
            bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
645
        } else {
646
            /* base image inherits from "parent" */
647
            bs->backing_hd->keep_read_only = bs->keep_read_only;
648
        }
649
    }
650

    
651
    if (!bdrv_key_required(bs)) {
652
        /* call the change callback */
653
        bs->media_changed = 1;
654
        if (bs->change_cb)
655
            bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
656
    }
657

    
658
    return 0;
659

    
660
unlink_and_fail:
661
    if (bs->is_temporary) {
662
        unlink(filename);
663
    }
664
    return ret;
665
}
666

    
667
void bdrv_close(BlockDriverState *bs)
668
{
669
    if (bs->drv) {
670
        if (bs == bs_snapshots) {
671
            bs_snapshots = NULL;
672
        }
673
        if (bs->backing_hd) {
674
            bdrv_delete(bs->backing_hd);
675
            bs->backing_hd = NULL;
676
        }
677
        bs->drv->bdrv_close(bs);
678
        qemu_free(bs->opaque);
679
#ifdef _WIN32
680
        if (bs->is_temporary) {
681
            unlink(bs->filename);
682
        }
683
#endif
684
        bs->opaque = NULL;
685
        bs->drv = NULL;
686

    
687
        if (bs->file != NULL) {
688
            bdrv_close(bs->file);
689
        }
690

    
691
        /* call the change callback */
692
        bs->media_changed = 1;
693
        if (bs->change_cb)
694
            bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
695
    }
696
}
697

    
698
void bdrv_close_all(void)
699
{
700
    BlockDriverState *bs;
701

    
702
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
703
        bdrv_close(bs);
704
    }
705
}
706

    
707
/* make a BlockDriverState anonymous by removing from bdrv_state list.
708
   Also, NULL terminate the device_name to prevent double remove */
709
void bdrv_make_anon(BlockDriverState *bs)
710
{
711
    if (bs->device_name[0] != '\0') {
712
        QTAILQ_REMOVE(&bdrv_states, bs, list);
713
    }
714
    bs->device_name[0] = '\0';
715
}
716

    
717
void bdrv_delete(BlockDriverState *bs)
718
{
719
    assert(!bs->peer);
720

    
721
    /* remove from list, if necessary */
722
    bdrv_make_anon(bs);
723

    
724
    bdrv_close(bs);
725
    if (bs->file != NULL) {
726
        bdrv_delete(bs->file);
727
    }
728

    
729
    assert(bs != bs_snapshots);
730
    qemu_free(bs);
731
}
732

    
733
int bdrv_attach(BlockDriverState *bs, DeviceState *qdev)
734
{
735
    if (bs->peer) {
736
        return -EBUSY;
737
    }
738
    bs->peer = qdev;
739
    return 0;
740
}
741

    
742
void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)
743
{
744
    assert(bs->peer == qdev);
745
    bs->peer = NULL;
746
    bs->change_cb = NULL;
747
    bs->change_opaque = NULL;
748
}
749

    
750
DeviceState *bdrv_get_attached(BlockDriverState *bs)
751
{
752
    return bs->peer;
753
}
754

    
755
/*
756
 * Run consistency checks on an image
757
 *
758
 * Returns 0 if the check could be completed (it doesn't mean that the image is
759
 * free of errors) or -errno when an internal error occurred. The results of the
760
 * check are stored in res.
761
 */
762
int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
763
{
764
    if (bs->drv->bdrv_check == NULL) {
765
        return -ENOTSUP;
766
    }
767

    
768
    memset(res, 0, sizeof(*res));
769
    return bs->drv->bdrv_check(bs, res);
770
}
771

    
772
#define COMMIT_BUF_SECTORS 2048
773

    
774
/* commit COW file into the raw image */
775
int bdrv_commit(BlockDriverState *bs)
776
{
777
    BlockDriver *drv = bs->drv;
778
    BlockDriver *backing_drv;
779
    int64_t sector, total_sectors;
780
    int n, ro, open_flags;
781
    int ret = 0, rw_ret = 0;
782
    uint8_t *buf;
783
    char filename[1024];
784
    BlockDriverState *bs_rw, *bs_ro;
785

    
786
    if (!drv)
787
        return -ENOMEDIUM;
788
    
789
    if (!bs->backing_hd) {
790
        return -ENOTSUP;
791
    }
792

    
793
    if (bs->backing_hd->keep_read_only) {
794
        return -EACCES;
795
    }
796

    
797
    backing_drv = bs->backing_hd->drv;
798
    ro = bs->backing_hd->read_only;
799
    strncpy(filename, bs->backing_hd->filename, sizeof(filename));
800
    open_flags =  bs->backing_hd->open_flags;
801

    
802
    if (ro) {
803
        /* re-open as RW */
804
        bdrv_delete(bs->backing_hd);
805
        bs->backing_hd = NULL;
806
        bs_rw = bdrv_new("");
807
        rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
808
            backing_drv);
809
        if (rw_ret < 0) {
810
            bdrv_delete(bs_rw);
811
            /* try to re-open read-only */
812
            bs_ro = bdrv_new("");
813
            ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
814
                backing_drv);
815
            if (ret < 0) {
816
                bdrv_delete(bs_ro);
817
                /* drive not functional anymore */
818
                bs->drv = NULL;
819
                return ret;
820
            }
821
            bs->backing_hd = bs_ro;
822
            return rw_ret;
823
        }
824
        bs->backing_hd = bs_rw;
825
    }
826

    
827
    total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
828
    buf = qemu_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
829

    
830
    for (sector = 0; sector < total_sectors; sector += n) {
831
        if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
832

    
833
            if (bdrv_read(bs, sector, buf, n) != 0) {
834
                ret = -EIO;
835
                goto ro_cleanup;
836
            }
837

    
838
            if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
839
                ret = -EIO;
840
                goto ro_cleanup;
841
            }
842
        }
843
    }
844

    
845
    if (drv->bdrv_make_empty) {
846
        ret = drv->bdrv_make_empty(bs);
847
        bdrv_flush(bs);
848
    }
849

    
850
    /*
851
     * Make sure all data we wrote to the backing device is actually
852
     * stable on disk.
853
     */
854
    if (bs->backing_hd)
855
        bdrv_flush(bs->backing_hd);
856

    
857
ro_cleanup:
858
    qemu_free(buf);
859

    
860
    if (ro) {
861
        /* re-open as RO */
862
        bdrv_delete(bs->backing_hd);
863
        bs->backing_hd = NULL;
864
        bs_ro = bdrv_new("");
865
        ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
866
            backing_drv);
867
        if (ret < 0) {
868
            bdrv_delete(bs_ro);
869
            /* drive not functional anymore */
870
            bs->drv = NULL;
871
            return ret;
872
        }
873
        bs->backing_hd = bs_ro;
874
        bs->backing_hd->keep_read_only = 0;
875
    }
876

    
877
    return ret;
878
}
879

    
880
void bdrv_commit_all(void)
881
{
882
    BlockDriverState *bs;
883

    
884
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
885
        bdrv_commit(bs);
886
    }
887
}
888

    
889
/*
890
 * Return values:
891
 * 0        - success
892
 * -EINVAL  - backing format specified, but no file
893
 * -ENOSPC  - can't update the backing file because no space is left in the
894
 *            image file header
895
 * -ENOTSUP - format driver doesn't support changing the backing file
896
 */
897
int bdrv_change_backing_file(BlockDriverState *bs,
898
    const char *backing_file, const char *backing_fmt)
899
{
900
    BlockDriver *drv = bs->drv;
901

    
902
    if (drv->bdrv_change_backing_file != NULL) {
903
        return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
904
    } else {
905
        return -ENOTSUP;
906
    }
907
}
908

    
909
static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
910
                                   size_t size)
911
{
912
    int64_t len;
913

    
914
    if (!bdrv_is_inserted(bs))
915
        return -ENOMEDIUM;
916

    
917
    if (bs->growable)
918
        return 0;
919

    
920
    len = bdrv_getlength(bs);
921

    
922
    if (offset < 0)
923
        return -EIO;
924

    
925
    if ((offset > len) || (len - offset < size))
926
        return -EIO;
927

    
928
    return 0;
929
}
930

    
931
static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
932
                              int nb_sectors)
933
{
934
    return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
935
                                   nb_sectors * BDRV_SECTOR_SIZE);
936
}
937

    
938
/* return < 0 if error. See bdrv_write() for the return codes */
939
int bdrv_read(BlockDriverState *bs, int64_t sector_num,
940
              uint8_t *buf, int nb_sectors)
941
{
942
    BlockDriver *drv = bs->drv;
943

    
944
    if (!drv)
945
        return -ENOMEDIUM;
946
    if (bdrv_check_request(bs, sector_num, nb_sectors))
947
        return -EIO;
948

    
949
    return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
950
}
951

    
952
static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
953
                             int nb_sectors, int dirty)
954
{
955
    int64_t start, end;
956
    unsigned long val, idx, bit;
957

    
958
    start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
959
    end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
960

    
961
    for (; start <= end; start++) {
962
        idx = start / (sizeof(unsigned long) * 8);
963
        bit = start % (sizeof(unsigned long) * 8);
964
        val = bs->dirty_bitmap[idx];
965
        if (dirty) {
966
            if (!(val & (1UL << bit))) {
967
                bs->dirty_count++;
968
                val |= 1UL << bit;
969
            }
970
        } else {
971
            if (val & (1UL << bit)) {
972
                bs->dirty_count--;
973
                val &= ~(1UL << bit);
974
            }
975
        }
976
        bs->dirty_bitmap[idx] = val;
977
    }
978
}
979

    
980
/* Return < 0 if error. Important errors are:
981
  -EIO         generic I/O error (may happen for all errors)
982
  -ENOMEDIUM   No media inserted.
983
  -EINVAL      Invalid sector number or nb_sectors
984
  -EACCES      Trying to write a read-only device
985
*/
986
int bdrv_write(BlockDriverState *bs, int64_t sector_num,
987
               const uint8_t *buf, int nb_sectors)
988
{
989
    BlockDriver *drv = bs->drv;
990
    if (!bs->drv)
991
        return -ENOMEDIUM;
992
    if (bs->read_only)
993
        return -EACCES;
994
    if (bdrv_check_request(bs, sector_num, nb_sectors))
995
        return -EIO;
996

    
997
    if (bs->dirty_bitmap) {
998
        set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
999
    }
1000

    
1001
    if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1002
        bs->wr_highest_sector = sector_num + nb_sectors - 1;
1003
    }
1004

    
1005
    return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
1006
}
1007

    
1008
int bdrv_pread(BlockDriverState *bs, int64_t offset,
1009
               void *buf, int count1)
1010
{
1011
    uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1012
    int len, nb_sectors, count;
1013
    int64_t sector_num;
1014
    int ret;
1015

    
1016
    count = count1;
1017
    /* first read to align to sector start */
1018
    len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1019
    if (len > count)
1020
        len = count;
1021
    sector_num = offset >> BDRV_SECTOR_BITS;
1022
    if (len > 0) {
1023
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1024
            return ret;
1025
        memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
1026
        count -= len;
1027
        if (count == 0)
1028
            return count1;
1029
        sector_num++;
1030
        buf += len;
1031
    }
1032

    
1033
    /* read the sectors "in place" */
1034
    nb_sectors = count >> BDRV_SECTOR_BITS;
1035
    if (nb_sectors > 0) {
1036
        if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1037
            return ret;
1038
        sector_num += nb_sectors;
1039
        len = nb_sectors << BDRV_SECTOR_BITS;
1040
        buf += len;
1041
        count -= len;
1042
    }
1043

    
1044
    /* add data from the last sector */
1045
    if (count > 0) {
1046
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1047
            return ret;
1048
        memcpy(buf, tmp_buf, count);
1049
    }
1050
    return count1;
1051
}
1052

    
1053
int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1054
                const void *buf, int count1)
1055
{
1056
    uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1057
    int len, nb_sectors, count;
1058
    int64_t sector_num;
1059
    int ret;
1060

    
1061
    count = count1;
1062
    /* first write to align to sector start */
1063
    len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1064
    if (len > count)
1065
        len = count;
1066
    sector_num = offset >> BDRV_SECTOR_BITS;
1067
    if (len > 0) {
1068
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1069
            return ret;
1070
        memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1071
        if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1072
            return ret;
1073
        count -= len;
1074
        if (count == 0)
1075
            return count1;
1076
        sector_num++;
1077
        buf += len;
1078
    }
1079

    
1080
    /* write the sectors "in place" */
1081
    nb_sectors = count >> BDRV_SECTOR_BITS;
1082
    if (nb_sectors > 0) {
1083
        if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1084
            return ret;
1085
        sector_num += nb_sectors;
1086
        len = nb_sectors << BDRV_SECTOR_BITS;
1087
        buf += len;
1088
        count -= len;
1089
    }
1090

    
1091
    /* add data from the last sector */
1092
    if (count > 0) {
1093
        if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1094
            return ret;
1095
        memcpy(tmp_buf, buf, count);
1096
        if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1097
            return ret;
1098
    }
1099
    return count1;
1100
}
1101

    
1102
/*
1103
 * Writes to the file and ensures that no writes are reordered across this
1104
 * request (acts as a barrier)
1105
 *
1106
 * Returns 0 on success, -errno in error cases.
1107
 */
1108
int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1109
    const void *buf, int count)
1110
{
1111
    int ret;
1112

    
1113
    ret = bdrv_pwrite(bs, offset, buf, count);
1114
    if (ret < 0) {
1115
        return ret;
1116
    }
1117

    
1118
    /* No flush needed for cache=writethrough, it uses O_DSYNC */
1119
    if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1120
        bdrv_flush(bs);
1121
    }
1122

    
1123
    return 0;
1124
}
1125

    
1126
int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1127
    int nb_sectors, QEMUIOVector *qiov)
1128
{
1129
    BlockDriver *drv = bs->drv;
1130

    
1131
    trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1132

    
1133
    if (!drv) {
1134
        return -ENOMEDIUM;
1135
    }
1136
    if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1137
        return -EIO;
1138
    }
1139

    
1140
    return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1141
}
1142

    
1143
int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1144
    int nb_sectors, QEMUIOVector *qiov)
1145
{
1146
    BlockDriver *drv = bs->drv;
1147

    
1148
    trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1149

    
1150
    if (!bs->drv) {
1151
        return -ENOMEDIUM;
1152
    }
1153
    if (bs->read_only) {
1154
        return -EACCES;
1155
    }
1156
    if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1157
        return -EIO;
1158
    }
1159

    
1160
    if (bs->dirty_bitmap) {
1161
        set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1162
    }
1163

    
1164
    if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1165
        bs->wr_highest_sector = sector_num + nb_sectors - 1;
1166
    }
1167

    
1168
    return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1169
}
1170

    
1171
/**
1172
 * Truncate file to 'offset' bytes (needed only for file protocols)
1173
 */
1174
int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1175
{
1176
    BlockDriver *drv = bs->drv;
1177
    int ret;
1178
    if (!drv)
1179
        return -ENOMEDIUM;
1180
    if (!drv->bdrv_truncate)
1181
        return -ENOTSUP;
1182
    if (bs->read_only)
1183
        return -EACCES;
1184
    if (bdrv_in_use(bs))
1185
        return -EBUSY;
1186
    ret = drv->bdrv_truncate(bs, offset);
1187
    if (ret == 0) {
1188
        ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1189
        if (bs->change_cb) {
1190
            bs->change_cb(bs->change_opaque, CHANGE_SIZE);
1191
        }
1192
    }
1193
    return ret;
1194
}
1195

    
1196
/**
1197
 * Length of a allocated file in bytes. Sparse files are counted by actual
1198
 * allocated space. Return < 0 if error or unknown.
1199
 */
1200
int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1201
{
1202
    BlockDriver *drv = bs->drv;
1203
    if (!drv) {
1204
        return -ENOMEDIUM;
1205
    }
1206
    if (drv->bdrv_get_allocated_file_size) {
1207
        return drv->bdrv_get_allocated_file_size(bs);
1208
    }
1209
    if (bs->file) {
1210
        return bdrv_get_allocated_file_size(bs->file);
1211
    }
1212
    return -ENOTSUP;
1213
}
1214

    
1215
/**
1216
 * Length of a file in bytes. Return < 0 if error or unknown.
1217
 */
1218
int64_t bdrv_getlength(BlockDriverState *bs)
1219
{
1220
    BlockDriver *drv = bs->drv;
1221
    if (!drv)
1222
        return -ENOMEDIUM;
1223

    
1224
    if (bs->growable || bs->removable) {
1225
        if (drv->bdrv_getlength) {
1226
            return drv->bdrv_getlength(bs);
1227
        }
1228
    }
1229
    return bs->total_sectors * BDRV_SECTOR_SIZE;
1230
}
1231

    
1232
/* return 0 as number of sectors if no device present or error */
1233
void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1234
{
1235
    int64_t length;
1236
    length = bdrv_getlength(bs);
1237
    if (length < 0)
1238
        length = 0;
1239
    else
1240
        length = length >> BDRV_SECTOR_BITS;
1241
    *nb_sectors_ptr = length;
1242
}
1243

    
1244
struct partition {
1245
        uint8_t boot_ind;           /* 0x80 - active */
1246
        uint8_t head;               /* starting head */
1247
        uint8_t sector;             /* starting sector */
1248
        uint8_t cyl;                /* starting cylinder */
1249
        uint8_t sys_ind;            /* What partition type */
1250
        uint8_t end_head;           /* end head */
1251
        uint8_t end_sector;         /* end sector */
1252
        uint8_t end_cyl;            /* end cylinder */
1253
        uint32_t start_sect;        /* starting sector counting from 0 */
1254
        uint32_t nr_sects;          /* nr of sectors in partition */
1255
} __attribute__((packed));
1256

    
1257
/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1258
static int guess_disk_lchs(BlockDriverState *bs,
1259
                           int *pcylinders, int *pheads, int *psectors)
1260
{
1261
    uint8_t buf[BDRV_SECTOR_SIZE];
1262
    int ret, i, heads, sectors, cylinders;
1263
    struct partition *p;
1264
    uint32_t nr_sects;
1265
    uint64_t nb_sectors;
1266

    
1267
    bdrv_get_geometry(bs, &nb_sectors);
1268

    
1269
    ret = bdrv_read(bs, 0, buf, 1);
1270
    if (ret < 0)
1271
        return -1;
1272
    /* test msdos magic */
1273
    if (buf[510] != 0x55 || buf[511] != 0xaa)
1274
        return -1;
1275
    for(i = 0; i < 4; i++) {
1276
        p = ((struct partition *)(buf + 0x1be)) + i;
1277
        nr_sects = le32_to_cpu(p->nr_sects);
1278
        if (nr_sects && p->end_head) {
1279
            /* We make the assumption that the partition terminates on
1280
               a cylinder boundary */
1281
            heads = p->end_head + 1;
1282
            sectors = p->end_sector & 63;
1283
            if (sectors == 0)
1284
                continue;
1285
            cylinders = nb_sectors / (heads * sectors);
1286
            if (cylinders < 1 || cylinders > 16383)
1287
                continue;
1288
            *pheads = heads;
1289
            *psectors = sectors;
1290
            *pcylinders = cylinders;
1291
#if 0
1292
            printf("guessed geometry: LCHS=%d %d %d\n",
1293
                   cylinders, heads, sectors);
1294
#endif
1295
            return 0;
1296
        }
1297
    }
1298
    return -1;
1299
}
1300

    
1301
void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1302
{
1303
    int translation, lba_detected = 0;
1304
    int cylinders, heads, secs;
1305
    uint64_t nb_sectors;
1306

    
1307
    /* if a geometry hint is available, use it */
1308
    bdrv_get_geometry(bs, &nb_sectors);
1309
    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1310
    translation = bdrv_get_translation_hint(bs);
1311
    if (cylinders != 0) {
1312
        *pcyls = cylinders;
1313
        *pheads = heads;
1314
        *psecs = secs;
1315
    } else {
1316
        if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1317
            if (heads > 16) {
1318
                /* if heads > 16, it means that a BIOS LBA
1319
                   translation was active, so the default
1320
                   hardware geometry is OK */
1321
                lba_detected = 1;
1322
                goto default_geometry;
1323
            } else {
1324
                *pcyls = cylinders;
1325
                *pheads = heads;
1326
                *psecs = secs;
1327
                /* disable any translation to be in sync with
1328
                   the logical geometry */
1329
                if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1330
                    bdrv_set_translation_hint(bs,
1331
                                              BIOS_ATA_TRANSLATION_NONE);
1332
                }
1333
            }
1334
        } else {
1335
        default_geometry:
1336
            /* if no geometry, use a standard physical disk geometry */
1337
            cylinders = nb_sectors / (16 * 63);
1338

    
1339
            if (cylinders > 16383)
1340
                cylinders = 16383;
1341
            else if (cylinders < 2)
1342
                cylinders = 2;
1343
            *pcyls = cylinders;
1344
            *pheads = 16;
1345
            *psecs = 63;
1346
            if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1347
                if ((*pcyls * *pheads) <= 131072) {
1348
                    bdrv_set_translation_hint(bs,
1349
                                              BIOS_ATA_TRANSLATION_LARGE);
1350
                } else {
1351
                    bdrv_set_translation_hint(bs,
1352
                                              BIOS_ATA_TRANSLATION_LBA);
1353
                }
1354
            }
1355
        }
1356
        bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1357
    }
1358
}
1359

    
1360
void bdrv_set_geometry_hint(BlockDriverState *bs,
1361
                            int cyls, int heads, int secs)
1362
{
1363
    bs->cyls = cyls;
1364
    bs->heads = heads;
1365
    bs->secs = secs;
1366
}
1367

    
1368
void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1369
{
1370
    bs->translation = translation;
1371
}
1372

    
1373
void bdrv_get_geometry_hint(BlockDriverState *bs,
1374
                            int *pcyls, int *pheads, int *psecs)
1375
{
1376
    *pcyls = bs->cyls;
1377
    *pheads = bs->heads;
1378
    *psecs = bs->secs;
1379
}
1380

    
1381
/* Recognize floppy formats */
1382
typedef struct FDFormat {
1383
    FDriveType drive;
1384
    uint8_t last_sect;
1385
    uint8_t max_track;
1386
    uint8_t max_head;
1387
} FDFormat;
1388

    
1389
static const FDFormat fd_formats[] = {
1390
    /* First entry is default format */
1391
    /* 1.44 MB 3"1/2 floppy disks */
1392
    { FDRIVE_DRV_144, 18, 80, 1, },
1393
    { FDRIVE_DRV_144, 20, 80, 1, },
1394
    { FDRIVE_DRV_144, 21, 80, 1, },
1395
    { FDRIVE_DRV_144, 21, 82, 1, },
1396
    { FDRIVE_DRV_144, 21, 83, 1, },
1397
    { FDRIVE_DRV_144, 22, 80, 1, },
1398
    { FDRIVE_DRV_144, 23, 80, 1, },
1399
    { FDRIVE_DRV_144, 24, 80, 1, },
1400
    /* 2.88 MB 3"1/2 floppy disks */
1401
    { FDRIVE_DRV_288, 36, 80, 1, },
1402
    { FDRIVE_DRV_288, 39, 80, 1, },
1403
    { FDRIVE_DRV_288, 40, 80, 1, },
1404
    { FDRIVE_DRV_288, 44, 80, 1, },
1405
    { FDRIVE_DRV_288, 48, 80, 1, },
1406
    /* 720 kB 3"1/2 floppy disks */
1407
    { FDRIVE_DRV_144,  9, 80, 1, },
1408
    { FDRIVE_DRV_144, 10, 80, 1, },
1409
    { FDRIVE_DRV_144, 10, 82, 1, },
1410
    { FDRIVE_DRV_144, 10, 83, 1, },
1411
    { FDRIVE_DRV_144, 13, 80, 1, },
1412
    { FDRIVE_DRV_144, 14, 80, 1, },
1413
    /* 1.2 MB 5"1/4 floppy disks */
1414
    { FDRIVE_DRV_120, 15, 80, 1, },
1415
    { FDRIVE_DRV_120, 18, 80, 1, },
1416
    { FDRIVE_DRV_120, 18, 82, 1, },
1417
    { FDRIVE_DRV_120, 18, 83, 1, },
1418
    { FDRIVE_DRV_120, 20, 80, 1, },
1419
    /* 720 kB 5"1/4 floppy disks */
1420
    { FDRIVE_DRV_120,  9, 80, 1, },
1421
    { FDRIVE_DRV_120, 11, 80, 1, },
1422
    /* 360 kB 5"1/4 floppy disks */
1423
    { FDRIVE_DRV_120,  9, 40, 1, },
1424
    { FDRIVE_DRV_120,  9, 40, 0, },
1425
    { FDRIVE_DRV_120, 10, 41, 1, },
1426
    { FDRIVE_DRV_120, 10, 42, 1, },
1427
    /* 320 kB 5"1/4 floppy disks */
1428
    { FDRIVE_DRV_120,  8, 40, 1, },
1429
    { FDRIVE_DRV_120,  8, 40, 0, },
1430
    /* 360 kB must match 5"1/4 better than 3"1/2... */
1431
    { FDRIVE_DRV_144,  9, 80, 0, },
1432
    /* end */
1433
    { FDRIVE_DRV_NONE, -1, -1, 0, },
1434
};
1435

    
1436
void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1437
                                   int *max_track, int *last_sect,
1438
                                   FDriveType drive_in, FDriveType *drive)
1439
{
1440
    const FDFormat *parse;
1441
    uint64_t nb_sectors, size;
1442
    int i, first_match, match;
1443

    
1444
    bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1445
    if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1446
        /* User defined disk */
1447
    } else {
1448
        bdrv_get_geometry(bs, &nb_sectors);
1449
        match = -1;
1450
        first_match = -1;
1451
        for (i = 0; ; i++) {
1452
            parse = &fd_formats[i];
1453
            if (parse->drive == FDRIVE_DRV_NONE) {
1454
                break;
1455
            }
1456
            if (drive_in == parse->drive ||
1457
                drive_in == FDRIVE_DRV_NONE) {
1458
                size = (parse->max_head + 1) * parse->max_track *
1459
                    parse->last_sect;
1460
                if (nb_sectors == size) {
1461
                    match = i;
1462
                    break;
1463
                }
1464
                if (first_match == -1) {
1465
                    first_match = i;
1466
                }
1467
            }
1468
        }
1469
        if (match == -1) {
1470
            if (first_match == -1) {
1471
                match = 1;
1472
            } else {
1473
                match = first_match;
1474
            }
1475
            parse = &fd_formats[match];
1476
        }
1477
        *nb_heads = parse->max_head + 1;
1478
        *max_track = parse->max_track;
1479
        *last_sect = parse->last_sect;
1480
        *drive = parse->drive;
1481
    }
1482
}
1483

    
1484
int bdrv_get_translation_hint(BlockDriverState *bs)
1485
{
1486
    return bs->translation;
1487
}
1488

    
1489
void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1490
                       BlockErrorAction on_write_error)
1491
{
1492
    bs->on_read_error = on_read_error;
1493
    bs->on_write_error = on_write_error;
1494
}
1495

    
1496
BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1497
{
1498
    return is_read ? bs->on_read_error : bs->on_write_error;
1499
}
1500

    
1501
void bdrv_set_removable(BlockDriverState *bs, int removable)
1502
{
1503
    bs->removable = removable;
1504
    if (removable && bs == bs_snapshots) {
1505
        bs_snapshots = NULL;
1506
    }
1507
}
1508

    
1509
int bdrv_is_removable(BlockDriverState *bs)
1510
{
1511
    return bs->removable;
1512
}
1513

    
1514
int bdrv_is_read_only(BlockDriverState *bs)
1515
{
1516
    return bs->read_only;
1517
}
1518

    
1519
int bdrv_is_sg(BlockDriverState *bs)
1520
{
1521
    return bs->sg;
1522
}
1523

    
1524
int bdrv_enable_write_cache(BlockDriverState *bs)
1525
{
1526
    return bs->enable_write_cache;
1527
}
1528

    
1529
/* XXX: no longer used */
1530
void bdrv_set_change_cb(BlockDriverState *bs,
1531
                        void (*change_cb)(void *opaque, int reason),
1532
                        void *opaque)
1533
{
1534
    bs->change_cb = change_cb;
1535
    bs->change_opaque = opaque;
1536
}
1537

    
1538
int bdrv_is_encrypted(BlockDriverState *bs)
1539
{
1540
    if (bs->backing_hd && bs->backing_hd->encrypted)
1541
        return 1;
1542
    return bs->encrypted;
1543
}
1544

    
1545
int bdrv_key_required(BlockDriverState *bs)
1546
{
1547
    BlockDriverState *backing_hd = bs->backing_hd;
1548

    
1549
    if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1550
        return 1;
1551
    return (bs->encrypted && !bs->valid_key);
1552
}
1553

    
1554
int bdrv_set_key(BlockDriverState *bs, const char *key)
1555
{
1556
    int ret;
1557
    if (bs->backing_hd && bs->backing_hd->encrypted) {
1558
        ret = bdrv_set_key(bs->backing_hd, key);
1559
        if (ret < 0)
1560
            return ret;
1561
        if (!bs->encrypted)
1562
            return 0;
1563
    }
1564
    if (!bs->encrypted) {
1565
        return -EINVAL;
1566
    } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1567
        return -ENOMEDIUM;
1568
    }
1569
    ret = bs->drv->bdrv_set_key(bs, key);
1570
    if (ret < 0) {
1571
        bs->valid_key = 0;
1572
    } else if (!bs->valid_key) {
1573
        bs->valid_key = 1;
1574
        /* call the change callback now, we skipped it on open */
1575
        bs->media_changed = 1;
1576
        if (bs->change_cb)
1577
            bs->change_cb(bs->change_opaque, CHANGE_MEDIA);
1578
    }
1579
    return ret;
1580
}
1581

    
1582
void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1583
{
1584
    if (!bs->drv) {
1585
        buf[0] = '\0';
1586
    } else {
1587
        pstrcpy(buf, buf_size, bs->drv->format_name);
1588
    }
1589
}
1590

    
1591
void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1592
                         void *opaque)
1593
{
1594
    BlockDriver *drv;
1595

    
1596
    QLIST_FOREACH(drv, &bdrv_drivers, list) {
1597
        it(opaque, drv->format_name);
1598
    }
1599
}
1600

    
1601
BlockDriverState *bdrv_find(const char *name)
1602
{
1603
    BlockDriverState *bs;
1604

    
1605
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1606
        if (!strcmp(name, bs->device_name)) {
1607
            return bs;
1608
        }
1609
    }
1610
    return NULL;
1611
}
1612

    
1613
BlockDriverState *bdrv_next(BlockDriverState *bs)
1614
{
1615
    if (!bs) {
1616
        return QTAILQ_FIRST(&bdrv_states);
1617
    }
1618
    return QTAILQ_NEXT(bs, list);
1619
}
1620

    
1621
void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1622
{
1623
    BlockDriverState *bs;
1624

    
1625
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1626
        it(opaque, bs);
1627
    }
1628
}
1629

    
1630
const char *bdrv_get_device_name(BlockDriverState *bs)
1631
{
1632
    return bs->device_name;
1633
}
1634

    
1635
int bdrv_flush(BlockDriverState *bs)
1636
{
1637
    if (bs->open_flags & BDRV_O_NO_FLUSH) {
1638
        return 0;
1639
    }
1640

    
1641
    if (bs->drv && bs->drv->bdrv_flush) {
1642
        return bs->drv->bdrv_flush(bs);
1643
    }
1644

    
1645
    /*
1646
     * Some block drivers always operate in either writethrough or unsafe mode
1647
     * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1648
     * the server works (because the behaviour is hardcoded or depends on
1649
     * server-side configuration), so we can't ensure that everything is safe
1650
     * on disk. Returning an error doesn't work because that would break guests
1651
     * even if the server operates in writethrough mode.
1652
     *
1653
     * Let's hope the user knows what he's doing.
1654
     */
1655
    return 0;
1656
}
1657

    
1658
void bdrv_flush_all(void)
1659
{
1660
    BlockDriverState *bs;
1661

    
1662
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1663
        if (bs->drv && !bdrv_is_read_only(bs) &&
1664
            (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1665
            bdrv_flush(bs);
1666
        }
1667
    }
1668
}
1669

    
1670
int bdrv_has_zero_init(BlockDriverState *bs)
1671
{
1672
    assert(bs->drv);
1673

    
1674
    if (bs->drv->bdrv_has_zero_init) {
1675
        return bs->drv->bdrv_has_zero_init(bs);
1676
    }
1677

    
1678
    return 1;
1679
}
1680

    
1681
int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1682
{
1683
    if (!bs->drv) {
1684
        return -ENOMEDIUM;
1685
    }
1686
    if (!bs->drv->bdrv_discard) {
1687
        return 0;
1688
    }
1689
    return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1690
}
1691

    
1692
/*
1693
 * Returns true iff the specified sector is present in the disk image. Drivers
1694
 * not implementing the functionality are assumed to not support backing files,
1695
 * hence all their sectors are reported as allocated.
1696
 *
1697
 * 'pnum' is set to the number of sectors (including and immediately following
1698
 * the specified sector) that are known to be in the same
1699
 * allocated/unallocated state.
1700
 *
1701
 * 'nb_sectors' is the max value 'pnum' should be set to.
1702
 */
1703
int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1704
        int *pnum)
1705
{
1706
    int64_t n;
1707
    if (!bs->drv->bdrv_is_allocated) {
1708
        if (sector_num >= bs->total_sectors) {
1709
            *pnum = 0;
1710
            return 0;
1711
        }
1712
        n = bs->total_sectors - sector_num;
1713
        *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1714
        return 1;
1715
    }
1716
    return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1717
}
1718

    
1719
void bdrv_mon_event(const BlockDriverState *bdrv,
1720
                    BlockMonEventAction action, int is_read)
1721
{
1722
    QObject *data;
1723
    const char *action_str;
1724

    
1725
    switch (action) {
1726
    case BDRV_ACTION_REPORT:
1727
        action_str = "report";
1728
        break;
1729
    case BDRV_ACTION_IGNORE:
1730
        action_str = "ignore";
1731
        break;
1732
    case BDRV_ACTION_STOP:
1733
        action_str = "stop";
1734
        break;
1735
    default:
1736
        abort();
1737
    }
1738

    
1739
    data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1740
                              bdrv->device_name,
1741
                              action_str,
1742
                              is_read ? "read" : "write");
1743
    monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1744

    
1745
    qobject_decref(data);
1746
}
1747

    
1748
static void bdrv_print_dict(QObject *obj, void *opaque)
1749
{
1750
    QDict *bs_dict;
1751
    Monitor *mon = opaque;
1752

    
1753
    bs_dict = qobject_to_qdict(obj);
1754

    
1755
    monitor_printf(mon, "%s: removable=%d",
1756
                        qdict_get_str(bs_dict, "device"),
1757
                        qdict_get_bool(bs_dict, "removable"));
1758

    
1759
    if (qdict_get_bool(bs_dict, "removable")) {
1760
        monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1761
    }
1762

    
1763
    if (qdict_haskey(bs_dict, "inserted")) {
1764
        QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1765

    
1766
        monitor_printf(mon, " file=");
1767
        monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1768
        if (qdict_haskey(qdict, "backing_file")) {
1769
            monitor_printf(mon, " backing_file=");
1770
            monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1771
        }
1772
        monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1773
                            qdict_get_bool(qdict, "ro"),
1774
                            qdict_get_str(qdict, "drv"),
1775
                            qdict_get_bool(qdict, "encrypted"));
1776
    } else {
1777
        monitor_printf(mon, " [not inserted]");
1778
    }
1779

    
1780
    monitor_printf(mon, "\n");
1781
}
1782

    
1783
void bdrv_info_print(Monitor *mon, const QObject *data)
1784
{
1785
    qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1786
}
1787

    
1788
void bdrv_info(Monitor *mon, QObject **ret_data)
1789
{
1790
    QList *bs_list;
1791
    BlockDriverState *bs;
1792

    
1793
    bs_list = qlist_new();
1794

    
1795
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1796
        QObject *bs_obj;
1797

    
1798
        bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1799
                                    "'removable': %i, 'locked': %i }",
1800
                                    bs->device_name, bs->removable,
1801
                                    bs->locked);
1802

    
1803
        if (bs->drv) {
1804
            QObject *obj;
1805
            QDict *bs_dict = qobject_to_qdict(bs_obj);
1806

    
1807
            obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1808
                                     "'encrypted': %i }",
1809
                                     bs->filename, bs->read_only,
1810
                                     bs->drv->format_name,
1811
                                     bdrv_is_encrypted(bs));
1812
            if (bs->backing_file[0] != '\0') {
1813
                QDict *qdict = qobject_to_qdict(obj);
1814
                qdict_put(qdict, "backing_file",
1815
                          qstring_from_str(bs->backing_file));
1816
            }
1817

    
1818
            qdict_put_obj(bs_dict, "inserted", obj);
1819
        }
1820
        qlist_append_obj(bs_list, bs_obj);
1821
    }
1822

    
1823
    *ret_data = QOBJECT(bs_list);
1824
}
1825

    
1826
static void bdrv_stats_iter(QObject *data, void *opaque)
1827
{
1828
    QDict *qdict;
1829
    Monitor *mon = opaque;
1830

    
1831
    qdict = qobject_to_qdict(data);
1832
    monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1833

    
1834
    qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1835
    monitor_printf(mon, " rd_bytes=%" PRId64
1836
                        " wr_bytes=%" PRId64
1837
                        " rd_operations=%" PRId64
1838
                        " wr_operations=%" PRId64
1839
                        "\n",
1840
                        qdict_get_int(qdict, "rd_bytes"),
1841
                        qdict_get_int(qdict, "wr_bytes"),
1842
                        qdict_get_int(qdict, "rd_operations"),
1843
                        qdict_get_int(qdict, "wr_operations"));
1844
}
1845

    
1846
void bdrv_stats_print(Monitor *mon, const QObject *data)
1847
{
1848
    qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1849
}
1850

    
1851
static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1852
{
1853
    QObject *res;
1854
    QDict *dict;
1855

    
1856
    res = qobject_from_jsonf("{ 'stats': {"
1857
                             "'rd_bytes': %" PRId64 ","
1858
                             "'wr_bytes': %" PRId64 ","
1859
                             "'rd_operations': %" PRId64 ","
1860
                             "'wr_operations': %" PRId64 ","
1861
                             "'wr_highest_offset': %" PRId64
1862
                             "} }",
1863
                             bs->rd_bytes, bs->wr_bytes,
1864
                             bs->rd_ops, bs->wr_ops,
1865
                             bs->wr_highest_sector *
1866
                             (uint64_t)BDRV_SECTOR_SIZE);
1867
    dict  = qobject_to_qdict(res);
1868

    
1869
    if (*bs->device_name) {
1870
        qdict_put(dict, "device", qstring_from_str(bs->device_name));
1871
    }
1872

    
1873
    if (bs->file) {
1874
        QObject *parent = bdrv_info_stats_bs(bs->file);
1875
        qdict_put_obj(dict, "parent", parent);
1876
    }
1877

    
1878
    return res;
1879
}
1880

    
1881
void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1882
{
1883
    QObject *obj;
1884
    QList *devices;
1885
    BlockDriverState *bs;
1886

    
1887
    devices = qlist_new();
1888

    
1889
    QTAILQ_FOREACH(bs, &bdrv_states, list) {
1890
        obj = bdrv_info_stats_bs(bs);
1891
        qlist_append_obj(devices, obj);
1892
    }
1893

    
1894
    *ret_data = QOBJECT(devices);
1895
}
1896

    
1897
const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1898
{
1899
    if (bs->backing_hd && bs->backing_hd->encrypted)
1900
        return bs->backing_file;
1901
    else if (bs->encrypted)
1902
        return bs->filename;
1903
    else
1904
        return NULL;
1905
}
1906

    
1907
void bdrv_get_backing_filename(BlockDriverState *bs,
1908
                               char *filename, int filename_size)
1909
{
1910
    if (!bs->backing_file) {
1911
        pstrcpy(filename, filename_size, "");
1912
    } else {
1913
        pstrcpy(filename, filename_size, bs->backing_file);
1914
    }
1915
}
1916

    
1917
int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1918
                          const uint8_t *buf, int nb_sectors)
1919
{
1920
    BlockDriver *drv = bs->drv;
1921
    if (!drv)
1922
        return -ENOMEDIUM;
1923
    if (!drv->bdrv_write_compressed)
1924
        return -ENOTSUP;
1925
    if (bdrv_check_request(bs, sector_num, nb_sectors))
1926
        return -EIO;
1927

    
1928
    if (bs->dirty_bitmap) {
1929
        set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1930
    }
1931

    
1932
    return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1933
}
1934

    
1935
int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1936
{
1937
    BlockDriver *drv = bs->drv;
1938
    if (!drv)
1939
        return -ENOMEDIUM;
1940
    if (!drv->bdrv_get_info)
1941
        return -ENOTSUP;
1942
    memset(bdi, 0, sizeof(*bdi));
1943
    return drv->bdrv_get_info(bs, bdi);
1944
}
1945

    
1946
int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1947
                      int64_t pos, int size)
1948
{
1949
    BlockDriver *drv = bs->drv;
1950
    if (!drv)
1951
        return -ENOMEDIUM;
1952
    if (drv->bdrv_save_vmstate)
1953
        return drv->bdrv_save_vmstate(bs, buf, pos, size);
1954
    if (bs->file)
1955
        return bdrv_save_vmstate(bs->file, buf, pos, size);
1956
    return -ENOTSUP;
1957
}
1958

    
1959
int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1960
                      int64_t pos, int size)
1961
{
1962
    BlockDriver *drv = bs->drv;
1963
    if (!drv)
1964
        return -ENOMEDIUM;
1965
    if (drv->bdrv_load_vmstate)
1966
        return drv->bdrv_load_vmstate(bs, buf, pos, size);
1967
    if (bs->file)
1968
        return bdrv_load_vmstate(bs->file, buf, pos, size);
1969
    return -ENOTSUP;
1970
}
1971

    
1972
void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1973
{
1974
    BlockDriver *drv = bs->drv;
1975

    
1976
    if (!drv || !drv->bdrv_debug_event) {
1977
        return;
1978
    }
1979

    
1980
    return drv->bdrv_debug_event(bs, event);
1981

    
1982
}
1983

    
1984
/**************************************************************/
1985
/* handling of snapshots */
1986

    
1987
int bdrv_can_snapshot(BlockDriverState *bs)
1988
{
1989
    BlockDriver *drv = bs->drv;
1990
    if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1991
        return 0;
1992
    }
1993

    
1994
    if (!drv->bdrv_snapshot_create) {
1995
        if (bs->file != NULL) {
1996
            return bdrv_can_snapshot(bs->file);
1997
        }
1998
        return 0;
1999
    }
2000

    
2001
    return 1;
2002
}
2003

    
2004
int bdrv_is_snapshot(BlockDriverState *bs)
2005
{
2006
    return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2007
}
2008

    
2009
BlockDriverState *bdrv_snapshots(void)
2010
{
2011
    BlockDriverState *bs;
2012

    
2013
    if (bs_snapshots) {
2014
        return bs_snapshots;
2015
    }
2016

    
2017
    bs = NULL;
2018
    while ((bs = bdrv_next(bs))) {
2019
        if (bdrv_can_snapshot(bs)) {
2020
            bs_snapshots = bs;
2021
            return bs;
2022
        }
2023
    }
2024
    return NULL;
2025
}
2026

    
2027
int bdrv_snapshot_create(BlockDriverState *bs,
2028
                         QEMUSnapshotInfo *sn_info)
2029
{
2030
    BlockDriver *drv = bs->drv;
2031
    if (!drv)
2032
        return -ENOMEDIUM;
2033
    if (drv->bdrv_snapshot_create)
2034
        return drv->bdrv_snapshot_create(bs, sn_info);
2035
    if (bs->file)
2036
        return bdrv_snapshot_create(bs->file, sn_info);
2037
    return -ENOTSUP;
2038
}
2039

    
2040
int bdrv_snapshot_goto(BlockDriverState *bs,
2041
                       const char *snapshot_id)
2042
{
2043
    BlockDriver *drv = bs->drv;
2044
    int ret, open_ret;
2045

    
2046
    if (!drv)
2047
        return -ENOMEDIUM;
2048
    if (drv->bdrv_snapshot_goto)
2049
        return drv->bdrv_snapshot_goto(bs, snapshot_id);
2050

    
2051
    if (bs->file) {
2052
        drv->bdrv_close(bs);
2053
        ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2054
        open_ret = drv->bdrv_open(bs, bs->open_flags);
2055
        if (open_ret < 0) {
2056
            bdrv_delete(bs->file);
2057
            bs->drv = NULL;
2058
            return open_ret;
2059
        }
2060
        return ret;
2061
    }
2062

    
2063
    return -ENOTSUP;
2064
}
2065

    
2066
int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2067
{
2068
    BlockDriver *drv = bs->drv;
2069
    if (!drv)
2070
        return -ENOMEDIUM;
2071
    if (drv->bdrv_snapshot_delete)
2072
        return drv->bdrv_snapshot_delete(bs, snapshot_id);
2073
    if (bs->file)
2074
        return bdrv_snapshot_delete(bs->file, snapshot_id);
2075
    return -ENOTSUP;
2076
}
2077

    
2078
int bdrv_snapshot_list(BlockDriverState *bs,
2079
                       QEMUSnapshotInfo **psn_info)
2080
{
2081
    BlockDriver *drv = bs->drv;
2082
    if (!drv)
2083
        return -ENOMEDIUM;
2084
    if (drv->bdrv_snapshot_list)
2085
        return drv->bdrv_snapshot_list(bs, psn_info);
2086
    if (bs->file)
2087
        return bdrv_snapshot_list(bs->file, psn_info);
2088
    return -ENOTSUP;
2089
}
2090

    
2091
int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2092
        const char *snapshot_name)
2093
{
2094
    BlockDriver *drv = bs->drv;
2095
    if (!drv) {
2096
        return -ENOMEDIUM;
2097
    }
2098
    if (!bs->read_only) {
2099
        return -EINVAL;
2100
    }
2101
    if (drv->bdrv_snapshot_load_tmp) {
2102
        return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2103
    }
2104
    return -ENOTSUP;
2105
}
2106

    
2107
#define NB_SUFFIXES 4
2108

    
2109
char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2110
{
2111
    static const char suffixes[NB_SUFFIXES] = "KMGT";
2112
    int64_t base;
2113
    int i;
2114

    
2115
    if (size <= 999) {
2116
        snprintf(buf, buf_size, "%" PRId64, size);
2117
    } else {
2118
        base = 1024;
2119
        for(i = 0; i < NB_SUFFIXES; i++) {
2120
            if (size < (10 * base)) {
2121
                snprintf(buf, buf_size, "%0.1f%c",
2122
                         (double)size / base,
2123
                         suffixes[i]);
2124
                break;
2125
            } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2126
                snprintf(buf, buf_size, "%" PRId64 "%c",
2127
                         ((size + (base >> 1)) / base),
2128
                         suffixes[i]);
2129
                break;
2130
            }
2131
            base = base * 1024;
2132
        }
2133
    }
2134
    return buf;
2135
}
2136

    
2137
char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2138
{
2139
    char buf1[128], date_buf[128], clock_buf[128];
2140
#ifdef _WIN32
2141
    struct tm *ptm;
2142
#else
2143
    struct tm tm;
2144
#endif
2145
    time_t ti;
2146
    int64_t secs;
2147

    
2148
    if (!sn) {
2149
        snprintf(buf, buf_size,
2150
                 "%-10s%-20s%7s%20s%15s",
2151
                 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2152
    } else {
2153
        ti = sn->date_sec;
2154
#ifdef _WIN32
2155
        ptm = localtime(&ti);
2156
        strftime(date_buf, sizeof(date_buf),
2157
                 "%Y-%m-%d %H:%M:%S", ptm);
2158
#else
2159
        localtime_r(&ti, &tm);
2160
        strftime(date_buf, sizeof(date_buf),
2161
                 "%Y-%m-%d %H:%M:%S", &tm);
2162
#endif
2163
        secs = sn->vm_clock_nsec / 1000000000;
2164
        snprintf(clock_buf, sizeof(clock_buf),
2165
                 "%02d:%02d:%02d.%03d",
2166
                 (int)(secs / 3600),
2167
                 (int)((secs / 60) % 60),
2168
                 (int)(secs % 60),
2169
                 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2170
        snprintf(buf, buf_size,
2171
                 "%-10s%-20s%7s%20s%15s",
2172
                 sn->id_str, sn->name,
2173
                 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2174
                 date_buf,
2175
                 clock_buf);
2176
    }
2177
    return buf;
2178
}
2179

    
2180

    
2181
/**************************************************************/
2182
/* async I/Os */
2183

    
2184
BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2185
                                 QEMUIOVector *qiov, int nb_sectors,
2186
                                 BlockDriverCompletionFunc *cb, void *opaque)
2187
{
2188
    BlockDriver *drv = bs->drv;
2189
    BlockDriverAIOCB *ret;
2190

    
2191
    trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2192

    
2193
    if (!drv)
2194
        return NULL;
2195
    if (bdrv_check_request(bs, sector_num, nb_sectors))
2196
        return NULL;
2197

    
2198
    ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2199
                              cb, opaque);
2200

    
2201
    if (ret) {
2202
        /* Update stats even though technically transfer has not happened. */
2203
        bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2204
        bs->rd_ops ++;
2205
    }
2206

    
2207
    return ret;
2208
}
2209

    
2210
typedef struct BlockCompleteData {
2211
    BlockDriverCompletionFunc *cb;
2212
    void *opaque;
2213
    BlockDriverState *bs;
2214
    int64_t sector_num;
2215
    int nb_sectors;
2216
} BlockCompleteData;
2217

    
2218
static void block_complete_cb(void *opaque, int ret)
2219
{
2220
    BlockCompleteData *b = opaque;
2221

    
2222
    if (b->bs->dirty_bitmap) {
2223
        set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2224
    }
2225
    b->cb(b->opaque, ret);
2226
    qemu_free(b);
2227
}
2228

    
2229
static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2230
                                             int64_t sector_num,
2231
                                             int nb_sectors,
2232
                                             BlockDriverCompletionFunc *cb,
2233
                                             void *opaque)
2234
{
2235
    BlockCompleteData *blkdata = qemu_mallocz(sizeof(BlockCompleteData));
2236

    
2237
    blkdata->bs = bs;
2238
    blkdata->cb = cb;
2239
    blkdata->opaque = opaque;
2240
    blkdata->sector_num = sector_num;
2241
    blkdata->nb_sectors = nb_sectors;
2242

    
2243
    return blkdata;
2244
}
2245

    
2246
BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2247
                                  QEMUIOVector *qiov, int nb_sectors,
2248
                                  BlockDriverCompletionFunc *cb, void *opaque)
2249
{
2250
    BlockDriver *drv = bs->drv;
2251
    BlockDriverAIOCB *ret;
2252
    BlockCompleteData *blk_cb_data;
2253

    
2254
    trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2255

    
2256
    if (!drv)
2257
        return NULL;
2258
    if (bs->read_only)
2259
        return NULL;
2260
    if (bdrv_check_request(bs, sector_num, nb_sectors))
2261
        return NULL;
2262

    
2263
    if (bs->dirty_bitmap) {
2264
        blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2265
                                         opaque);
2266
        cb = &block_complete_cb;
2267
        opaque = blk_cb_data;
2268
    }
2269

    
2270
    ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2271
                               cb, opaque);
2272

    
2273
    if (ret) {
2274
        /* Update stats even though technically transfer has not happened. */
2275
        bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
2276
        bs->wr_ops ++;
2277
        if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2278
            bs->wr_highest_sector = sector_num + nb_sectors - 1;
2279
        }
2280
    }
2281

    
2282
    return ret;
2283
}
2284

    
2285

    
2286
typedef struct MultiwriteCB {
2287
    int error;
2288
    int num_requests;
2289
    int num_callbacks;
2290
    struct {
2291
        BlockDriverCompletionFunc *cb;
2292
        void *opaque;
2293
        QEMUIOVector *free_qiov;
2294
        void *free_buf;
2295
    } callbacks[];
2296
} MultiwriteCB;
2297

    
2298
static void multiwrite_user_cb(MultiwriteCB *mcb)
2299
{
2300
    int i;
2301

    
2302
    for (i = 0; i < mcb->num_callbacks; i++) {
2303
        mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2304
        if (mcb->callbacks[i].free_qiov) {
2305
            qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2306
        }
2307
        qemu_free(mcb->callbacks[i].free_qiov);
2308
        qemu_vfree(mcb->callbacks[i].free_buf);
2309
    }
2310
}
2311

    
2312
static void multiwrite_cb(void *opaque, int ret)
2313
{
2314
    MultiwriteCB *mcb = opaque;
2315

    
2316
    trace_multiwrite_cb(mcb, ret);
2317

    
2318
    if (ret < 0 && !mcb->error) {
2319
        mcb->error = ret;
2320
    }
2321

    
2322
    mcb->num_requests--;
2323
    if (mcb->num_requests == 0) {
2324
        multiwrite_user_cb(mcb);
2325
        qemu_free(mcb);
2326
    }
2327
}
2328

    
2329
static int multiwrite_req_compare(const void *a, const void *b)
2330
{
2331
    const BlockRequest *req1 = a, *req2 = b;
2332

    
2333
    /*
2334
     * Note that we can't simply subtract req2->sector from req1->sector
2335
     * here as that could overflow the return value.
2336
     */
2337
    if (req1->sector > req2->sector) {
2338
        return 1;
2339
    } else if (req1->sector < req2->sector) {
2340
        return -1;
2341
    } else {
2342
        return 0;
2343
    }
2344
}
2345

    
2346
/*
2347
 * Takes a bunch of requests and tries to merge them. Returns the number of
2348
 * requests that remain after merging.
2349
 */
2350
static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2351
    int num_reqs, MultiwriteCB *mcb)
2352
{
2353
    int i, outidx;
2354

    
2355
    // Sort requests by start sector
2356
    qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2357

    
2358
    // Check if adjacent requests touch the same clusters. If so, combine them,
2359
    // filling up gaps with zero sectors.
2360
    outidx = 0;
2361
    for (i = 1; i < num_reqs; i++) {
2362
        int merge = 0;
2363
        int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2364

    
2365
        // This handles the cases that are valid for all block drivers, namely
2366
        // exactly sequential writes and overlapping writes.
2367
        if (reqs[i].sector <= oldreq_last) {
2368
            merge = 1;
2369
        }
2370

    
2371
        // The block driver may decide that it makes sense to combine requests
2372
        // even if there is a gap of some sectors between them. In this case,
2373
        // the gap is filled with zeros (therefore only applicable for yet
2374
        // unused space in format like qcow2).
2375
        if (!merge && bs->drv->bdrv_merge_requests) {
2376
            merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2377
        }
2378

    
2379
        if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2380
            merge = 0;
2381
        }
2382

    
2383
        if (merge) {
2384
            size_t size;
2385
            QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2386
            qemu_iovec_init(qiov,
2387
                reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2388

    
2389
            // Add the first request to the merged one. If the requests are
2390
            // overlapping, drop the last sectors of the first request.
2391
            size = (reqs[i].sector - reqs[outidx].sector) << 9;
2392
            qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2393

    
2394
            // We might need to add some zeros between the two requests
2395
            if (reqs[i].sector > oldreq_last) {
2396
                size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2397
                uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2398
                memset(buf, 0, zero_bytes);
2399
                qemu_iovec_add(qiov, buf, zero_bytes);
2400
                mcb->callbacks[i].free_buf = buf;
2401
            }
2402

    
2403
            // Add the second request
2404
            qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2405

    
2406
            reqs[outidx].nb_sectors = qiov->size >> 9;
2407
            reqs[outidx].qiov = qiov;
2408

    
2409
            mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2410
        } else {
2411
            outidx++;
2412
            reqs[outidx].sector     = reqs[i].sector;
2413
            reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2414
            reqs[outidx].qiov       = reqs[i].qiov;
2415
        }
2416
    }
2417

    
2418
    return outidx + 1;
2419
}
2420

    
2421
/*
2422
 * Submit multiple AIO write requests at once.
2423
 *
2424
 * On success, the function returns 0 and all requests in the reqs array have
2425
 * been submitted. In error case this function returns -1, and any of the
2426
 * requests may or may not be submitted yet. In particular, this means that the
2427
 * callback will be called for some of the requests, for others it won't. The
2428
 * caller must check the error field of the BlockRequest to wait for the right
2429
 * callbacks (if error != 0, no callback will be called).
2430
 *
2431
 * The implementation may modify the contents of the reqs array, e.g. to merge
2432
 * requests. However, the fields opaque and error are left unmodified as they
2433
 * are used to signal failure for a single request to the caller.
2434
 */
2435
int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2436
{
2437
    BlockDriverAIOCB *acb;
2438
    MultiwriteCB *mcb;
2439
    int i;
2440

    
2441
    /* don't submit writes if we don't have a medium */
2442
    if (bs->drv == NULL) {
2443
        for (i = 0; i < num_reqs; i++) {
2444
            reqs[i].error = -ENOMEDIUM;
2445
        }
2446
        return -1;
2447
    }
2448

    
2449
    if (num_reqs == 0) {
2450
        return 0;
2451
    }
2452

    
2453
    // Create MultiwriteCB structure
2454
    mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2455
    mcb->num_requests = 0;
2456
    mcb->num_callbacks = num_reqs;
2457

    
2458
    for (i = 0; i < num_reqs; i++) {
2459
        mcb->callbacks[i].cb = reqs[i].cb;
2460
        mcb->callbacks[i].opaque = reqs[i].opaque;
2461
    }
2462

    
2463
    // Check for mergable requests
2464
    num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2465

    
2466
    trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2467

    
2468
    /*
2469
     * Run the aio requests. As soon as one request can't be submitted
2470
     * successfully, fail all requests that are not yet submitted (we must
2471
     * return failure for all requests anyway)
2472
     *
2473
     * num_requests cannot be set to the right value immediately: If
2474
     * bdrv_aio_writev fails for some request, num_requests would be too high
2475
     * and therefore multiwrite_cb() would never recognize the multiwrite
2476
     * request as completed. We also cannot use the loop variable i to set it
2477
     * when the first request fails because the callback may already have been
2478
     * called for previously submitted requests. Thus, num_requests must be
2479
     * incremented for each request that is submitted.
2480
     *
2481
     * The problem that callbacks may be called early also means that we need
2482
     * to take care that num_requests doesn't become 0 before all requests are
2483
     * submitted - multiwrite_cb() would consider the multiwrite request
2484
     * completed. A dummy request that is "completed" by a manual call to
2485
     * multiwrite_cb() takes care of this.
2486
     */
2487
    mcb->num_requests = 1;
2488

    
2489
    // Run the aio requests
2490
    for (i = 0; i < num_reqs; i++) {
2491
        mcb->num_requests++;
2492
        acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2493
            reqs[i].nb_sectors, multiwrite_cb, mcb);
2494

    
2495
        if (acb == NULL) {
2496
            // We can only fail the whole thing if no request has been
2497
            // submitted yet. Otherwise we'll wait for the submitted AIOs to
2498
            // complete and report the error in the callback.
2499
            if (i == 0) {
2500
                trace_bdrv_aio_multiwrite_earlyfail(mcb);
2501
                goto fail;
2502
            } else {
2503
                trace_bdrv_aio_multiwrite_latefail(mcb, i);
2504
                multiwrite_cb(mcb, -EIO);
2505
                break;
2506
            }
2507
        }
2508
    }
2509

    
2510
    /* Complete the dummy request */
2511
    multiwrite_cb(mcb, 0);
2512

    
2513
    return 0;
2514

    
2515
fail:
2516
    for (i = 0; i < mcb->num_callbacks; i++) {
2517
        reqs[i].error = -EIO;
2518
    }
2519
    qemu_free(mcb);
2520
    return -1;
2521
}
2522

    
2523
BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2524
        BlockDriverCompletionFunc *cb, void *opaque)
2525
{
2526
    BlockDriver *drv = bs->drv;
2527

    
2528
    trace_bdrv_aio_flush(bs, opaque);
2529

    
2530
    if (bs->open_flags & BDRV_O_NO_FLUSH) {
2531
        return bdrv_aio_noop_em(bs, cb, opaque);
2532
    }
2533

    
2534
    if (!drv)
2535
        return NULL;
2536
    return drv->bdrv_aio_flush(bs, cb, opaque);
2537
}
2538

    
2539
void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2540
{
2541
    acb->pool->cancel(acb);
2542
}
2543

    
2544

    
2545
/**************************************************************/
2546
/* async block device emulation */
2547

    
2548
typedef struct BlockDriverAIOCBSync {
2549
    BlockDriverAIOCB common;
2550
    QEMUBH *bh;
2551
    int ret;
2552
    /* vector translation state */
2553
    QEMUIOVector *qiov;
2554
    uint8_t *bounce;
2555
    int is_write;
2556
} BlockDriverAIOCBSync;
2557

    
2558
static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2559
{
2560
    BlockDriverAIOCBSync *acb =
2561
        container_of(blockacb, BlockDriverAIOCBSync, common);
2562
    qemu_bh_delete(acb->bh);
2563
    acb->bh = NULL;
2564
    qemu_aio_release(acb);
2565
}
2566

    
2567
static AIOPool bdrv_em_aio_pool = {
2568
    .aiocb_size         = sizeof(BlockDriverAIOCBSync),
2569
    .cancel             = bdrv_aio_cancel_em,
2570
};
2571

    
2572
static void bdrv_aio_bh_cb(void *opaque)
2573
{
2574
    BlockDriverAIOCBSync *acb = opaque;
2575

    
2576
    if (!acb->is_write)
2577
        qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2578
    qemu_vfree(acb->bounce);
2579
    acb->common.cb(acb->common.opaque, acb->ret);
2580
    qemu_bh_delete(acb->bh);
2581
    acb->bh = NULL;
2582
    qemu_aio_release(acb);
2583
}
2584

    
2585
static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2586
                                            int64_t sector_num,
2587
                                            QEMUIOVector *qiov,
2588
                                            int nb_sectors,
2589
                                            BlockDriverCompletionFunc *cb,
2590
                                            void *opaque,
2591
                                            int is_write)
2592

    
2593
{
2594
    BlockDriverAIOCBSync *acb;
2595

    
2596
    acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2597
    acb->is_write = is_write;
2598
    acb->qiov = qiov;
2599
    acb->bounce = qemu_blockalign(bs, qiov->size);
2600

    
2601
    if (!acb->bh)
2602
        acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2603

    
2604
    if (is_write) {
2605
        qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2606
        acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2607
    } else {
2608
        acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2609
    }
2610

    
2611
    qemu_bh_schedule(acb->bh);
2612

    
2613
    return &acb->common;
2614
}
2615

    
2616
static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2617
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2618
        BlockDriverCompletionFunc *cb, void *opaque)
2619
{
2620
    return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2621
}
2622

    
2623
static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2624
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2625
        BlockDriverCompletionFunc *cb, void *opaque)
2626
{
2627
    return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2628
}
2629

    
2630

    
2631
typedef struct BlockDriverAIOCBCoroutine {
2632
    BlockDriverAIOCB common;
2633
    BlockRequest req;
2634
    bool is_write;
2635
    QEMUBH* bh;
2636
} BlockDriverAIOCBCoroutine;
2637

    
2638
static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2639
{
2640
    qemu_aio_flush();
2641
}
2642

    
2643
static AIOPool bdrv_em_co_aio_pool = {
2644
    .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
2645
    .cancel             = bdrv_aio_co_cancel_em,
2646
};
2647

    
2648
static void bdrv_co_rw_bh(void *opaque)
2649
{
2650
    BlockDriverAIOCBCoroutine *acb = opaque;
2651

    
2652
    acb->common.cb(acb->common.opaque, acb->req.error);
2653
    qemu_bh_delete(acb->bh);
2654
    qemu_aio_release(acb);
2655
}
2656

    
2657
static void coroutine_fn bdrv_co_rw(void *opaque)
2658
{
2659
    BlockDriverAIOCBCoroutine *acb = opaque;
2660
    BlockDriverState *bs = acb->common.bs;
2661

    
2662
    if (!acb->is_write) {
2663
        acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2664
            acb->req.nb_sectors, acb->req.qiov);
2665
    } else {
2666
        acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2667
            acb->req.nb_sectors, acb->req.qiov);
2668
    }
2669

    
2670
    acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2671
    qemu_bh_schedule(acb->bh);
2672
}
2673

    
2674
static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2675
                                               int64_t sector_num,
2676
                                               QEMUIOVector *qiov,
2677
                                               int nb_sectors,
2678
                                               BlockDriverCompletionFunc *cb,
2679
                                               void *opaque,
2680
                                               bool is_write)
2681
{
2682
    Coroutine *co;
2683
    BlockDriverAIOCBCoroutine *acb;
2684

    
2685
    acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2686
    acb->req.sector = sector_num;
2687
    acb->req.nb_sectors = nb_sectors;
2688
    acb->req.qiov = qiov;
2689
    acb->is_write = is_write;
2690

    
2691
    co = qemu_coroutine_create(bdrv_co_rw);
2692
    qemu_coroutine_enter(co, acb);
2693

    
2694
    return &acb->common;
2695
}
2696

    
2697
static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2698
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2699
        BlockDriverCompletionFunc *cb, void *opaque)
2700
{
2701
    return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2702
                                 false);
2703
}
2704

    
2705
static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2706
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2707
        BlockDriverCompletionFunc *cb, void *opaque)
2708
{
2709
    return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2710
                                 true);
2711
}
2712

    
2713
static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2714
        BlockDriverCompletionFunc *cb, void *opaque)
2715
{
2716
    BlockDriverAIOCBSync *acb;
2717

    
2718
    acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2719
    acb->is_write = 1; /* don't bounce in the completion hadler */
2720
    acb->qiov = NULL;
2721
    acb->bounce = NULL;
2722
    acb->ret = 0;
2723

    
2724
    if (!acb->bh)
2725
        acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2726

    
2727
    bdrv_flush(bs);
2728
    qemu_bh_schedule(acb->bh);
2729
    return &acb->common;
2730
}
2731

    
2732
static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2733
        BlockDriverCompletionFunc *cb, void *opaque)
2734
{
2735
    BlockDriverAIOCBSync *acb;
2736

    
2737
    acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2738
    acb->is_write = 1; /* don't bounce in the completion handler */
2739
    acb->qiov = NULL;
2740
    acb->bounce = NULL;
2741
    acb->ret = 0;
2742

    
2743
    if (!acb->bh) {
2744
        acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2745
    }
2746

    
2747
    qemu_bh_schedule(acb->bh);
2748
    return &acb->common;
2749
}
2750

    
2751
/**************************************************************/
2752
/* sync block device emulation */
2753

    
2754
static void bdrv_rw_em_cb(void *opaque, int ret)
2755
{
2756
    *(int *)opaque = ret;
2757
}
2758

    
2759
#define NOT_DONE 0x7fffffff
2760

    
2761
static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2762
                        uint8_t *buf, int nb_sectors)
2763
{
2764
    int async_ret;
2765
    BlockDriverAIOCB *acb;
2766
    struct iovec iov;
2767
    QEMUIOVector qiov;
2768

    
2769
    async_context_push();
2770

    
2771
    async_ret = NOT_DONE;
2772
    iov.iov_base = (void *)buf;
2773
    iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2774
    qemu_iovec_init_external(&qiov, &iov, 1);
2775
    acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2776
        bdrv_rw_em_cb, &async_ret);
2777
    if (acb == NULL) {
2778
        async_ret = -1;
2779
        goto fail;
2780
    }
2781

    
2782
    while (async_ret == NOT_DONE) {
2783
        qemu_aio_wait();
2784
    }
2785

    
2786

    
2787
fail:
2788
    async_context_pop();
2789
    return async_ret;
2790
}
2791

    
2792
static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2793
                         const uint8_t *buf, int nb_sectors)
2794
{
2795
    int async_ret;
2796
    BlockDriverAIOCB *acb;
2797
    struct iovec iov;
2798
    QEMUIOVector qiov;
2799

    
2800
    async_context_push();
2801

    
2802
    async_ret = NOT_DONE;
2803
    iov.iov_base = (void *)buf;
2804
    iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2805
    qemu_iovec_init_external(&qiov, &iov, 1);
2806
    acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2807
        bdrv_rw_em_cb, &async_ret);
2808
    if (acb == NULL) {
2809
        async_ret = -1;
2810
        goto fail;
2811
    }
2812
    while (async_ret == NOT_DONE) {
2813
        qemu_aio_wait();
2814
    }
2815

    
2816
fail:
2817
    async_context_pop();
2818
    return async_ret;
2819
}
2820

    
2821
void bdrv_init(void)
2822
{
2823
    module_call_init(MODULE_INIT_BLOCK);
2824
}
2825

    
2826
void bdrv_init_with_whitelist(void)
2827
{
2828
    use_bdrv_whitelist = 1;
2829
    bdrv_init();
2830
}
2831

    
2832
void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2833
                   BlockDriverCompletionFunc *cb, void *opaque)
2834
{
2835
    BlockDriverAIOCB *acb;
2836

    
2837
    if (pool->free_aiocb) {
2838
        acb = pool->free_aiocb;
2839
        pool->free_aiocb = acb->next;
2840
    } else {
2841
        acb = qemu_mallocz(pool->aiocb_size);
2842
        acb->pool = pool;
2843
    }
2844
    acb->bs = bs;
2845
    acb->cb = cb;
2846
    acb->opaque = opaque;
2847
    return acb;
2848
}
2849

    
2850
void qemu_aio_release(void *p)
2851
{
2852
    BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2853
    AIOPool *pool = acb->pool;
2854
    acb->next = pool->free_aiocb;
2855
    pool->free_aiocb = acb;
2856
}
2857

    
2858
/**************************************************************/
2859
/* removable device support */
2860

    
2861
/**
2862
 * Return TRUE if the media is present
2863
 */
2864
int bdrv_is_inserted(BlockDriverState *bs)
2865
{
2866
    BlockDriver *drv = bs->drv;
2867
    int ret;
2868
    if (!drv)
2869
        return 0;
2870
    if (!drv->bdrv_is_inserted)
2871
        return !bs->tray_open;
2872
    ret = drv->bdrv_is_inserted(bs);
2873
    return ret;
2874
}
2875

    
2876
/**
2877
 * Return TRUE if the media changed since the last call to this
2878
 * function. It is currently only used for floppy disks
2879
 */
2880
int bdrv_media_changed(BlockDriverState *bs)
2881
{
2882
    BlockDriver *drv = bs->drv;
2883
    int ret;
2884

    
2885
    if (!drv || !drv->bdrv_media_changed)
2886
        ret = -ENOTSUP;
2887
    else
2888
        ret = drv->bdrv_media_changed(bs);
2889
    if (ret == -ENOTSUP)
2890
        ret = bs->media_changed;
2891
    bs->media_changed = 0;
2892
    return ret;
2893
}
2894

    
2895
/**
2896
 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2897
 */
2898
int bdrv_eject(BlockDriverState *bs, int eject_flag)
2899
{
2900
    BlockDriver *drv = bs->drv;
2901

    
2902
    if (eject_flag && bs->locked) {
2903
        return -EBUSY;
2904
    }
2905

    
2906
    if (drv && drv->bdrv_eject) {
2907
        drv->bdrv_eject(bs, eject_flag);
2908
    }
2909
    bs->tray_open = eject_flag;
2910
    return 0;
2911
}
2912

    
2913
int bdrv_is_locked(BlockDriverState *bs)
2914
{
2915
    return bs->locked;
2916
}
2917

    
2918
/**
2919
 * Lock or unlock the media (if it is locked, the user won't be able
2920
 * to eject it manually).
2921
 */
2922
void bdrv_set_locked(BlockDriverState *bs, int locked)
2923
{
2924
    BlockDriver *drv = bs->drv;
2925

    
2926
    trace_bdrv_set_locked(bs, locked);
2927

    
2928
    bs->locked = locked;
2929
    if (drv && drv->bdrv_set_locked) {
2930
        drv->bdrv_set_locked(bs, locked);
2931
    }
2932
}
2933

    
2934
/* needed for generic scsi interface */
2935

    
2936
int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2937
{
2938
    BlockDriver *drv = bs->drv;
2939

    
2940
    if (drv && drv->bdrv_ioctl)
2941
        return drv->bdrv_ioctl(bs, req, buf);
2942
    return -ENOTSUP;
2943
}
2944

    
2945
BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2946
        unsigned long int req, void *buf,
2947
        BlockDriverCompletionFunc *cb, void *opaque)
2948
{
2949
    BlockDriver *drv = bs->drv;
2950

    
2951
    if (drv && drv->bdrv_aio_ioctl)
2952
        return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2953
    return NULL;
2954
}
2955

    
2956

    
2957

    
2958
void *qemu_blockalign(BlockDriverState *bs, size_t size)
2959
{
2960
    return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2961
}
2962

    
2963
void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2964
{
2965
    int64_t bitmap_size;
2966

    
2967
    bs->dirty_count = 0;
2968
    if (enable) {
2969
        if (!bs->dirty_bitmap) {
2970
            bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2971
                    BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2972
            bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2973

    
2974
            bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2975
        }
2976
    } else {
2977
        if (bs->dirty_bitmap) {
2978
            qemu_free(bs->dirty_bitmap);
2979
            bs->dirty_bitmap = NULL;
2980
        }
2981
    }
2982
}
2983

    
2984
int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2985
{
2986
    int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2987

    
2988
    if (bs->dirty_bitmap &&
2989
        (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2990
        return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2991
            (1UL << (chunk % (sizeof(unsigned long) * 8))));
2992
    } else {
2993
        return 0;
2994
    }
2995
}
2996

    
2997
void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2998
                      int nr_sectors)
2999
{
3000
    set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3001
}
3002

    
3003
int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3004
{
3005
    return bs->dirty_count;
3006
}
3007

    
3008
void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3009
{
3010
    assert(bs->in_use != in_use);
3011
    bs->in_use = in_use;
3012
}
3013

    
3014
int bdrv_in_use(BlockDriverState *bs)
3015
{
3016
    return bs->in_use;
3017
}
3018

    
3019
int bdrv_img_create(const char *filename, const char *fmt,
3020
                    const char *base_filename, const char *base_fmt,
3021
                    char *options, uint64_t img_size, int flags)
3022
{
3023
    QEMUOptionParameter *param = NULL, *create_options = NULL;
3024
    QEMUOptionParameter *backing_fmt, *backing_file, *size;
3025
    BlockDriverState *bs = NULL;
3026
    BlockDriver *drv, *proto_drv;
3027
    BlockDriver *backing_drv = NULL;
3028
    int ret = 0;
3029

    
3030
    /* Find driver and parse its options */
3031
    drv = bdrv_find_format(fmt);
3032
    if (!drv) {
3033
        error_report("Unknown file format '%s'", fmt);
3034
        ret = -EINVAL;
3035
        goto out;
3036
    }
3037

    
3038
    proto_drv = bdrv_find_protocol(filename);
3039
    if (!proto_drv) {
3040
        error_report("Unknown protocol '%s'", filename);
3041
        ret = -EINVAL;
3042
        goto out;
3043
    }
3044

    
3045
    create_options = append_option_parameters(create_options,
3046
                                              drv->create_options);
3047
    create_options = append_option_parameters(create_options,
3048
                                              proto_drv->create_options);
3049

    
3050
    /* Create parameter list with default values */
3051
    param = parse_option_parameters("", create_options, param);
3052

    
3053
    set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3054

    
3055
    /* Parse -o options */
3056
    if (options) {
3057
        param = parse_option_parameters(options, create_options, param);
3058
        if (param == NULL) {
3059
            error_report("Invalid options for file format '%s'.", fmt);
3060
            ret = -EINVAL;
3061
            goto out;
3062
        }
3063
    }
3064

    
3065
    if (base_filename) {
3066
        if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3067
                                 base_filename)) {
3068
            error_report("Backing file not supported for file format '%s'",
3069
                         fmt);
3070
            ret = -EINVAL;
3071
            goto out;
3072
        }
3073
    }
3074

    
3075
    if (base_fmt) {
3076
        if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3077
            error_report("Backing file format not supported for file "
3078
                         "format '%s'", fmt);
3079
            ret = -EINVAL;
3080
            goto out;
3081
        }
3082
    }
3083

    
3084
    backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3085
    if (backing_file && backing_file->value.s) {
3086
        if (!strcmp(filename, backing_file->value.s)) {
3087
            error_report("Error: Trying to create an image with the "
3088
                         "same filename as the backing file");
3089
            ret = -EINVAL;
3090
            goto out;
3091
        }
3092
    }
3093

    
3094
    backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3095
    if (backing_fmt && backing_fmt->value.s) {
3096
        backing_drv = bdrv_find_format(backing_fmt->value.s);
3097
        if (!backing_drv) {
3098
            error_report("Unknown backing file format '%s'",
3099
                         backing_fmt->value.s);
3100
            ret = -EINVAL;
3101
            goto out;
3102
        }
3103
    }
3104

    
3105
    // The size for the image must always be specified, with one exception:
3106
    // If we are using a backing file, we can obtain the size from there
3107
    size = get_option_parameter(param, BLOCK_OPT_SIZE);
3108
    if (size && size->value.n == -1) {
3109
        if (backing_file && backing_file->value.s) {
3110
            uint64_t size;
3111
            char buf[32];
3112

    
3113
            bs = bdrv_new("");
3114

    
3115
            ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
3116
            if (ret < 0) {
3117
                error_report("Could not open '%s'", backing_file->value.s);
3118
                goto out;
3119
            }
3120
            bdrv_get_geometry(bs, &size);
3121
            size *= 512;
3122

    
3123
            snprintf(buf, sizeof(buf), "%" PRId64, size);
3124
            set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3125
        } else {
3126
            error_report("Image creation needs a size parameter");
3127
            ret = -EINVAL;
3128
            goto out;
3129
        }
3130
    }
3131

    
3132
    printf("Formatting '%s', fmt=%s ", filename, fmt);
3133
    print_option_parameters(param);
3134
    puts("");
3135

    
3136
    ret = bdrv_create(drv, filename, param);
3137

    
3138
    if (ret < 0) {
3139
        if (ret == -ENOTSUP) {
3140
            error_report("Formatting or formatting option not supported for "
3141
                         "file format '%s'", fmt);
3142
        } else if (ret == -EFBIG) {
3143
            error_report("The image size is too large for file format '%s'",
3144
                         fmt);
3145
        } else {
3146
            error_report("%s: error while creating %s: %s", filename, fmt,
3147
                         strerror(-ret));
3148
        }
3149
    }
3150

    
3151
out:
3152
    free_option_parameters(create_options);
3153
    free_option_parameters(param);
3154

    
3155
    if (bs) {
3156
        bdrv_delete(bs);
3157
    }
3158

    
3159
    return ret;
3160
}