Statistics
| Branch: | Revision:

root / block.c @ c16b5a2c

History | View | Annotate | Download (42.9 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
#ifdef HOST_BSD
26
/* include native header before sys-queue.h */
27
#include <sys/queue.h>
28
#endif
29

    
30
#include "qemu-common.h"
31
#include "monitor.h"
32
#include "block_int.h"
33
#include "module.h"
34

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

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

    
48
#define SECTOR_BITS 9
49
#define SECTOR_SIZE (1 << SECTOR_BITS)
50

    
51
static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
52
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
53
        BlockDriverCompletionFunc *cb, void *opaque);
54
static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
55
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
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

    
62
BlockDriverState *bdrv_first;
63

    
64
static BlockDriver *first_drv;
65

    
66
int path_is_absolute(const char *path)
67
{
68
    const char *p;
69
#ifdef _WIN32
70
    /* specific case for names like: "\\.\d:" */
71
    if (*path == '/' || *path == '\\')
72
        return 1;
73
#endif
74
    p = strchr(path, ':');
75
    if (p)
76
        p++;
77
    else
78
        p = path;
79
#ifdef _WIN32
80
    return (*p == '/' || *p == '\\');
81
#else
82
    return (*p == '/');
83
#endif
84
}
85

    
86
/* if filename is absolute, just copy it to dest. Otherwise, build a
87
   path to it by considering it is relative to base_path. URL are
88
   supported. */
89
void path_combine(char *dest, int dest_size,
90
                  const char *base_path,
91
                  const char *filename)
92
{
93
    const char *p, *p1;
94
    int len;
95

    
96
    if (dest_size <= 0)
97
        return;
98
    if (path_is_absolute(filename)) {
99
        pstrcpy(dest, dest_size, filename);
100
    } else {
101
        p = strchr(base_path, ':');
102
        if (p)
103
            p++;
104
        else
105
            p = base_path;
106
        p1 = strrchr(base_path, '/');
107
#ifdef _WIN32
108
        {
109
            const char *p2;
110
            p2 = strrchr(base_path, '\\');
111
            if (!p1 || p2 > p1)
112
                p1 = p2;
113
        }
114
#endif
115
        if (p1)
116
            p1++;
117
        else
118
            p1 = base_path;
119
        if (p1 > p)
120
            p = p1;
121
        len = p - base_path;
122
        if (len > dest_size - 1)
123
            len = dest_size - 1;
124
        memcpy(dest, base_path, len);
125
        dest[len] = '\0';
126
        pstrcat(dest, dest_size, filename);
127
    }
128
}
129

    
130
void bdrv_register(BlockDriver *bdrv)
131
{
132
    if (!bdrv->bdrv_aio_readv) {
133
        /* add AIO emulation layer */
134
        bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
135
        bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
136
    } else if (!bdrv->bdrv_read) {
137
        /* add synchronous IO emulation layer */
138
        bdrv->bdrv_read = bdrv_read_em;
139
        bdrv->bdrv_write = bdrv_write_em;
140
    }
141
    bdrv->next = first_drv;
142
    first_drv = bdrv;
143
}
144

    
145
/* create a new block device (by default it is empty) */
146
BlockDriverState *bdrv_new(const char *device_name)
147
{
148
    BlockDriverState **pbs, *bs;
149

    
150
    bs = qemu_mallocz(sizeof(BlockDriverState));
151
    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
152
    if (device_name[0] != '\0') {
153
        /* insert at the end */
154
        pbs = &bdrv_first;
155
        while (*pbs != NULL)
156
            pbs = &(*pbs)->next;
157
        *pbs = bs;
158
    }
159
    return bs;
160
}
161

    
162
BlockDriver *bdrv_find_format(const char *format_name)
163
{
164
    BlockDriver *drv1;
165
    for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
166
        if (!strcmp(drv1->format_name, format_name))
167
            return drv1;
168
    }
169
    return NULL;
170
}
171

    
172
int bdrv_create(BlockDriver *drv, const char* filename,
173
    QEMUOptionParameter *options)
174
{
175
    if (!drv->bdrv_create)
176
        return -ENOTSUP;
177

    
178
    return drv->bdrv_create(filename, options);
179
}
180

    
181
#ifdef _WIN32
182
void get_tmp_filename(char *filename, int size)
183
{
184
    char temp_dir[MAX_PATH];
185

    
186
    GetTempPath(MAX_PATH, temp_dir);
187
    GetTempFileName(temp_dir, "qem", 0, filename);
188
}
189
#else
190
void get_tmp_filename(char *filename, int size)
191
{
192
    int fd;
193
    const char *tmpdir;
194
    /* XXX: race condition possible */
195
    tmpdir = getenv("TMPDIR");
196
    if (!tmpdir)
197
        tmpdir = "/tmp";
198
    snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
199
    fd = mkstemp(filename);
200
    close(fd);
201
}
202
#endif
203

    
204
#ifdef _WIN32
205
static int is_windows_drive_prefix(const char *filename)
206
{
207
    return (((filename[0] >= 'a' && filename[0] <= 'z') ||
208
             (filename[0] >= 'A' && filename[0] <= 'Z')) &&
209
            filename[1] == ':');
210
}
211

    
212
static int is_windows_drive(const char *filename)
213
{
214
    if (is_windows_drive_prefix(filename) &&
215
        filename[2] == '\0')
216
        return 1;
217
    if (strstart(filename, "\\\\.\\", NULL) ||
218
        strstart(filename, "//./", NULL))
219
        return 1;
220
    return 0;
221
}
222
#endif
223

    
224
static BlockDriver *find_protocol(const char *filename)
225
{
226
    BlockDriver *drv1;
227
    char protocol[128];
228
    int len;
229
    const char *p;
230

    
231
#ifdef _WIN32
232
    if (is_windows_drive(filename) ||
233
        is_windows_drive_prefix(filename))
234
        return bdrv_find_format("raw");
235
#endif
236
    p = strchr(filename, ':');
237
    if (!p)
238
        return bdrv_find_format("raw");
239
    len = p - filename;
240
    if (len > sizeof(protocol) - 1)
241
        len = sizeof(protocol) - 1;
242
    memcpy(protocol, filename, len);
243
    protocol[len] = '\0';
244
    for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
245
        if (drv1->protocol_name &&
246
            !strcmp(drv1->protocol_name, protocol))
247
            return drv1;
248
    }
249
    return NULL;
250
}
251

    
252
/* XXX: force raw format if block or character device ? It would
253
   simplify the BSD case */
254
static BlockDriver *find_image_format(const char *filename)
255
{
256
    int ret, score, score_max;
257
    BlockDriver *drv1, *drv;
258
    uint8_t buf[2048];
259
    BlockDriverState *bs;
260

    
261
    /* detect host devices. By convention, /dev/cdrom[N] is always
262
       recognized as a host CDROM */
263
    if (strstart(filename, "/dev/cdrom", NULL))
264
        return bdrv_find_format("host_device");
265
#ifdef _WIN32
266
    if (is_windows_drive(filename))
267
        return bdrv_find_format("host_device");
268
#else
269
    {
270
        struct stat st;
271
        if (stat(filename, &st) >= 0 &&
272
            (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
273
            return bdrv_find_format("host_device");
274
        }
275
    }
276
#endif
277

    
278
    drv = find_protocol(filename);
279
    /* no need to test disk image formats for vvfat */
280
    if (drv && strcmp(drv->format_name, "vvfat") == 0)
281
        return drv;
282

    
283
    ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
284
    if (ret < 0)
285
        return NULL;
286
    ret = bdrv_pread(bs, 0, buf, sizeof(buf));
287
    bdrv_delete(bs);
288
    if (ret < 0) {
289
        return NULL;
290
    }
291

    
292
    score_max = 0;
293
    for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
294
        if (drv1->bdrv_probe) {
295
            score = drv1->bdrv_probe(buf, ret, filename);
296
            if (score > score_max) {
297
                score_max = score;
298
                drv = drv1;
299
            }
300
        }
301
    }
302
    return drv;
303
}
304

    
305
int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
306
{
307
    BlockDriverState *bs;
308
    int ret;
309

    
310
    bs = bdrv_new("");
311
    ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
312
    if (ret < 0) {
313
        bdrv_delete(bs);
314
        return ret;
315
    }
316
    bs->growable = 1;
317
    *pbs = bs;
318
    return 0;
319
}
320

    
321
int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
322
{
323
    return bdrv_open2(bs, filename, flags, NULL);
324
}
325

    
326
int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
327
               BlockDriver *drv)
328
{
329
    int ret, open_flags;
330
    char tmp_filename[PATH_MAX];
331
    char backing_filename[PATH_MAX];
332

    
333
    bs->read_only = 0;
334
    bs->is_temporary = 0;
335
    bs->encrypted = 0;
336
    bs->valid_key = 0;
337
    /* buffer_alignment defaulted to 512, drivers can change this value */
338
    bs->buffer_alignment = 512;
339

    
340
    if (flags & BDRV_O_SNAPSHOT) {
341
        BlockDriverState *bs1;
342
        int64_t total_size;
343
        int is_protocol = 0;
344
        BlockDriver *bdrv_qcow2;
345
        QEMUOptionParameter *options;
346

    
347
        /* if snapshot, we create a temporary backing file and open it
348
           instead of opening 'filename' directly */
349

    
350
        /* if there is a backing file, use it */
351
        bs1 = bdrv_new("");
352
        ret = bdrv_open2(bs1, filename, 0, drv);
353
        if (ret < 0) {
354
            bdrv_delete(bs1);
355
            return ret;
356
        }
357
        total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
358

    
359
        if (bs1->drv && bs1->drv->protocol_name)
360
            is_protocol = 1;
361

    
362
        bdrv_delete(bs1);
363

    
364
        get_tmp_filename(tmp_filename, sizeof(tmp_filename));
365

    
366
        /* Real path is meaningless for protocols */
367
        if (is_protocol)
368
            snprintf(backing_filename, sizeof(backing_filename),
369
                     "%s", filename);
370
        else
371
            realpath(filename, backing_filename);
372

    
373
        bdrv_qcow2 = bdrv_find_format("qcow2");
374
        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
375

    
376
        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
377
        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
378
        if (drv) {
379
            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
380
                drv->format_name);
381
        }
382

    
383
        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
384
        if (ret < 0) {
385
            return ret;
386
        }
387

    
388
        filename = tmp_filename;
389
        drv = bdrv_qcow2;
390
        bs->is_temporary = 1;
391
    }
392

    
393
    pstrcpy(bs->filename, sizeof(bs->filename), filename);
394
    if (flags & BDRV_O_FILE) {
395
        drv = find_protocol(filename);
396
    } else if (!drv) {
397
        drv = find_image_format(filename);
398
    }
399
    if (!drv) {
400
        ret = -ENOENT;
401
        goto unlink_and_fail;
402
    }
403
    bs->drv = drv;
404
    bs->opaque = qemu_mallocz(drv->instance_size);
405
    /* Note: for compatibility, we open disk image files as RDWR, and
406
       RDONLY as fallback */
407
    if (!(flags & BDRV_O_FILE))
408
        open_flags = BDRV_O_RDWR | (flags & BDRV_O_CACHE_MASK);
409
    else
410
        open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
411
    ret = drv->bdrv_open(bs, filename, open_flags);
412
    if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
413
        ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
414
        bs->read_only = 1;
415
    }
416
    if (ret < 0) {
417
        qemu_free(bs->opaque);
418
        bs->opaque = NULL;
419
        bs->drv = NULL;
420
    unlink_and_fail:
421
        if (bs->is_temporary)
422
            unlink(filename);
423
        return ret;
424
    }
425
    if (drv->bdrv_getlength) {
426
        bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
427
    }
428
#ifndef _WIN32
429
    if (bs->is_temporary) {
430
        unlink(filename);
431
    }
432
#endif
433
    if (bs->backing_file[0] != '\0') {
434
        /* if there is a backing file, use it */
435
        BlockDriver *back_drv = NULL;
436
        bs->backing_hd = bdrv_new("");
437
        path_combine(backing_filename, sizeof(backing_filename),
438
                     filename, bs->backing_file);
439
        if (bs->backing_format[0] != '\0')
440
            back_drv = bdrv_find_format(bs->backing_format);
441
        ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,
442
                         back_drv);
443
        if (ret < 0) {
444
            bdrv_close(bs);
445
            return ret;
446
        }
447
    }
448

    
449
    if (!bdrv_key_required(bs)) {
450
        /* call the change callback */
451
        bs->media_changed = 1;
452
        if (bs->change_cb)
453
            bs->change_cb(bs->change_opaque);
454
    }
455
    return 0;
456
}
457

    
458
void bdrv_close(BlockDriverState *bs)
459
{
460
    if (bs->drv) {
461
        if (bs->backing_hd)
462
            bdrv_delete(bs->backing_hd);
463
        bs->drv->bdrv_close(bs);
464
        qemu_free(bs->opaque);
465
#ifdef _WIN32
466
        if (bs->is_temporary) {
467
            unlink(bs->filename);
468
        }
469
#endif
470
        bs->opaque = NULL;
471
        bs->drv = NULL;
472

    
473
        /* call the change callback */
474
        bs->media_changed = 1;
475
        if (bs->change_cb)
476
            bs->change_cb(bs->change_opaque);
477
    }
478
}
479

    
480
void bdrv_delete(BlockDriverState *bs)
481
{
482
    BlockDriverState **pbs;
483

    
484
    pbs = &bdrv_first;
485
    while (*pbs != bs && *pbs != NULL)
486
        pbs = &(*pbs)->next;
487
    if (*pbs == bs)
488
        *pbs = bs->next;
489

    
490
    bdrv_close(bs);
491
    qemu_free(bs);
492
}
493

    
494
/*
495
 * Run consistency checks on an image
496
 *
497
 * Returns the number of errors or -errno when an internal error occurs
498
 */
499
int bdrv_check(BlockDriverState *bs)
500
{
501
    if (bs->drv->bdrv_check == NULL) {
502
        return -ENOTSUP;
503
    }
504

    
505
    return bs->drv->bdrv_check(bs);
506
}
507

    
508
/* commit COW file into the raw image */
509
int bdrv_commit(BlockDriverState *bs)
510
{
511
    BlockDriver *drv = bs->drv;
512
    int64_t i, total_sectors;
513
    int n, j;
514
    unsigned char sector[512];
515

    
516
    if (!drv)
517
        return -ENOMEDIUM;
518

    
519
    if (bs->read_only) {
520
        return -EACCES;
521
    }
522

    
523
    if (!bs->backing_hd) {
524
        return -ENOTSUP;
525
    }
526

    
527
    total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
528
    for (i = 0; i < total_sectors;) {
529
        if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
530
            for(j = 0; j < n; j++) {
531
                if (bdrv_read(bs, i, sector, 1) != 0) {
532
                    return -EIO;
533
                }
534

    
535
                if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
536
                    return -EIO;
537
                }
538
                i++;
539
            }
540
        } else {
541
            i += n;
542
        }
543
    }
544

    
545
    if (drv->bdrv_make_empty)
546
        return drv->bdrv_make_empty(bs);
547

    
548
    return 0;
549
}
550

    
551
static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
552
                                   size_t size)
553
{
554
    int64_t len;
555

    
556
    if (!bdrv_is_inserted(bs))
557
        return -ENOMEDIUM;
558

    
559
    if (bs->growable)
560
        return 0;
561

    
562
    len = bdrv_getlength(bs);
563

    
564
    if (offset < 0)
565
        return -EIO;
566

    
567
    if ((offset > len) || (len - offset < size))
568
        return -EIO;
569

    
570
    return 0;
571
}
572

    
573
static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
574
                              int nb_sectors)
575
{
576
    return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
577
}
578

    
579
/* return < 0 if error. See bdrv_write() for the return codes */
580
int bdrv_read(BlockDriverState *bs, int64_t sector_num,
581
              uint8_t *buf, int nb_sectors)
582
{
583
    BlockDriver *drv = bs->drv;
584

    
585
    if (!drv)
586
        return -ENOMEDIUM;
587
    if (bdrv_check_request(bs, sector_num, nb_sectors))
588
        return -EIO;
589

    
590
    return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
591
}
592

    
593
/* Return < 0 if error. Important errors are:
594
  -EIO         generic I/O error (may happen for all errors)
595
  -ENOMEDIUM   No media inserted.
596
  -EINVAL      Invalid sector number or nb_sectors
597
  -EACCES      Trying to write a read-only device
598
*/
599
int bdrv_write(BlockDriverState *bs, int64_t sector_num,
600
               const uint8_t *buf, int nb_sectors)
601
{
602
    BlockDriver *drv = bs->drv;
603
    if (!bs->drv)
604
        return -ENOMEDIUM;
605
    if (bs->read_only)
606
        return -EACCES;
607
    if (bdrv_check_request(bs, sector_num, nb_sectors))
608
        return -EIO;
609

    
610
    return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
611
}
612

    
613
int bdrv_pread(BlockDriverState *bs, int64_t offset,
614
               void *buf, int count1)
615
{
616
    uint8_t tmp_buf[SECTOR_SIZE];
617
    int len, nb_sectors, count;
618
    int64_t sector_num;
619

    
620
    count = count1;
621
    /* first read to align to sector start */
622
    len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
623
    if (len > count)
624
        len = count;
625
    sector_num = offset >> SECTOR_BITS;
626
    if (len > 0) {
627
        if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
628
            return -EIO;
629
        memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
630
        count -= len;
631
        if (count == 0)
632
            return count1;
633
        sector_num++;
634
        buf += len;
635
    }
636

    
637
    /* read the sectors "in place" */
638
    nb_sectors = count >> SECTOR_BITS;
639
    if (nb_sectors > 0) {
640
        if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
641
            return -EIO;
642
        sector_num += nb_sectors;
643
        len = nb_sectors << SECTOR_BITS;
644
        buf += len;
645
        count -= len;
646
    }
647

    
648
    /* add data from the last sector */
649
    if (count > 0) {
650
        if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
651
            return -EIO;
652
        memcpy(buf, tmp_buf, count);
653
    }
654
    return count1;
655
}
656

    
657
int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
658
                const void *buf, int count1)
659
{
660
    uint8_t tmp_buf[SECTOR_SIZE];
661
    int len, nb_sectors, count;
662
    int64_t sector_num;
663

    
664
    count = count1;
665
    /* first write to align to sector start */
666
    len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
667
    if (len > count)
668
        len = count;
669
    sector_num = offset >> SECTOR_BITS;
670
    if (len > 0) {
671
        if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
672
            return -EIO;
673
        memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
674
        if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
675
            return -EIO;
676
        count -= len;
677
        if (count == 0)
678
            return count1;
679
        sector_num++;
680
        buf += len;
681
    }
682

    
683
    /* write the sectors "in place" */
684
    nb_sectors = count >> SECTOR_BITS;
685
    if (nb_sectors > 0) {
686
        if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
687
            return -EIO;
688
        sector_num += nb_sectors;
689
        len = nb_sectors << SECTOR_BITS;
690
        buf += len;
691
        count -= len;
692
    }
693

    
694
    /* add data from the last sector */
695
    if (count > 0) {
696
        if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
697
            return -EIO;
698
        memcpy(tmp_buf, buf, count);
699
        if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
700
            return -EIO;
701
    }
702
    return count1;
703
}
704

    
705
/**
706
 * Truncate file to 'offset' bytes (needed only for file protocols)
707
 */
708
int bdrv_truncate(BlockDriverState *bs, int64_t offset)
709
{
710
    BlockDriver *drv = bs->drv;
711
    if (!drv)
712
        return -ENOMEDIUM;
713
    if (!drv->bdrv_truncate)
714
        return -ENOTSUP;
715
    return drv->bdrv_truncate(bs, offset);
716
}
717

    
718
/**
719
 * Length of a file in bytes. Return < 0 if error or unknown.
720
 */
721
int64_t bdrv_getlength(BlockDriverState *bs)
722
{
723
    BlockDriver *drv = bs->drv;
724
    if (!drv)
725
        return -ENOMEDIUM;
726
    if (!drv->bdrv_getlength) {
727
        /* legacy mode */
728
        return bs->total_sectors * SECTOR_SIZE;
729
    }
730
    return drv->bdrv_getlength(bs);
731
}
732

    
733
/* return 0 as number of sectors if no device present or error */
734
void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
735
{
736
    int64_t length;
737
    length = bdrv_getlength(bs);
738
    if (length < 0)
739
        length = 0;
740
    else
741
        length = length >> SECTOR_BITS;
742
    *nb_sectors_ptr = length;
743
}
744

    
745
struct partition {
746
        uint8_t boot_ind;           /* 0x80 - active */
747
        uint8_t head;               /* starting head */
748
        uint8_t sector;             /* starting sector */
749
        uint8_t cyl;                /* starting cylinder */
750
        uint8_t sys_ind;            /* What partition type */
751
        uint8_t end_head;           /* end head */
752
        uint8_t end_sector;         /* end sector */
753
        uint8_t end_cyl;            /* end cylinder */
754
        uint32_t start_sect;        /* starting sector counting from 0 */
755
        uint32_t nr_sects;          /* nr of sectors in partition */
756
} __attribute__((packed));
757

    
758
/* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
759
static int guess_disk_lchs(BlockDriverState *bs,
760
                           int *pcylinders, int *pheads, int *psectors)
761
{
762
    uint8_t buf[512];
763
    int ret, i, heads, sectors, cylinders;
764
    struct partition *p;
765
    uint32_t nr_sects;
766
    uint64_t nb_sectors;
767

    
768
    bdrv_get_geometry(bs, &nb_sectors);
769

    
770
    ret = bdrv_read(bs, 0, buf, 1);
771
    if (ret < 0)
772
        return -1;
773
    /* test msdos magic */
774
    if (buf[510] != 0x55 || buf[511] != 0xaa)
775
        return -1;
776
    for(i = 0; i < 4; i++) {
777
        p = ((struct partition *)(buf + 0x1be)) + i;
778
        nr_sects = le32_to_cpu(p->nr_sects);
779
        if (nr_sects && p->end_head) {
780
            /* We make the assumption that the partition terminates on
781
               a cylinder boundary */
782
            heads = p->end_head + 1;
783
            sectors = p->end_sector & 63;
784
            if (sectors == 0)
785
                continue;
786
            cylinders = nb_sectors / (heads * sectors);
787
            if (cylinders < 1 || cylinders > 16383)
788
                continue;
789
            *pheads = heads;
790
            *psectors = sectors;
791
            *pcylinders = cylinders;
792
#if 0
793
            printf("guessed geometry: LCHS=%d %d %d\n",
794
                   cylinders, heads, sectors);
795
#endif
796
            return 0;
797
        }
798
    }
799
    return -1;
800
}
801

    
802
void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
803
{
804
    int translation, lba_detected = 0;
805
    int cylinders, heads, secs;
806
    uint64_t nb_sectors;
807

    
808
    /* if a geometry hint is available, use it */
809
    bdrv_get_geometry(bs, &nb_sectors);
810
    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
811
    translation = bdrv_get_translation_hint(bs);
812
    if (cylinders != 0) {
813
        *pcyls = cylinders;
814
        *pheads = heads;
815
        *psecs = secs;
816
    } else {
817
        if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
818
            if (heads > 16) {
819
                /* if heads > 16, it means that a BIOS LBA
820
                   translation was active, so the default
821
                   hardware geometry is OK */
822
                lba_detected = 1;
823
                goto default_geometry;
824
            } else {
825
                *pcyls = cylinders;
826
                *pheads = heads;
827
                *psecs = secs;
828
                /* disable any translation to be in sync with
829
                   the logical geometry */
830
                if (translation == BIOS_ATA_TRANSLATION_AUTO) {
831
                    bdrv_set_translation_hint(bs,
832
                                              BIOS_ATA_TRANSLATION_NONE);
833
                }
834
            }
835
        } else {
836
        default_geometry:
837
            /* if no geometry, use a standard physical disk geometry */
838
            cylinders = nb_sectors / (16 * 63);
839

    
840
            if (cylinders > 16383)
841
                cylinders = 16383;
842
            else if (cylinders < 2)
843
                cylinders = 2;
844
            *pcyls = cylinders;
845
            *pheads = 16;
846
            *psecs = 63;
847
            if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
848
                if ((*pcyls * *pheads) <= 131072) {
849
                    bdrv_set_translation_hint(bs,
850
                                              BIOS_ATA_TRANSLATION_LARGE);
851
                } else {
852
                    bdrv_set_translation_hint(bs,
853
                                              BIOS_ATA_TRANSLATION_LBA);
854
                }
855
            }
856
        }
857
        bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
858
    }
859
}
860

    
861
void bdrv_set_geometry_hint(BlockDriverState *bs,
862
                            int cyls, int heads, int secs)
863
{
864
    bs->cyls = cyls;
865
    bs->heads = heads;
866
    bs->secs = secs;
867
}
868

    
869
void bdrv_set_type_hint(BlockDriverState *bs, int type)
870
{
871
    bs->type = type;
872
    bs->removable = ((type == BDRV_TYPE_CDROM ||
873
                      type == BDRV_TYPE_FLOPPY));
874
}
875

    
876
void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
877
{
878
    bs->translation = translation;
879
}
880

    
881
void bdrv_get_geometry_hint(BlockDriverState *bs,
882
                            int *pcyls, int *pheads, int *psecs)
883
{
884
    *pcyls = bs->cyls;
885
    *pheads = bs->heads;
886
    *psecs = bs->secs;
887
}
888

    
889
int bdrv_get_type_hint(BlockDriverState *bs)
890
{
891
    return bs->type;
892
}
893

    
894
int bdrv_get_translation_hint(BlockDriverState *bs)
895
{
896
    return bs->translation;
897
}
898

    
899
int bdrv_is_removable(BlockDriverState *bs)
900
{
901
    return bs->removable;
902
}
903

    
904
int bdrv_is_read_only(BlockDriverState *bs)
905
{
906
    return bs->read_only;
907
}
908

    
909
int bdrv_is_sg(BlockDriverState *bs)
910
{
911
    return bs->sg;
912
}
913

    
914
/* XXX: no longer used */
915
void bdrv_set_change_cb(BlockDriverState *bs,
916
                        void (*change_cb)(void *opaque), void *opaque)
917
{
918
    bs->change_cb = change_cb;
919
    bs->change_opaque = opaque;
920
}
921

    
922
int bdrv_is_encrypted(BlockDriverState *bs)
923
{
924
    if (bs->backing_hd && bs->backing_hd->encrypted)
925
        return 1;
926
    return bs->encrypted;
927
}
928

    
929
int bdrv_key_required(BlockDriverState *bs)
930
{
931
    BlockDriverState *backing_hd = bs->backing_hd;
932

    
933
    if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
934
        return 1;
935
    return (bs->encrypted && !bs->valid_key);
936
}
937

    
938
int bdrv_set_key(BlockDriverState *bs, const char *key)
939
{
940
    int ret;
941
    if (bs->backing_hd && bs->backing_hd->encrypted) {
942
        ret = bdrv_set_key(bs->backing_hd, key);
943
        if (ret < 0)
944
            return ret;
945
        if (!bs->encrypted)
946
            return 0;
947
    }
948
    if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
949
        return -1;
950
    ret = bs->drv->bdrv_set_key(bs, key);
951
    if (ret < 0) {
952
        bs->valid_key = 0;
953
    } else if (!bs->valid_key) {
954
        bs->valid_key = 1;
955
        /* call the change callback now, we skipped it on open */
956
        bs->media_changed = 1;
957
        if (bs->change_cb)
958
            bs->change_cb(bs->change_opaque);
959
    }
960
    return ret;
961
}
962

    
963
void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
964
{
965
    if (!bs->drv) {
966
        buf[0] = '\0';
967
    } else {
968
        pstrcpy(buf, buf_size, bs->drv->format_name);
969
    }
970
}
971

    
972
void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
973
                         void *opaque)
974
{
975
    BlockDriver *drv;
976

    
977
    for (drv = first_drv; drv != NULL; drv = drv->next) {
978
        it(opaque, drv->format_name);
979
    }
980
}
981

    
982
BlockDriverState *bdrv_find(const char *name)
983
{
984
    BlockDriverState *bs;
985

    
986
    for (bs = bdrv_first; bs != NULL; bs = bs->next) {
987
        if (!strcmp(name, bs->device_name))
988
            return bs;
989
    }
990
    return NULL;
991
}
992

    
993
void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
994
{
995
    BlockDriverState *bs;
996

    
997
    for (bs = bdrv_first; bs != NULL; bs = bs->next) {
998
        it(opaque, bs);
999
    }
1000
}
1001

    
1002
const char *bdrv_get_device_name(BlockDriverState *bs)
1003
{
1004
    return bs->device_name;
1005
}
1006

    
1007
void bdrv_flush(BlockDriverState *bs)
1008
{
1009
    if (!bs->drv)
1010
        return;
1011
    if (bs->drv->bdrv_flush)
1012
        bs->drv->bdrv_flush(bs);
1013
    if (bs->backing_hd)
1014
        bdrv_flush(bs->backing_hd);
1015
}
1016

    
1017
void bdrv_flush_all(void)
1018
{
1019
    BlockDriverState *bs;
1020

    
1021
    for (bs = bdrv_first; bs != NULL; bs = bs->next)
1022
        if (bs->drv && !bdrv_is_read_only(bs) && 
1023
            (!bdrv_is_removable(bs) || bdrv_is_inserted(bs)))
1024
            bdrv_flush(bs);
1025
}
1026

    
1027
/*
1028
 * Returns true iff the specified sector is present in the disk image. Drivers
1029
 * not implementing the functionality are assumed to not support backing files,
1030
 * hence all their sectors are reported as allocated.
1031
 *
1032
 * 'pnum' is set to the number of sectors (including and immediately following
1033
 * the specified sector) that are known to be in the same
1034
 * allocated/unallocated state.
1035
 *
1036
 * 'nb_sectors' is the max value 'pnum' should be set to.
1037
 */
1038
int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1039
        int *pnum)
1040
{
1041
    int64_t n;
1042
    if (!bs->drv->bdrv_is_allocated) {
1043
        if (sector_num >= bs->total_sectors) {
1044
            *pnum = 0;
1045
            return 0;
1046
        }
1047
        n = bs->total_sectors - sector_num;
1048
        *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1049
        return 1;
1050
    }
1051
    return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1052
}
1053

    
1054
void bdrv_info(Monitor *mon)
1055
{
1056
    BlockDriverState *bs;
1057

    
1058
    for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1059
        monitor_printf(mon, "%s:", bs->device_name);
1060
        monitor_printf(mon, " type=");
1061
        switch(bs->type) {
1062
        case BDRV_TYPE_HD:
1063
            monitor_printf(mon, "hd");
1064
            break;
1065
        case BDRV_TYPE_CDROM:
1066
            monitor_printf(mon, "cdrom");
1067
            break;
1068
        case BDRV_TYPE_FLOPPY:
1069
            monitor_printf(mon, "floppy");
1070
            break;
1071
        }
1072
        monitor_printf(mon, " removable=%d", bs->removable);
1073
        if (bs->removable) {
1074
            monitor_printf(mon, " locked=%d", bs->locked);
1075
        }
1076
        if (bs->drv) {
1077
            monitor_printf(mon, " file=");
1078
            monitor_print_filename(mon, bs->filename);
1079
            if (bs->backing_file[0] != '\0') {
1080
                monitor_printf(mon, " backing_file=");
1081
                monitor_print_filename(mon, bs->backing_file);
1082
            }
1083
            monitor_printf(mon, " ro=%d", bs->read_only);
1084
            monitor_printf(mon, " drv=%s", bs->drv->format_name);
1085
            monitor_printf(mon, " encrypted=%d", bdrv_is_encrypted(bs));
1086
        } else {
1087
            monitor_printf(mon, " [not inserted]");
1088
        }
1089
        monitor_printf(mon, "\n");
1090
    }
1091
}
1092

    
1093
/* The "info blockstats" command. */
1094
void bdrv_info_stats(Monitor *mon)
1095
{
1096
    BlockDriverState *bs;
1097

    
1098
    for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1099
        monitor_printf(mon, "%s:"
1100
                       " rd_bytes=%" PRIu64
1101
                       " wr_bytes=%" PRIu64
1102
                       " rd_operations=%" PRIu64
1103
                       " wr_operations=%" PRIu64
1104
                       "\n",
1105
                       bs->device_name,
1106
                       bs->rd_bytes, bs->wr_bytes,
1107
                       bs->rd_ops, bs->wr_ops);
1108
    }
1109
}
1110

    
1111
const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1112
{
1113
    if (bs->backing_hd && bs->backing_hd->encrypted)
1114
        return bs->backing_file;
1115
    else if (bs->encrypted)
1116
        return bs->filename;
1117
    else
1118
        return NULL;
1119
}
1120

    
1121
void bdrv_get_backing_filename(BlockDriverState *bs,
1122
                               char *filename, int filename_size)
1123
{
1124
    if (!bs->backing_hd) {
1125
        pstrcpy(filename, filename_size, "");
1126
    } else {
1127
        pstrcpy(filename, filename_size, bs->backing_file);
1128
    }
1129
}
1130

    
1131
int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1132
                          const uint8_t *buf, int nb_sectors)
1133
{
1134
    BlockDriver *drv = bs->drv;
1135
    if (!drv)
1136
        return -ENOMEDIUM;
1137
    if (!drv->bdrv_write_compressed)
1138
        return -ENOTSUP;
1139
    if (bdrv_check_request(bs, sector_num, nb_sectors))
1140
        return -EIO;
1141
    return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1142
}
1143

    
1144
int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1145
{
1146
    BlockDriver *drv = bs->drv;
1147
    if (!drv)
1148
        return -ENOMEDIUM;
1149
    if (!drv->bdrv_get_info)
1150
        return -ENOTSUP;
1151
    memset(bdi, 0, sizeof(*bdi));
1152
    return drv->bdrv_get_info(bs, bdi);
1153
}
1154

    
1155
int bdrv_put_buffer(BlockDriverState *bs, const uint8_t *buf, int64_t pos, int size)
1156
{
1157
    BlockDriver *drv = bs->drv;
1158
    if (!drv)
1159
        return -ENOMEDIUM;
1160
    if (!drv->bdrv_put_buffer)
1161
        return -ENOTSUP;
1162
    return drv->bdrv_put_buffer(bs, buf, pos, size);
1163
}
1164

    
1165
int bdrv_get_buffer(BlockDriverState *bs, uint8_t *buf, int64_t pos, int size)
1166
{
1167
    BlockDriver *drv = bs->drv;
1168
    if (!drv)
1169
        return -ENOMEDIUM;
1170
    if (!drv->bdrv_get_buffer)
1171
        return -ENOTSUP;
1172
    return drv->bdrv_get_buffer(bs, buf, pos, size);
1173
}
1174

    
1175
/**************************************************************/
1176
/* handling of snapshots */
1177

    
1178
int bdrv_snapshot_create(BlockDriverState *bs,
1179
                         QEMUSnapshotInfo *sn_info)
1180
{
1181
    BlockDriver *drv = bs->drv;
1182
    if (!drv)
1183
        return -ENOMEDIUM;
1184
    if (!drv->bdrv_snapshot_create)
1185
        return -ENOTSUP;
1186
    return drv->bdrv_snapshot_create(bs, sn_info);
1187
}
1188

    
1189
int bdrv_snapshot_goto(BlockDriverState *bs,
1190
                       const char *snapshot_id)
1191
{
1192
    BlockDriver *drv = bs->drv;
1193
    if (!drv)
1194
        return -ENOMEDIUM;
1195
    if (!drv->bdrv_snapshot_goto)
1196
        return -ENOTSUP;
1197
    return drv->bdrv_snapshot_goto(bs, snapshot_id);
1198
}
1199

    
1200
int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1201
{
1202
    BlockDriver *drv = bs->drv;
1203
    if (!drv)
1204
        return -ENOMEDIUM;
1205
    if (!drv->bdrv_snapshot_delete)
1206
        return -ENOTSUP;
1207
    return drv->bdrv_snapshot_delete(bs, snapshot_id);
1208
}
1209

    
1210
int bdrv_snapshot_list(BlockDriverState *bs,
1211
                       QEMUSnapshotInfo **psn_info)
1212
{
1213
    BlockDriver *drv = bs->drv;
1214
    if (!drv)
1215
        return -ENOMEDIUM;
1216
    if (!drv->bdrv_snapshot_list)
1217
        return -ENOTSUP;
1218
    return drv->bdrv_snapshot_list(bs, psn_info);
1219
}
1220

    
1221
#define NB_SUFFIXES 4
1222

    
1223
char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1224
{
1225
    static const char suffixes[NB_SUFFIXES] = "KMGT";
1226
    int64_t base;
1227
    int i;
1228

    
1229
    if (size <= 999) {
1230
        snprintf(buf, buf_size, "%" PRId64, size);
1231
    } else {
1232
        base = 1024;
1233
        for(i = 0; i < NB_SUFFIXES; i++) {
1234
            if (size < (10 * base)) {
1235
                snprintf(buf, buf_size, "%0.1f%c",
1236
                         (double)size / base,
1237
                         suffixes[i]);
1238
                break;
1239
            } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1240
                snprintf(buf, buf_size, "%" PRId64 "%c",
1241
                         ((size + (base >> 1)) / base),
1242
                         suffixes[i]);
1243
                break;
1244
            }
1245
            base = base * 1024;
1246
        }
1247
    }
1248
    return buf;
1249
}
1250

    
1251
char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1252
{
1253
    char buf1[128], date_buf[128], clock_buf[128];
1254
#ifdef _WIN32
1255
    struct tm *ptm;
1256
#else
1257
    struct tm tm;
1258
#endif
1259
    time_t ti;
1260
    int64_t secs;
1261

    
1262
    if (!sn) {
1263
        snprintf(buf, buf_size,
1264
                 "%-10s%-20s%7s%20s%15s",
1265
                 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1266
    } else {
1267
        ti = sn->date_sec;
1268
#ifdef _WIN32
1269
        ptm = localtime(&ti);
1270
        strftime(date_buf, sizeof(date_buf),
1271
                 "%Y-%m-%d %H:%M:%S", ptm);
1272
#else
1273
        localtime_r(&ti, &tm);
1274
        strftime(date_buf, sizeof(date_buf),
1275
                 "%Y-%m-%d %H:%M:%S", &tm);
1276
#endif
1277
        secs = sn->vm_clock_nsec / 1000000000;
1278
        snprintf(clock_buf, sizeof(clock_buf),
1279
                 "%02d:%02d:%02d.%03d",
1280
                 (int)(secs / 3600),
1281
                 (int)((secs / 60) % 60),
1282
                 (int)(secs % 60),
1283
                 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1284
        snprintf(buf, buf_size,
1285
                 "%-10s%-20s%7s%20s%15s",
1286
                 sn->id_str, sn->name,
1287
                 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1288
                 date_buf,
1289
                 clock_buf);
1290
    }
1291
    return buf;
1292
}
1293

    
1294

    
1295
/**************************************************************/
1296
/* async I/Os */
1297

    
1298
BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1299
                                 QEMUIOVector *qiov, int nb_sectors,
1300
                                 BlockDriverCompletionFunc *cb, void *opaque)
1301
{
1302
    BlockDriver *drv = bs->drv;
1303
    BlockDriverAIOCB *ret;
1304

    
1305
    if (!drv)
1306
        return NULL;
1307
    if (bdrv_check_request(bs, sector_num, nb_sectors))
1308
        return NULL;
1309

    
1310
    ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1311
                              cb, opaque);
1312

    
1313
    if (ret) {
1314
        /* Update stats even though technically transfer has not happened. */
1315
        bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1316
        bs->rd_ops ++;
1317
    }
1318

    
1319
    return ret;
1320
}
1321

    
1322
BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1323
                                  QEMUIOVector *qiov, int nb_sectors,
1324
                                  BlockDriverCompletionFunc *cb, void *opaque)
1325
{
1326
    BlockDriver *drv = bs->drv;
1327
    BlockDriverAIOCB *ret;
1328

    
1329
    if (!drv)
1330
        return NULL;
1331
    if (bs->read_only)
1332
        return NULL;
1333
    if (bdrv_check_request(bs, sector_num, nb_sectors))
1334
        return NULL;
1335

    
1336
    ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1337
                               cb, opaque);
1338

    
1339
    if (ret) {
1340
        /* Update stats even though technically transfer has not happened. */
1341
        bs->wr_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1342
        bs->wr_ops ++;
1343
    }
1344

    
1345
    return ret;
1346
}
1347

    
1348
void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1349
{
1350
    acb->pool->cancel(acb);
1351
}
1352

    
1353

    
1354
/**************************************************************/
1355
/* async block device emulation */
1356

    
1357
typedef struct BlockDriverAIOCBSync {
1358
    BlockDriverAIOCB common;
1359
    QEMUBH *bh;
1360
    int ret;
1361
    /* vector translation state */
1362
    QEMUIOVector *qiov;
1363
    uint8_t *bounce;
1364
    int is_write;
1365
} BlockDriverAIOCBSync;
1366

    
1367
static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1368
{
1369
    BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1370
    qemu_bh_cancel(acb->bh);
1371
    qemu_aio_release(acb);
1372
}
1373

    
1374
static AIOPool bdrv_em_aio_pool = {
1375
    .aiocb_size         = sizeof(BlockDriverAIOCBSync),
1376
    .cancel             = bdrv_aio_cancel_em,
1377
};
1378

    
1379
static void bdrv_aio_bh_cb(void *opaque)
1380
{
1381
    BlockDriverAIOCBSync *acb = opaque;
1382

    
1383
    if (!acb->is_write)
1384
        qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1385
    qemu_vfree(acb->bounce);
1386
    acb->common.cb(acb->common.opaque, acb->ret);
1387

    
1388
    qemu_aio_release(acb);
1389
}
1390

    
1391
static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1392
                                            int64_t sector_num,
1393
                                            QEMUIOVector *qiov,
1394
                                            int nb_sectors,
1395
                                            BlockDriverCompletionFunc *cb,
1396
                                            void *opaque,
1397
                                            int is_write)
1398

    
1399
{
1400
    BlockDriverAIOCBSync *acb;
1401

    
1402
    acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1403
    acb->is_write = is_write;
1404
    acb->qiov = qiov;
1405
    acb->bounce = qemu_blockalign(bs, qiov->size);
1406

    
1407
    if (!acb->bh)
1408
        acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1409

    
1410
    if (is_write) {
1411
        qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1412
        acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1413
    } else {
1414
        acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1415
    }
1416

    
1417
    qemu_bh_schedule(acb->bh);
1418

    
1419
    return &acb->common;
1420
}
1421

    
1422
static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1423
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1424
        BlockDriverCompletionFunc *cb, void *opaque)
1425
{
1426
    return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1427
}
1428

    
1429
static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1430
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1431
        BlockDriverCompletionFunc *cb, void *opaque)
1432
{
1433
    return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1434
}
1435

    
1436
/**************************************************************/
1437
/* sync block device emulation */
1438

    
1439
static void bdrv_rw_em_cb(void *opaque, int ret)
1440
{
1441
    *(int *)opaque = ret;
1442
}
1443

    
1444
#define NOT_DONE 0x7fffffff
1445

    
1446
static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
1447
                        uint8_t *buf, int nb_sectors)
1448
{
1449
    int async_ret;
1450
    BlockDriverAIOCB *acb;
1451
    struct iovec iov;
1452
    QEMUIOVector qiov;
1453

    
1454
    async_ret = NOT_DONE;
1455
    iov.iov_base = (void *)buf;
1456
    iov.iov_len = nb_sectors * 512;
1457
    qemu_iovec_init_external(&qiov, &iov, 1);
1458
    acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1459
        bdrv_rw_em_cb, &async_ret);
1460
    if (acb == NULL)
1461
        return -1;
1462

    
1463
    while (async_ret == NOT_DONE) {
1464
        qemu_aio_wait();
1465
    }
1466

    
1467
    return async_ret;
1468
}
1469

    
1470
static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1471
                         const uint8_t *buf, int nb_sectors)
1472
{
1473
    int async_ret;
1474
    BlockDriverAIOCB *acb;
1475
    struct iovec iov;
1476
    QEMUIOVector qiov;
1477

    
1478
    async_ret = NOT_DONE;
1479
    iov.iov_base = (void *)buf;
1480
    iov.iov_len = nb_sectors * 512;
1481
    qemu_iovec_init_external(&qiov, &iov, 1);
1482
    acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1483
        bdrv_rw_em_cb, &async_ret);
1484
    if (acb == NULL)
1485
        return -1;
1486
    while (async_ret == NOT_DONE) {
1487
        qemu_aio_wait();
1488
    }
1489
    return async_ret;
1490
}
1491

    
1492
void bdrv_init(void)
1493
{
1494
    module_call_init(MODULE_INIT_BLOCK);
1495
}
1496

    
1497
void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1498
                   BlockDriverCompletionFunc *cb, void *opaque)
1499
{
1500
    BlockDriverAIOCB *acb;
1501

    
1502
    if (pool->free_aiocb) {
1503
        acb = pool->free_aiocb;
1504
        pool->free_aiocb = acb->next;
1505
    } else {
1506
        acb = qemu_mallocz(pool->aiocb_size);
1507
        acb->pool = pool;
1508
    }
1509
    acb->bs = bs;
1510
    acb->cb = cb;
1511
    acb->opaque = opaque;
1512
    return acb;
1513
}
1514

    
1515
void qemu_aio_release(void *p)
1516
{
1517
    BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1518
    AIOPool *pool = acb->pool;
1519
    acb->next = pool->free_aiocb;
1520
    pool->free_aiocb = acb;
1521
}
1522

    
1523
/**************************************************************/
1524
/* removable device support */
1525

    
1526
/**
1527
 * Return TRUE if the media is present
1528
 */
1529
int bdrv_is_inserted(BlockDriverState *bs)
1530
{
1531
    BlockDriver *drv = bs->drv;
1532
    int ret;
1533
    if (!drv)
1534
        return 0;
1535
    if (!drv->bdrv_is_inserted)
1536
        return 1;
1537
    ret = drv->bdrv_is_inserted(bs);
1538
    return ret;
1539
}
1540

    
1541
/**
1542
 * Return TRUE if the media changed since the last call to this
1543
 * function. It is currently only used for floppy disks
1544
 */
1545
int bdrv_media_changed(BlockDriverState *bs)
1546
{
1547
    BlockDriver *drv = bs->drv;
1548
    int ret;
1549

    
1550
    if (!drv || !drv->bdrv_media_changed)
1551
        ret = -ENOTSUP;
1552
    else
1553
        ret = drv->bdrv_media_changed(bs);
1554
    if (ret == -ENOTSUP)
1555
        ret = bs->media_changed;
1556
    bs->media_changed = 0;
1557
    return ret;
1558
}
1559

    
1560
/**
1561
 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1562
 */
1563
void bdrv_eject(BlockDriverState *bs, int eject_flag)
1564
{
1565
    BlockDriver *drv = bs->drv;
1566
    int ret;
1567

    
1568
    if (!drv || !drv->bdrv_eject) {
1569
        ret = -ENOTSUP;
1570
    } else {
1571
        ret = drv->bdrv_eject(bs, eject_flag);
1572
    }
1573
    if (ret == -ENOTSUP) {
1574
        if (eject_flag)
1575
            bdrv_close(bs);
1576
    }
1577
}
1578

    
1579
int bdrv_is_locked(BlockDriverState *bs)
1580
{
1581
    return bs->locked;
1582
}
1583

    
1584
/**
1585
 * Lock or unlock the media (if it is locked, the user won't be able
1586
 * to eject it manually).
1587
 */
1588
void bdrv_set_locked(BlockDriverState *bs, int locked)
1589
{
1590
    BlockDriver *drv = bs->drv;
1591

    
1592
    bs->locked = locked;
1593
    if (drv && drv->bdrv_set_locked) {
1594
        drv->bdrv_set_locked(bs, locked);
1595
    }
1596
}
1597

    
1598
/* needed for generic scsi interface */
1599

    
1600
int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1601
{
1602
    BlockDriver *drv = bs->drv;
1603

    
1604
    if (drv && drv->bdrv_ioctl)
1605
        return drv->bdrv_ioctl(bs, req, buf);
1606
    return -ENOTSUP;
1607
}
1608

    
1609
BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1610
        unsigned long int req, void *buf,
1611
        BlockDriverCompletionFunc *cb, void *opaque)
1612
{
1613
    BlockDriver *drv = bs->drv;
1614

    
1615
    if (drv && drv->bdrv_aio_ioctl)
1616
        return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1617
    return NULL;
1618
}
1619

    
1620
void *qemu_blockalign(BlockDriverState *bs, size_t size)
1621
{
1622
    return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
1623
}