qemu/block/raw-posix.c
<<
>>
Prefs
   1/*
   2 * Block driver for RAW files (posix)
   3 *
   4 * Copyright (c) 2006 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 "qemu-common.h"
  25#include "qemu/error-report.h"
  26#include "qemu/timer.h"
  27#include "qemu/log.h"
  28#include "block/block_int.h"
  29#include "qemu/module.h"
  30#include "trace.h"
  31#include "block/thread-pool.h"
  32#include "qemu/iov.h"
  33#include "raw-aio.h"
  34#include "qapi/util.h"
  35#include "qapi/qmp/qstring.h"
  36
  37#if defined(__APPLE__) && (__MACH__)
  38#include <paths.h>
  39#include <sys/param.h>
  40#include <IOKit/IOKitLib.h>
  41#include <IOKit/IOBSD.h>
  42#include <IOKit/storage/IOMediaBSDClient.h>
  43#include <IOKit/storage/IOMedia.h>
  44#include <IOKit/storage/IOCDMedia.h>
  45//#include <IOKit/storage/IOCDTypes.h>
  46#include <CoreFoundation/CoreFoundation.h>
  47#endif
  48
  49#ifdef __sun__
  50#define _POSIX_PTHREAD_SEMANTICS 1
  51#include <sys/dkio.h>
  52#endif
  53#ifdef __linux__
  54#include <sys/types.h>
  55#include <sys/stat.h>
  56#include <sys/ioctl.h>
  57#include <sys/param.h>
  58#include <linux/cdrom.h>
  59#include <linux/fd.h>
  60#include <linux/fs.h>
  61#include <linux/hdreg.h>
  62#include <scsi/sg.h>
  63#ifdef __s390__
  64#include <asm/dasd.h>
  65#endif
  66#ifndef FS_NOCOW_FL
  67#define FS_NOCOW_FL                     0x00800000 /* Do not cow file */
  68#endif
  69#endif
  70#if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
  71#include <linux/falloc.h>
  72#endif
  73#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
  74#include <sys/disk.h>
  75#include <sys/cdio.h>
  76#endif
  77
  78#ifdef __OpenBSD__
  79#include <sys/ioctl.h>
  80#include <sys/disklabel.h>
  81#include <sys/dkio.h>
  82#endif
  83
  84#ifdef __NetBSD__
  85#include <sys/ioctl.h>
  86#include <sys/disklabel.h>
  87#include <sys/dkio.h>
  88#include <sys/disk.h>
  89#endif
  90
  91#ifdef __DragonFly__
  92#include <sys/ioctl.h>
  93#include <sys/diskslice.h>
  94#endif
  95
  96#ifdef CONFIG_XFS
  97#include <xfs/xfs.h>
  98#endif
  99
 100//#define DEBUG_BLOCK
 101
 102#ifdef DEBUG_BLOCK
 103# define DEBUG_BLOCK_PRINT 1
 104#else
 105# define DEBUG_BLOCK_PRINT 0
 106#endif
 107#define DPRINTF(fmt, ...) \
 108do { \
 109    if (DEBUG_BLOCK_PRINT) { \
 110        printf(fmt, ## __VA_ARGS__); \
 111    } \
 112} while (0)
 113
 114/* OS X does not have O_DSYNC */
 115#ifndef O_DSYNC
 116#ifdef O_SYNC
 117#define O_DSYNC O_SYNC
 118#elif defined(O_FSYNC)
 119#define O_DSYNC O_FSYNC
 120#endif
 121#endif
 122
 123/* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
 124#ifndef O_DIRECT
 125#define O_DIRECT O_DSYNC
 126#endif
 127
 128#define FTYPE_FILE   0
 129#define FTYPE_CD     1
 130
 131#define MAX_BLOCKSIZE   4096
 132
 133typedef struct BDRVRawState {
 134    int fd;
 135    int type;
 136    int open_flags;
 137    size_t buf_align;
 138
 139#ifdef CONFIG_LINUX_AIO
 140    int use_aio;
 141    void *aio_ctx;
 142#endif
 143#ifdef CONFIG_XFS
 144    bool is_xfs:1;
 145#endif
 146    bool has_discard:1;
 147    bool has_write_zeroes:1;
 148    bool discard_zeroes:1;
 149    bool has_fallocate;
 150    bool needs_alignment;
 151} BDRVRawState;
 152
 153typedef struct BDRVRawReopenState {
 154    int fd;
 155    int open_flags;
 156#ifdef CONFIG_LINUX_AIO
 157    int use_aio;
 158#endif
 159} BDRVRawReopenState;
 160
 161static int fd_open(BlockDriverState *bs);
 162static int64_t raw_getlength(BlockDriverState *bs);
 163
 164typedef struct RawPosixAIOData {
 165    BlockDriverState *bs;
 166    int aio_fildes;
 167    union {
 168        struct iovec *aio_iov;
 169        void *aio_ioctl_buf;
 170    };
 171    int aio_niov;
 172    uint64_t aio_nbytes;
 173#define aio_ioctl_cmd   aio_nbytes /* for QEMU_AIO_IOCTL */
 174    off_t aio_offset;
 175    int aio_type;
 176} RawPosixAIOData;
 177
 178#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
 179static int cdrom_reopen(BlockDriverState *bs);
 180#endif
 181
 182#if defined(__NetBSD__)
 183static int raw_normalize_devicepath(const char **filename)
 184{
 185    static char namebuf[PATH_MAX];
 186    const char *dp, *fname;
 187    struct stat sb;
 188
 189    fname = *filename;
 190    dp = strrchr(fname, '/');
 191    if (lstat(fname, &sb) < 0) {
 192        fprintf(stderr, "%s: stat failed: %s\n",
 193            fname, strerror(errno));
 194        return -errno;
 195    }
 196
 197    if (!S_ISBLK(sb.st_mode)) {
 198        return 0;
 199    }
 200
 201    if (dp == NULL) {
 202        snprintf(namebuf, PATH_MAX, "r%s", fname);
 203    } else {
 204        snprintf(namebuf, PATH_MAX, "%.*s/r%s",
 205            (int)(dp - fname), fname, dp + 1);
 206    }
 207    fprintf(stderr, "%s is a block device", fname);
 208    *filename = namebuf;
 209    fprintf(stderr, ", using %s\n", *filename);
 210
 211    return 0;
 212}
 213#else
 214static int raw_normalize_devicepath(const char **filename)
 215{
 216    return 0;
 217}
 218#endif
 219
 220/*
 221 * Get logical block size via ioctl. On success store it in @sector_size_p.
 222 */
 223static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
 224{
 225    unsigned int sector_size;
 226    bool success = false;
 227
 228    errno = ENOTSUP;
 229
 230    /* Try a few ioctls to get the right size */
 231#ifdef BLKSSZGET
 232    if (ioctl(fd, BLKSSZGET, &sector_size) >= 0) {
 233        *sector_size_p = sector_size;
 234        success = true;
 235    }
 236#endif
 237#ifdef DKIOCGETBLOCKSIZE
 238    if (ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) >= 0) {
 239        *sector_size_p = sector_size;
 240        success = true;
 241    }
 242#endif
 243#ifdef DIOCGSECTORSIZE
 244    if (ioctl(fd, DIOCGSECTORSIZE, &sector_size) >= 0) {
 245        *sector_size_p = sector_size;
 246        success = true;
 247    }
 248#endif
 249
 250    return success ? 0 : -errno;
 251}
 252
 253/**
 254 * Get physical block size of @fd.
 255 * On success, store it in @blk_size and return 0.
 256 * On failure, return -errno.
 257 */
 258static int probe_physical_blocksize(int fd, unsigned int *blk_size)
 259{
 260#ifdef BLKPBSZGET
 261    if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
 262        return -errno;
 263    }
 264    return 0;
 265#else
 266    return -ENOTSUP;
 267#endif
 268}
 269
 270/* Check if read is allowed with given memory buffer and length.
 271 *
 272 * This function is used to check O_DIRECT memory buffer and request alignment.
 273 */
 274static bool raw_is_io_aligned(int fd, void *buf, size_t len)
 275{
 276    ssize_t ret = pread(fd, buf, len, 0);
 277
 278    if (ret >= 0) {
 279        return true;
 280    }
 281
 282#ifdef __linux__
 283    /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads.  Ignore
 284     * other errors (e.g. real I/O error), which could happen on a failed
 285     * drive, since we only care about probing alignment.
 286     */
 287    if (errno != EINVAL) {
 288        return true;
 289    }
 290#endif
 291
 292    return false;
 293}
 294
 295static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
 296{
 297    BDRVRawState *s = bs->opaque;
 298    char *buf;
 299    size_t max_align = MAX(MAX_BLOCKSIZE, getpagesize());
 300
 301    /* For SCSI generic devices the alignment is not really used.
 302       With buffered I/O, we don't have any restrictions. */
 303    if (bdrv_is_sg(bs) || !s->needs_alignment) {
 304        bs->request_alignment = 1;
 305        s->buf_align = 1;
 306        return;
 307    }
 308
 309    bs->request_alignment = 0;
 310    s->buf_align = 0;
 311    /* Let's try to use the logical blocksize for the alignment. */
 312    if (probe_logical_blocksize(fd, &bs->request_alignment) < 0) {
 313        bs->request_alignment = 0;
 314    }
 315#ifdef CONFIG_XFS
 316    if (s->is_xfs) {
 317        struct dioattr da;
 318        if (xfsctl(NULL, fd, XFS_IOC_DIOINFO, &da) >= 0) {
 319            bs->request_alignment = da.d_miniosz;
 320            /* The kernel returns wrong information for d_mem */
 321            /* s->buf_align = da.d_mem; */
 322        }
 323    }
 324#endif
 325
 326    /* If we could not get the sizes so far, we can only guess them */
 327    if (!s->buf_align) {
 328        size_t align;
 329        buf = qemu_memalign(max_align, 2 * max_align);
 330        for (align = 512; align <= max_align; align <<= 1) {
 331            if (raw_is_io_aligned(fd, buf + align, max_align)) {
 332                s->buf_align = align;
 333                break;
 334            }
 335        }
 336        qemu_vfree(buf);
 337    }
 338
 339    if (!bs->request_alignment) {
 340        size_t align;
 341        buf = qemu_memalign(s->buf_align, max_align);
 342        for (align = 512; align <= max_align; align <<= 1) {
 343            if (raw_is_io_aligned(fd, buf, align)) {
 344                bs->request_alignment = align;
 345                break;
 346            }
 347        }
 348        qemu_vfree(buf);
 349    }
 350
 351    if (!s->buf_align || !bs->request_alignment) {
 352        error_setg(errp, "Could not find working O_DIRECT alignment. "
 353                         "Try cache.direct=off.");
 354    }
 355}
 356
 357static void raw_parse_flags(int bdrv_flags, int *open_flags)
 358{
 359    assert(open_flags != NULL);
 360
 361    *open_flags |= O_BINARY;
 362    *open_flags &= ~O_ACCMODE;
 363    if (bdrv_flags & BDRV_O_RDWR) {
 364        *open_flags |= O_RDWR;
 365    } else {
 366        *open_flags |= O_RDONLY;
 367    }
 368
 369    /* Use O_DSYNC for write-through caching, no flags for write-back caching,
 370     * and O_DIRECT for no caching. */
 371    if ((bdrv_flags & BDRV_O_NOCACHE)) {
 372        *open_flags |= O_DIRECT;
 373    }
 374}
 375
 376static void raw_detach_aio_context(BlockDriverState *bs)
 377{
 378#ifdef CONFIG_LINUX_AIO
 379    BDRVRawState *s = bs->opaque;
 380
 381    if (s->use_aio) {
 382        laio_detach_aio_context(s->aio_ctx, bdrv_get_aio_context(bs));
 383    }
 384#endif
 385}
 386
 387static void raw_attach_aio_context(BlockDriverState *bs,
 388                                   AioContext *new_context)
 389{
 390#ifdef CONFIG_LINUX_AIO
 391    BDRVRawState *s = bs->opaque;
 392
 393    if (s->use_aio) {
 394        laio_attach_aio_context(s->aio_ctx, new_context);
 395    }
 396#endif
 397}
 398
 399#ifdef CONFIG_LINUX_AIO
 400static int raw_set_aio(void **aio_ctx, int *use_aio, int bdrv_flags)
 401{
 402    int ret = -1;
 403    assert(aio_ctx != NULL);
 404    assert(use_aio != NULL);
 405    /*
 406     * Currently Linux do AIO only for files opened with O_DIRECT
 407     * specified so check NOCACHE flag too
 408     */
 409    if ((bdrv_flags & (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) ==
 410                      (BDRV_O_NOCACHE|BDRV_O_NATIVE_AIO)) {
 411
 412        /* if non-NULL, laio_init() has already been run */
 413        if (*aio_ctx == NULL) {
 414            *aio_ctx = laio_init();
 415            if (!*aio_ctx) {
 416                goto error;
 417            }
 418        }
 419        *use_aio = 1;
 420    } else {
 421        *use_aio = 0;
 422    }
 423
 424    ret = 0;
 425
 426error:
 427    return ret;
 428}
 429#endif
 430
 431static void raw_parse_filename(const char *filename, QDict *options,
 432                               Error **errp)
 433{
 434    /* The filename does not have to be prefixed by the protocol name, since
 435     * "file" is the default protocol; therefore, the return value of this
 436     * function call can be ignored. */
 437    strstart(filename, "file:", &filename);
 438
 439    qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
 440}
 441
 442static QemuOptsList raw_runtime_opts = {
 443    .name = "raw",
 444    .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
 445    .desc = {
 446        {
 447            .name = "filename",
 448            .type = QEMU_OPT_STRING,
 449            .help = "File name of the image",
 450        },
 451        { /* end of list */ }
 452    },
 453};
 454
 455static int raw_open_common(BlockDriverState *bs, QDict *options,
 456                           int bdrv_flags, int open_flags, Error **errp)
 457{
 458    BDRVRawState *s = bs->opaque;
 459    QemuOpts *opts;
 460    Error *local_err = NULL;
 461    const char *filename = NULL;
 462    int fd, ret;
 463    struct stat st;
 464
 465    opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
 466    qemu_opts_absorb_qdict(opts, options, &local_err);
 467    if (local_err) {
 468        error_propagate(errp, local_err);
 469        ret = -EINVAL;
 470        goto fail;
 471    }
 472
 473    filename = qemu_opt_get(opts, "filename");
 474
 475    ret = raw_normalize_devicepath(&filename);
 476    if (ret != 0) {
 477        error_setg_errno(errp, -ret, "Could not normalize device path");
 478        goto fail;
 479    }
 480
 481    s->open_flags = open_flags;
 482    raw_parse_flags(bdrv_flags, &s->open_flags);
 483
 484    s->fd = -1;
 485    fd = qemu_open(filename, s->open_flags, 0644);
 486    if (fd < 0) {
 487        ret = -errno;
 488        if (ret == -EROFS) {
 489            ret = -EACCES;
 490        }
 491        goto fail;
 492    }
 493    s->fd = fd;
 494
 495#ifdef CONFIG_LINUX_AIO
 496    if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {
 497        qemu_close(fd);
 498        ret = -errno;
 499        error_setg_errno(errp, -ret, "Could not set AIO state");
 500        goto fail;
 501    }
 502    if (!s->use_aio && (bdrv_flags & BDRV_O_NATIVE_AIO)) {
 503        error_printf("WARNING: aio=native was specified for '%s', but "
 504                     "it requires cache.direct=on, which was not "
 505                     "specified. Falling back to aio=threads.\n"
 506                     "         This will become an error condition in "
 507                     "future QEMU versions.\n",
 508                     bs->filename);
 509    }
 510#else
 511    if (bdrv_flags & BDRV_O_NATIVE_AIO) {
 512        error_printf("WARNING: aio=native was specified for '%s', but "
 513                     "is not supported in this build. Falling back to "
 514                     "aio=threads.\n"
 515                     "         This will become an error condition in "
 516                     "future QEMU versions.\n",
 517                     bs->filename);
 518    }
 519#endif /* !defined(CONFIG_LINUX_AIO) */
 520
 521    s->has_discard = true;
 522    s->has_write_zeroes = true;
 523    if ((bs->open_flags & BDRV_O_NOCACHE) != 0) {
 524        s->needs_alignment = true;
 525    }
 526
 527    if (fstat(s->fd, &st) < 0) {
 528        ret = -errno;
 529        error_setg_errno(errp, errno, "Could not stat file");
 530        goto fail;
 531    }
 532    if (S_ISREG(st.st_mode)) {
 533        s->discard_zeroes = true;
 534        s->has_fallocate = true;
 535    }
 536    if (S_ISBLK(st.st_mode)) {
 537#ifdef BLKDISCARDZEROES
 538        unsigned int arg;
 539        if (ioctl(s->fd, BLKDISCARDZEROES, &arg) == 0 && arg) {
 540            s->discard_zeroes = true;
 541        }
 542#endif
 543#ifdef __linux__
 544        /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache.  Do
 545         * not rely on the contents of discarded blocks unless using O_DIRECT.
 546         * Same for BLKZEROOUT.
 547         */
 548        if (!(bs->open_flags & BDRV_O_NOCACHE)) {
 549            s->discard_zeroes = false;
 550            s->has_write_zeroes = false;
 551        }
 552#endif
 553    }
 554#ifdef __FreeBSD__
 555    if (S_ISCHR(st.st_mode)) {
 556        /*
 557         * The file is a char device (disk), which on FreeBSD isn't behind
 558         * a pager, so force all requests to be aligned. This is needed
 559         * so QEMU makes sure all IO operations on the device are aligned
 560         * to sector size, or else FreeBSD will reject them with EINVAL.
 561         */
 562        s->needs_alignment = true;
 563    }
 564#endif
 565
 566#ifdef CONFIG_XFS
 567    if (platform_test_xfs_fd(s->fd)) {
 568        s->is_xfs = true;
 569    }
 570#endif
 571
 572    raw_attach_aio_context(bs, bdrv_get_aio_context(bs));
 573
 574    ret = 0;
 575fail:
 576    if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
 577        unlink(filename);
 578    }
 579    qemu_opts_del(opts);
 580    return ret;
 581}
 582
 583static int raw_open(BlockDriverState *bs, QDict *options, int flags,
 584                    Error **errp)
 585{
 586    BDRVRawState *s = bs->opaque;
 587    Error *local_err = NULL;
 588    int ret;
 589
 590    s->type = FTYPE_FILE;
 591    ret = raw_open_common(bs, options, flags, 0, &local_err);
 592    if (local_err) {
 593        error_propagate(errp, local_err);
 594    }
 595    return ret;
 596}
 597
 598static int raw_reopen_prepare(BDRVReopenState *state,
 599                              BlockReopenQueue *queue, Error **errp)
 600{
 601    BDRVRawState *s;
 602    BDRVRawReopenState *raw_s;
 603    int ret = 0;
 604    Error *local_err = NULL;
 605
 606    assert(state != NULL);
 607    assert(state->bs != NULL);
 608
 609    s = state->bs->opaque;
 610
 611    state->opaque = g_new0(BDRVRawReopenState, 1);
 612    raw_s = state->opaque;
 613
 614#ifdef CONFIG_LINUX_AIO
 615    raw_s->use_aio = s->use_aio;
 616
 617    /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
 618     * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
 619     * won't override aio_ctx if aio_ctx is non-NULL */
 620    if (raw_set_aio(&s->aio_ctx, &raw_s->use_aio, state->flags)) {
 621        error_setg(errp, "Could not set AIO state");
 622        return -1;
 623    }
 624#endif
 625
 626    if (s->type == FTYPE_CD) {
 627        raw_s->open_flags |= O_NONBLOCK;
 628    }
 629
 630    raw_parse_flags(state->flags, &raw_s->open_flags);
 631
 632    raw_s->fd = -1;
 633
 634    int fcntl_flags = O_APPEND | O_NONBLOCK;
 635#ifdef O_NOATIME
 636    fcntl_flags |= O_NOATIME;
 637#endif
 638
 639#ifdef O_ASYNC
 640    /* Not all operating systems have O_ASYNC, and those that don't
 641     * will not let us track the state into raw_s->open_flags (typically
 642     * you achieve the same effect with an ioctl, for example I_SETSIG
 643     * on Solaris). But we do not use O_ASYNC, so that's fine.
 644     */
 645    assert((s->open_flags & O_ASYNC) == 0);
 646#endif
 647
 648    if ((raw_s->open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
 649        /* dup the original fd */
 650        /* TODO: use qemu fcntl wrapper */
 651#ifdef F_DUPFD_CLOEXEC
 652        raw_s->fd = fcntl(s->fd, F_DUPFD_CLOEXEC, 0);
 653#else
 654        raw_s->fd = dup(s->fd);
 655        if (raw_s->fd != -1) {
 656            qemu_set_cloexec(raw_s->fd);
 657        }
 658#endif
 659        if (raw_s->fd >= 0) {
 660            ret = fcntl_setfl(raw_s->fd, raw_s->open_flags);
 661            if (ret) {
 662                qemu_close(raw_s->fd);
 663                raw_s->fd = -1;
 664            }
 665        }
 666    }
 667
 668    /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
 669    if (raw_s->fd == -1) {
 670        const char *normalized_filename = state->bs->filename;
 671        ret = raw_normalize_devicepath(&normalized_filename);
 672        if (ret < 0) {
 673            error_setg_errno(errp, -ret, "Could not normalize device path");
 674        } else {
 675            assert(!(raw_s->open_flags & O_CREAT));
 676            raw_s->fd = qemu_open(normalized_filename, raw_s->open_flags);
 677            if (raw_s->fd == -1) {
 678                error_setg_errno(errp, errno, "Could not reopen file");
 679                ret = -1;
 680            }
 681        }
 682    }
 683
 684    /* Fail already reopen_prepare() if we can't get a working O_DIRECT
 685     * alignment with the new fd. */
 686    if (raw_s->fd != -1) {
 687        raw_probe_alignment(state->bs, raw_s->fd, &local_err);
 688        if (local_err) {
 689            qemu_close(raw_s->fd);
 690            raw_s->fd = -1;
 691            error_propagate(errp, local_err);
 692            ret = -EINVAL;
 693        }
 694    }
 695
 696    return ret;
 697}
 698
 699static void raw_reopen_commit(BDRVReopenState *state)
 700{
 701    BDRVRawReopenState *raw_s = state->opaque;
 702    BDRVRawState *s = state->bs->opaque;
 703
 704    s->open_flags = raw_s->open_flags;
 705
 706    qemu_close(s->fd);
 707    s->fd = raw_s->fd;
 708#ifdef CONFIG_LINUX_AIO
 709    s->use_aio = raw_s->use_aio;
 710#endif
 711
 712    g_free(state->opaque);
 713    state->opaque = NULL;
 714}
 715
 716
 717static void raw_reopen_abort(BDRVReopenState *state)
 718{
 719    BDRVRawReopenState *raw_s = state->opaque;
 720
 721     /* nothing to do if NULL, we didn't get far enough */
 722    if (raw_s == NULL) {
 723        return;
 724    }
 725
 726    if (raw_s->fd >= 0) {
 727        qemu_close(raw_s->fd);
 728        raw_s->fd = -1;
 729    }
 730    g_free(state->opaque);
 731    state->opaque = NULL;
 732}
 733
 734static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
 735{
 736    BDRVRawState *s = bs->opaque;
 737
 738    raw_probe_alignment(bs, s->fd, errp);
 739    bs->bl.min_mem_alignment = s->buf_align;
 740    bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());
 741}
 742
 743static int check_for_dasd(int fd)
 744{
 745#ifdef BIODASDINFO2
 746    struct dasd_information2_t info = {0};
 747
 748    return ioctl(fd, BIODASDINFO2, &info);
 749#else
 750    return -1;
 751#endif
 752}
 753
 754/**
 755 * Try to get @bs's logical and physical block size.
 756 * On success, store them in @bsz and return zero.
 757 * On failure, return negative errno.
 758 */
 759static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
 760{
 761    BDRVRawState *s = bs->opaque;
 762    int ret;
 763
 764    /* If DASD, get blocksizes */
 765    if (check_for_dasd(s->fd) < 0) {
 766        return -ENOTSUP;
 767    }
 768    ret = probe_logical_blocksize(s->fd, &bsz->log);
 769    if (ret < 0) {
 770        return ret;
 771    }
 772    return probe_physical_blocksize(s->fd, &bsz->phys);
 773}
 774
 775/**
 776 * Try to get @bs's geometry: cyls, heads, sectors.
 777 * On success, store them in @geo and return 0.
 778 * On failure return -errno.
 779 * (Allows block driver to assign default geometry values that guest sees)
 780 */
 781#ifdef __linux__
 782static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
 783{
 784    BDRVRawState *s = bs->opaque;
 785    struct hd_geometry ioctl_geo = {0};
 786
 787    /* If DASD, get its geometry */
 788    if (check_for_dasd(s->fd) < 0) {
 789        return -ENOTSUP;
 790    }
 791    if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
 792        return -errno;
 793    }
 794    /* HDIO_GETGEO may return success even though geo contains zeros
 795       (e.g. certain multipath setups) */
 796    if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
 797        return -ENOTSUP;
 798    }
 799    /* Do not return a geometry for partition */
 800    if (ioctl_geo.start != 0) {
 801        return -ENOTSUP;
 802    }
 803    geo->heads = ioctl_geo.heads;
 804    geo->sectors = ioctl_geo.sectors;
 805    geo->cylinders = ioctl_geo.cylinders;
 806
 807    return 0;
 808}
 809#else /* __linux__ */
 810static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
 811{
 812    return -ENOTSUP;
 813}
 814#endif
 815
 816static ssize_t handle_aiocb_ioctl(RawPosixAIOData *aiocb)
 817{
 818    int ret;
 819
 820    ret = ioctl(aiocb->aio_fildes, aiocb->aio_ioctl_cmd, aiocb->aio_ioctl_buf);
 821    if (ret == -1) {
 822        return -errno;
 823    }
 824
 825    return 0;
 826}
 827
 828static ssize_t handle_aiocb_flush(RawPosixAIOData *aiocb)
 829{
 830    int ret;
 831
 832    ret = qemu_fdatasync(aiocb->aio_fildes);
 833    if (ret == -1) {
 834        return -errno;
 835    }
 836    return 0;
 837}
 838
 839#ifdef CONFIG_PREADV
 840
 841static bool preadv_present = true;
 842
 843static ssize_t
 844qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
 845{
 846    return preadv(fd, iov, nr_iov, offset);
 847}
 848
 849static ssize_t
 850qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
 851{
 852    return pwritev(fd, iov, nr_iov, offset);
 853}
 854
 855#else
 856
 857static bool preadv_present = false;
 858
 859static ssize_t
 860qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
 861{
 862    return -ENOSYS;
 863}
 864
 865static ssize_t
 866qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
 867{
 868    return -ENOSYS;
 869}
 870
 871#endif
 872
 873static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
 874{
 875    ssize_t len;
 876
 877    do {
 878        if (aiocb->aio_type & QEMU_AIO_WRITE)
 879            len = qemu_pwritev(aiocb->aio_fildes,
 880                               aiocb->aio_iov,
 881                               aiocb->aio_niov,
 882                               aiocb->aio_offset);
 883         else
 884            len = qemu_preadv(aiocb->aio_fildes,
 885                              aiocb->aio_iov,
 886                              aiocb->aio_niov,
 887                              aiocb->aio_offset);
 888    } while (len == -1 && errno == EINTR);
 889
 890    if (len == -1) {
 891        return -errno;
 892    }
 893    return len;
 894}
 895
 896/*
 897 * Read/writes the data to/from a given linear buffer.
 898 *
 899 * Returns the number of bytes handles or -errno in case of an error. Short
 900 * reads are only returned if the end of the file is reached.
 901 */
 902static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
 903{
 904    ssize_t offset = 0;
 905    ssize_t len;
 906
 907    while (offset < aiocb->aio_nbytes) {
 908        if (aiocb->aio_type & QEMU_AIO_WRITE) {
 909            len = pwrite(aiocb->aio_fildes,
 910                         (const char *)buf + offset,
 911                         aiocb->aio_nbytes - offset,
 912                         aiocb->aio_offset + offset);
 913        } else {
 914            len = pread(aiocb->aio_fildes,
 915                        buf + offset,
 916                        aiocb->aio_nbytes - offset,
 917                        aiocb->aio_offset + offset);
 918        }
 919        if (len == -1 && errno == EINTR) {
 920            continue;
 921        } else if (len == -1 && errno == EINVAL &&
 922                   (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
 923                   !(aiocb->aio_type & QEMU_AIO_WRITE) &&
 924                   offset > 0) {
 925            /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
 926             * after a short read.  Assume that O_DIRECT short reads only occur
 927             * at EOF.  Therefore this is a short read, not an I/O error.
 928             */
 929            break;
 930        } else if (len == -1) {
 931            offset = -errno;
 932            break;
 933        } else if (len == 0) {
 934            break;
 935        }
 936        offset += len;
 937    }
 938
 939    return offset;
 940}
 941
 942static ssize_t handle_aiocb_rw(RawPosixAIOData *aiocb)
 943{
 944    ssize_t nbytes;
 945    char *buf;
 946
 947    if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
 948        /*
 949         * If there is just a single buffer, and it is properly aligned
 950         * we can just use plain pread/pwrite without any problems.
 951         */
 952        if (aiocb->aio_niov == 1) {
 953             return handle_aiocb_rw_linear(aiocb, aiocb->aio_iov->iov_base);
 954        }
 955        /*
 956         * We have more than one iovec, and all are properly aligned.
 957         *
 958         * Try preadv/pwritev first and fall back to linearizing the
 959         * buffer if it's not supported.
 960         */
 961        if (preadv_present) {
 962            nbytes = handle_aiocb_rw_vector(aiocb);
 963            if (nbytes == aiocb->aio_nbytes ||
 964                (nbytes < 0 && nbytes != -ENOSYS)) {
 965                return nbytes;
 966            }
 967            preadv_present = false;
 968        }
 969
 970        /*
 971         * XXX(hch): short read/write.  no easy way to handle the reminder
 972         * using these interfaces.  For now retry using plain
 973         * pread/pwrite?
 974         */
 975    }
 976
 977    /*
 978     * Ok, we have to do it the hard way, copy all segments into
 979     * a single aligned buffer.
 980     */
 981    buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
 982    if (buf == NULL) {
 983        return -ENOMEM;
 984    }
 985
 986    if (aiocb->aio_type & QEMU_AIO_WRITE) {
 987        char *p = buf;
 988        int i;
 989
 990        for (i = 0; i < aiocb->aio_niov; ++i) {
 991            memcpy(p, aiocb->aio_iov[i].iov_base, aiocb->aio_iov[i].iov_len);
 992            p += aiocb->aio_iov[i].iov_len;
 993        }
 994        assert(p - buf == aiocb->aio_nbytes);
 995    }
 996
 997    nbytes = handle_aiocb_rw_linear(aiocb, buf);
 998    if (!(aiocb->aio_type & QEMU_AIO_WRITE)) {
 999        char *p = buf;
1000        size_t count = aiocb->aio_nbytes, copy;
1001        int i;
1002
1003        for (i = 0; i < aiocb->aio_niov && count; ++i) {
1004            copy = count;
1005            if (copy > aiocb->aio_iov[i].iov_len) {
1006                copy = aiocb->aio_iov[i].iov_len;
1007            }
1008            memcpy(aiocb->aio_iov[i].iov_base, p, copy);
1009            assert(count >= copy);
1010            p     += copy;
1011            count -= copy;
1012        }
1013        assert(count == 0);
1014    }
1015    qemu_vfree(buf);
1016
1017    return nbytes;
1018}
1019
1020#ifdef CONFIG_XFS
1021static int xfs_write_zeroes(BDRVRawState *s, int64_t offset, uint64_t bytes)
1022{
1023    struct xfs_flock64 fl;
1024    int err;
1025
1026    memset(&fl, 0, sizeof(fl));
1027    fl.l_whence = SEEK_SET;
1028    fl.l_start = offset;
1029    fl.l_len = bytes;
1030
1031    if (xfsctl(NULL, s->fd, XFS_IOC_ZERO_RANGE, &fl) < 0) {
1032        err = errno;
1033        DPRINTF("cannot write zero range (%s)\n", strerror(errno));
1034        return -err;
1035    }
1036
1037    return 0;
1038}
1039
1040static int xfs_discard(BDRVRawState *s, int64_t offset, uint64_t bytes)
1041{
1042    struct xfs_flock64 fl;
1043    int err;
1044
1045    memset(&fl, 0, sizeof(fl));
1046    fl.l_whence = SEEK_SET;
1047    fl.l_start = offset;
1048    fl.l_len = bytes;
1049
1050    if (xfsctl(NULL, s->fd, XFS_IOC_UNRESVSP64, &fl) < 0) {
1051        err = errno;
1052        DPRINTF("cannot punch hole (%s)\n", strerror(errno));
1053        return -err;
1054    }
1055
1056    return 0;
1057}
1058#endif
1059
1060static int translate_err(int err)
1061{
1062    if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1063        err == -ENOTTY) {
1064        err = -ENOTSUP;
1065    }
1066    return err;
1067}
1068
1069#ifdef CONFIG_FALLOCATE
1070static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1071{
1072    do {
1073        if (fallocate(fd, mode, offset, len) == 0) {
1074            return 0;
1075        }
1076    } while (errno == EINTR);
1077    return translate_err(-errno);
1078}
1079#endif
1080
1081static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1082{
1083    int ret = -ENOTSUP;
1084    BDRVRawState *s = aiocb->bs->opaque;
1085
1086    if (!s->has_write_zeroes) {
1087        return -ENOTSUP;
1088    }
1089
1090#ifdef BLKZEROOUT
1091    do {
1092        uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1093        if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1094            return 0;
1095        }
1096    } while (errno == EINTR);
1097
1098    ret = translate_err(-errno);
1099#endif
1100
1101    if (ret == -ENOTSUP) {
1102        s->has_write_zeroes = false;
1103    }
1104    return ret;
1105}
1106
1107static ssize_t handle_aiocb_write_zeroes(RawPosixAIOData *aiocb)
1108{
1109#if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1110    BDRVRawState *s = aiocb->bs->opaque;
1111#endif
1112
1113    if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1114        return handle_aiocb_write_zeroes_block(aiocb);
1115    }
1116
1117#ifdef CONFIG_XFS
1118    if (s->is_xfs) {
1119        return xfs_write_zeroes(s, aiocb->aio_offset, aiocb->aio_nbytes);
1120    }
1121#endif
1122
1123#ifdef CONFIG_FALLOCATE_ZERO_RANGE
1124    if (s->has_write_zeroes) {
1125        int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1126                               aiocb->aio_offset, aiocb->aio_nbytes);
1127        if (ret == 0 || ret != -ENOTSUP) {
1128            return ret;
1129        }
1130        s->has_write_zeroes = false;
1131    }
1132#endif
1133
1134#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1135    if (s->has_discard && s->has_fallocate) {
1136        int ret = do_fallocate(s->fd,
1137                               FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1138                               aiocb->aio_offset, aiocb->aio_nbytes);
1139        if (ret == 0) {
1140            ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1141            if (ret == 0 || ret != -ENOTSUP) {
1142                return ret;
1143            }
1144            s->has_fallocate = false;
1145        } else if (ret != -ENOTSUP) {
1146            return ret;
1147        } else {
1148            s->has_discard = false;
1149        }
1150    }
1151#endif
1152
1153#ifdef CONFIG_FALLOCATE
1154    if (s->has_fallocate && aiocb->aio_offset >= bdrv_getlength(aiocb->bs)) {
1155        int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1156        if (ret == 0 || ret != -ENOTSUP) {
1157            return ret;
1158        }
1159        s->has_fallocate = false;
1160    }
1161#endif
1162
1163    return -ENOTSUP;
1164}
1165
1166static ssize_t handle_aiocb_discard(RawPosixAIOData *aiocb)
1167{
1168    int ret = -EOPNOTSUPP;
1169    BDRVRawState *s = aiocb->bs->opaque;
1170
1171    if (!s->has_discard) {
1172        return -ENOTSUP;
1173    }
1174
1175    if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1176#ifdef BLKDISCARD
1177        do {
1178            uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1179            if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
1180                return 0;
1181            }
1182        } while (errno == EINTR);
1183
1184        ret = -errno;
1185#endif
1186    } else {
1187#ifdef CONFIG_XFS
1188        if (s->is_xfs) {
1189            return xfs_discard(s, aiocb->aio_offset, aiocb->aio_nbytes);
1190        }
1191#endif
1192
1193#ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1194        ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1195                           aiocb->aio_offset, aiocb->aio_nbytes);
1196#endif
1197    }
1198
1199    ret = translate_err(ret);
1200    if (ret == -ENOTSUP) {
1201        s->has_discard = false;
1202    }
1203    return ret;
1204}
1205
1206static int aio_worker(void *arg)
1207{
1208    RawPosixAIOData *aiocb = arg;
1209    ssize_t ret = 0;
1210
1211    switch (aiocb->aio_type & QEMU_AIO_TYPE_MASK) {
1212    case QEMU_AIO_READ:
1213        ret = handle_aiocb_rw(aiocb);
1214        if (ret >= 0 && ret < aiocb->aio_nbytes) {
1215            iov_memset(aiocb->aio_iov, aiocb->aio_niov, ret,
1216                      0, aiocb->aio_nbytes - ret);
1217
1218            ret = aiocb->aio_nbytes;
1219        }
1220        if (ret == aiocb->aio_nbytes) {
1221            ret = 0;
1222        } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1223            ret = -EINVAL;
1224        }
1225        break;
1226    case QEMU_AIO_WRITE:
1227        ret = handle_aiocb_rw(aiocb);
1228        if (ret == aiocb->aio_nbytes) {
1229            ret = 0;
1230        } else if (ret >= 0 && ret < aiocb->aio_nbytes) {
1231            ret = -EINVAL;
1232        }
1233        break;
1234    case QEMU_AIO_FLUSH:
1235        ret = handle_aiocb_flush(aiocb);
1236        break;
1237    case QEMU_AIO_IOCTL:
1238        ret = handle_aiocb_ioctl(aiocb);
1239        break;
1240    case QEMU_AIO_DISCARD:
1241        ret = handle_aiocb_discard(aiocb);
1242        break;
1243    case QEMU_AIO_WRITE_ZEROES:
1244        ret = handle_aiocb_write_zeroes(aiocb);
1245        break;
1246    default:
1247        fprintf(stderr, "invalid aio request (0x%x)\n", aiocb->aio_type);
1248        ret = -EINVAL;
1249        break;
1250    }
1251
1252    g_free(aiocb);
1253    return ret;
1254}
1255
1256static int paio_submit_co(BlockDriverState *bs, int fd,
1257        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1258        int type)
1259{
1260    RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1261    ThreadPool *pool;
1262
1263    acb->bs = bs;
1264    acb->aio_type = type;
1265    acb->aio_fildes = fd;
1266
1267    acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1268    acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1269
1270    if (qiov) {
1271        acb->aio_iov = qiov->iov;
1272        acb->aio_niov = qiov->niov;
1273        assert(qiov->size == acb->aio_nbytes);
1274    }
1275
1276    trace_paio_submit_co(sector_num, nb_sectors, type);
1277    pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1278    return thread_pool_submit_co(pool, aio_worker, acb);
1279}
1280
1281static BlockAIOCB *paio_submit(BlockDriverState *bs, int fd,
1282        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1283        BlockCompletionFunc *cb, void *opaque, int type)
1284{
1285    RawPosixAIOData *acb = g_new(RawPosixAIOData, 1);
1286    ThreadPool *pool;
1287
1288    acb->bs = bs;
1289    acb->aio_type = type;
1290    acb->aio_fildes = fd;
1291
1292    acb->aio_nbytes = nb_sectors * BDRV_SECTOR_SIZE;
1293    acb->aio_offset = sector_num * BDRV_SECTOR_SIZE;
1294
1295    if (qiov) {
1296        acb->aio_iov = qiov->iov;
1297        acb->aio_niov = qiov->niov;
1298        assert(qiov->size == acb->aio_nbytes);
1299    }
1300
1301    trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);
1302    pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
1303    return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
1304}
1305
1306static BlockAIOCB *raw_aio_submit(BlockDriverState *bs,
1307        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1308        BlockCompletionFunc *cb, void *opaque, int type)
1309{
1310    BDRVRawState *s = bs->opaque;
1311
1312    if (fd_open(bs) < 0)
1313        return NULL;
1314
1315    /*
1316     * Check if the underlying device requires requests to be aligned,
1317     * and if the request we are trying to submit is aligned or not.
1318     * If this is the case tell the low-level driver that it needs
1319     * to copy the buffer.
1320     */
1321    if (s->needs_alignment) {
1322        if (!bdrv_qiov_is_aligned(bs, qiov)) {
1323            type |= QEMU_AIO_MISALIGNED;
1324#ifdef CONFIG_LINUX_AIO
1325        } else if (s->use_aio) {
1326            return laio_submit(bs, s->aio_ctx, s->fd, sector_num, qiov,
1327                               nb_sectors, cb, opaque, type);
1328#endif
1329        }
1330    }
1331
1332    return paio_submit(bs, s->fd, sector_num, qiov, nb_sectors,
1333                       cb, opaque, type);
1334}
1335
1336static void raw_aio_plug(BlockDriverState *bs)
1337{
1338#ifdef CONFIG_LINUX_AIO
1339    BDRVRawState *s = bs->opaque;
1340    if (s->use_aio) {
1341        laio_io_plug(bs, s->aio_ctx);
1342    }
1343#endif
1344}
1345
1346static void raw_aio_unplug(BlockDriverState *bs)
1347{
1348#ifdef CONFIG_LINUX_AIO
1349    BDRVRawState *s = bs->opaque;
1350    if (s->use_aio) {
1351        laio_io_unplug(bs, s->aio_ctx, true);
1352    }
1353#endif
1354}
1355
1356static void raw_aio_flush_io_queue(BlockDriverState *bs)
1357{
1358#ifdef CONFIG_LINUX_AIO
1359    BDRVRawState *s = bs->opaque;
1360    if (s->use_aio) {
1361        laio_io_unplug(bs, s->aio_ctx, false);
1362    }
1363#endif
1364}
1365
1366static BlockAIOCB *raw_aio_readv(BlockDriverState *bs,
1367        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1368        BlockCompletionFunc *cb, void *opaque)
1369{
1370    return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1371                          cb, opaque, QEMU_AIO_READ);
1372}
1373
1374static BlockAIOCB *raw_aio_writev(BlockDriverState *bs,
1375        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1376        BlockCompletionFunc *cb, void *opaque)
1377{
1378    return raw_aio_submit(bs, sector_num, qiov, nb_sectors,
1379                          cb, opaque, QEMU_AIO_WRITE);
1380}
1381
1382static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
1383        BlockCompletionFunc *cb, void *opaque)
1384{
1385    BDRVRawState *s = bs->opaque;
1386
1387    if (fd_open(bs) < 0)
1388        return NULL;
1389
1390    return paio_submit(bs, s->fd, 0, NULL, 0, cb, opaque, QEMU_AIO_FLUSH);
1391}
1392
1393static void raw_close(BlockDriverState *bs)
1394{
1395    BDRVRawState *s = bs->opaque;
1396
1397    raw_detach_aio_context(bs);
1398
1399#ifdef CONFIG_LINUX_AIO
1400    if (s->use_aio) {
1401        laio_cleanup(s->aio_ctx);
1402    }
1403#endif
1404    if (s->fd >= 0) {
1405        qemu_close(s->fd);
1406        s->fd = -1;
1407    }
1408}
1409
1410static int raw_truncate(BlockDriverState *bs, int64_t offset)
1411{
1412    BDRVRawState *s = bs->opaque;
1413    struct stat st;
1414
1415    if (fstat(s->fd, &st)) {
1416        return -errno;
1417    }
1418
1419    if (S_ISREG(st.st_mode)) {
1420        if (ftruncate(s->fd, offset) < 0) {
1421            return -errno;
1422        }
1423    } else if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1424       if (offset > raw_getlength(bs)) {
1425           return -EINVAL;
1426       }
1427    } else {
1428        return -ENOTSUP;
1429    }
1430
1431    return 0;
1432}
1433
1434#ifdef __OpenBSD__
1435static int64_t raw_getlength(BlockDriverState *bs)
1436{
1437    BDRVRawState *s = bs->opaque;
1438    int fd = s->fd;
1439    struct stat st;
1440
1441    if (fstat(fd, &st))
1442        return -errno;
1443    if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1444        struct disklabel dl;
1445
1446        if (ioctl(fd, DIOCGDINFO, &dl))
1447            return -errno;
1448        return (uint64_t)dl.d_secsize *
1449            dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1450    } else
1451        return st.st_size;
1452}
1453#elif defined(__NetBSD__)
1454static int64_t raw_getlength(BlockDriverState *bs)
1455{
1456    BDRVRawState *s = bs->opaque;
1457    int fd = s->fd;
1458    struct stat st;
1459
1460    if (fstat(fd, &st))
1461        return -errno;
1462    if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
1463        struct dkwedge_info dkw;
1464
1465        if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
1466            return dkw.dkw_size * 512;
1467        } else {
1468            struct disklabel dl;
1469
1470            if (ioctl(fd, DIOCGDINFO, &dl))
1471                return -errno;
1472            return (uint64_t)dl.d_secsize *
1473                dl.d_partitions[DISKPART(st.st_rdev)].p_size;
1474        }
1475    } else
1476        return st.st_size;
1477}
1478#elif defined(__sun__)
1479static int64_t raw_getlength(BlockDriverState *bs)
1480{
1481    BDRVRawState *s = bs->opaque;
1482    struct dk_minfo minfo;
1483    int ret;
1484    int64_t size;
1485
1486    ret = fd_open(bs);
1487    if (ret < 0) {
1488        return ret;
1489    }
1490
1491    /*
1492     * Use the DKIOCGMEDIAINFO ioctl to read the size.
1493     */
1494    ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
1495    if (ret != -1) {
1496        return minfo.dki_lbsize * minfo.dki_capacity;
1497    }
1498
1499    /*
1500     * There are reports that lseek on some devices fails, but
1501     * irc discussion said that contingency on contingency was overkill.
1502     */
1503    size = lseek(s->fd, 0, SEEK_END);
1504    if (size < 0) {
1505        return -errno;
1506    }
1507    return size;
1508}
1509#elif defined(CONFIG_BSD)
1510static int64_t raw_getlength(BlockDriverState *bs)
1511{
1512    BDRVRawState *s = bs->opaque;
1513    int fd = s->fd;
1514    int64_t size;
1515    struct stat sb;
1516#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1517    int reopened = 0;
1518#endif
1519    int ret;
1520
1521    ret = fd_open(bs);
1522    if (ret < 0)
1523        return ret;
1524
1525#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1526again:
1527#endif
1528    if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
1529#ifdef DIOCGMEDIASIZE
1530        if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size))
1531#elif defined(DIOCGPART)
1532        {
1533                struct partinfo pi;
1534                if (ioctl(fd, DIOCGPART, &pi) == 0)
1535                        size = pi.media_size;
1536                else
1537                        size = 0;
1538        }
1539        if (size == 0)
1540#endif
1541#if defined(__APPLE__) && defined(__MACH__)
1542        {
1543            uint64_t sectors = 0;
1544            uint32_t sector_size = 0;
1545
1546            if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
1547               && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
1548                size = sectors * sector_size;
1549            } else {
1550                size = lseek(fd, 0LL, SEEK_END);
1551                if (size < 0) {
1552                    return -errno;
1553                }
1554            }
1555        }
1556#else
1557        size = lseek(fd, 0LL, SEEK_END);
1558        if (size < 0) {
1559            return -errno;
1560        }
1561#endif
1562#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1563        switch(s->type) {
1564        case FTYPE_CD:
1565            /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1566            if (size == 2048LL * (unsigned)-1)
1567                size = 0;
1568            /* XXX no disc?  maybe we need to reopen... */
1569            if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
1570                reopened = 1;
1571                goto again;
1572            }
1573        }
1574#endif
1575    } else {
1576        size = lseek(fd, 0, SEEK_END);
1577        if (size < 0) {
1578            return -errno;
1579        }
1580    }
1581    return size;
1582}
1583#else
1584static int64_t raw_getlength(BlockDriverState *bs)
1585{
1586    BDRVRawState *s = bs->opaque;
1587    int ret;
1588    int64_t size;
1589
1590    ret = fd_open(bs);
1591    if (ret < 0) {
1592        return ret;
1593    }
1594
1595    size = lseek(s->fd, 0, SEEK_END);
1596    if (size < 0) {
1597        return -errno;
1598    }
1599    return size;
1600}
1601#endif
1602
1603static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
1604{
1605    struct stat st;
1606    BDRVRawState *s = bs->opaque;
1607
1608    if (fstat(s->fd, &st) < 0) {
1609        return -errno;
1610    }
1611    return (int64_t)st.st_blocks * 512;
1612}
1613
1614static int raw_create(const char *filename, QemuOpts *opts, Error **errp)
1615{
1616    int fd;
1617    int result = 0;
1618    int64_t total_size = 0;
1619    bool nocow = false;
1620    PreallocMode prealloc;
1621    char *buf = NULL;
1622    Error *local_err = NULL;
1623
1624    strstart(filename, "file:", &filename);
1625
1626    /* Read out options */
1627    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1628                          BDRV_SECTOR_SIZE);
1629    nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
1630    buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1631    prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
1632                               PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
1633                               &local_err);
1634    g_free(buf);
1635    if (local_err) {
1636        error_propagate(errp, local_err);
1637        result = -EINVAL;
1638        goto out;
1639    }
1640
1641    fd = qemu_open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY,
1642                   0644);
1643    if (fd < 0) {
1644        result = -errno;
1645        error_setg_errno(errp, -result, "Could not create file");
1646        goto out;
1647    }
1648
1649    if (nocow) {
1650#ifdef __linux__
1651        /* Set NOCOW flag to solve performance issue on fs like btrfs.
1652         * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1653         * will be ignored since any failure of this operation should not
1654         * block the left work.
1655         */
1656        int attr;
1657        if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
1658            attr |= FS_NOCOW_FL;
1659            ioctl(fd, FS_IOC_SETFLAGS, &attr);
1660        }
1661#endif
1662    }
1663
1664    if (ftruncate(fd, total_size) != 0) {
1665        result = -errno;
1666        error_setg_errno(errp, -result, "Could not resize file");
1667        goto out_close;
1668    }
1669
1670    switch (prealloc) {
1671#ifdef CONFIG_POSIX_FALLOCATE
1672    case PREALLOC_MODE_FALLOC:
1673        /* posix_fallocate() doesn't set errno. */
1674        result = -posix_fallocate(fd, 0, total_size);
1675        if (result != 0) {
1676            error_setg_errno(errp, -result,
1677                             "Could not preallocate data for the new file");
1678        }
1679        break;
1680#endif
1681    case PREALLOC_MODE_FULL:
1682    {
1683        int64_t num = 0, left = total_size;
1684        buf = g_malloc0(65536);
1685
1686        while (left > 0) {
1687            num = MIN(left, 65536);
1688            result = write(fd, buf, num);
1689            if (result < 0) {
1690                result = -errno;
1691                error_setg_errno(errp, -result,
1692                                 "Could not write to the new file");
1693                break;
1694            }
1695            left -= result;
1696        }
1697        if (result >= 0) {
1698            result = fsync(fd);
1699            if (result < 0) {
1700                result = -errno;
1701                error_setg_errno(errp, -result,
1702                                 "Could not flush new file to disk");
1703            }
1704        }
1705        g_free(buf);
1706        break;
1707    }
1708    case PREALLOC_MODE_OFF:
1709        break;
1710    default:
1711        result = -EINVAL;
1712        error_setg(errp, "Unsupported preallocation mode: %s",
1713                   PreallocMode_lookup[prealloc]);
1714        break;
1715    }
1716
1717out_close:
1718    if (qemu_close(fd) != 0 && result == 0) {
1719        result = -errno;
1720        error_setg_errno(errp, -result, "Could not close the new file");
1721    }
1722out:
1723    return result;
1724}
1725
1726/*
1727 * Find allocation range in @bs around offset @start.
1728 * May change underlying file descriptor's file offset.
1729 * If @start is not in a hole, store @start in @data, and the
1730 * beginning of the next hole in @hole, and return 0.
1731 * If @start is in a non-trailing hole, store @start in @hole and the
1732 * beginning of the next non-hole in @data, and return 0.
1733 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1734 * If we can't find out, return a negative errno other than -ENXIO.
1735 */
1736static int find_allocation(BlockDriverState *bs, off_t start,
1737                           off_t *data, off_t *hole)
1738{
1739#if defined SEEK_HOLE && defined SEEK_DATA
1740    BDRVRawState *s = bs->opaque;
1741    off_t offs;
1742
1743    /*
1744     * SEEK_DATA cases:
1745     * D1. offs == start: start is in data
1746     * D2. offs > start: start is in a hole, next data at offs
1747     * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1748     *                              or start is beyond EOF
1749     *     If the latter happens, the file has been truncated behind
1750     *     our back since we opened it.  All bets are off then.
1751     *     Treating like a trailing hole is simplest.
1752     * D4. offs < 0, errno != ENXIO: we learned nothing
1753     */
1754    offs = lseek(s->fd, start, SEEK_DATA);
1755    if (offs < 0) {
1756        return -errno;          /* D3 or D4 */
1757    }
1758    assert(offs >= start);
1759
1760    if (offs > start) {
1761        /* D2: in hole, next data at offs */
1762        *hole = start;
1763        *data = offs;
1764        return 0;
1765    }
1766
1767    /* D1: in data, end not yet known */
1768
1769    /*
1770     * SEEK_HOLE cases:
1771     * H1. offs == start: start is in a hole
1772     *     If this happens here, a hole has been dug behind our back
1773     *     since the previous lseek().
1774     * H2. offs > start: either start is in data, next hole at offs,
1775     *                   or start is in trailing hole, EOF at offs
1776     *     Linux treats trailing holes like any other hole: offs ==
1777     *     start.  Solaris seeks to EOF instead: offs > start (blech).
1778     *     If that happens here, a hole has been dug behind our back
1779     *     since the previous lseek().
1780     * H3. offs < 0, errno = ENXIO: start is beyond EOF
1781     *     If this happens, the file has been truncated behind our
1782     *     back since we opened it.  Treat it like a trailing hole.
1783     * H4. offs < 0, errno != ENXIO: we learned nothing
1784     *     Pretend we know nothing at all, i.e. "forget" about D1.
1785     */
1786    offs = lseek(s->fd, start, SEEK_HOLE);
1787    if (offs < 0) {
1788        return -errno;          /* D1 and (H3 or H4) */
1789    }
1790    assert(offs >= start);
1791
1792    if (offs > start) {
1793        /*
1794         * D1 and H2: either in data, next hole at offs, or it was in
1795         * data but is now in a trailing hole.  In the latter case,
1796         * all bets are off.  Treating it as if it there was data all
1797         * the way to EOF is safe, so simply do that.
1798         */
1799        *data = start;
1800        *hole = offs;
1801        return 0;
1802    }
1803
1804    /* D1 and H1 */
1805    return -EBUSY;
1806#else
1807    return -ENOTSUP;
1808#endif
1809}
1810
1811/*
1812 * Returns the allocation status of the specified sectors.
1813 *
1814 * If 'sector_num' is beyond the end of the disk image the return value is 0
1815 * and 'pnum' is set to 0.
1816 *
1817 * 'pnum' is set to the number of sectors (including and immediately following
1818 * the specified sector) that are known to be in the same
1819 * allocated/unallocated state.
1820 *
1821 * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
1822 * beyond the end of the disk image it will be clamped.
1823 */
1824static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,
1825                                                    int64_t sector_num,
1826                                                    int nb_sectors, int *pnum)
1827{
1828    off_t start, data = 0, hole = 0;
1829    int64_t total_size;
1830    int ret;
1831
1832    ret = fd_open(bs);
1833    if (ret < 0) {
1834        return ret;
1835    }
1836
1837    start = sector_num * BDRV_SECTOR_SIZE;
1838    total_size = bdrv_getlength(bs);
1839    if (total_size < 0) {
1840        return total_size;
1841    } else if (start >= total_size) {
1842        *pnum = 0;
1843        return 0;
1844    } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {
1845        nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);
1846    }
1847
1848    ret = find_allocation(bs, start, &data, &hole);
1849    if (ret == -ENXIO) {
1850        /* Trailing hole */
1851        *pnum = nb_sectors;
1852        ret = BDRV_BLOCK_ZERO;
1853    } else if (ret < 0) {
1854        /* No info available, so pretend there are no holes */
1855        *pnum = nb_sectors;
1856        ret = BDRV_BLOCK_DATA;
1857    } else if (data == start) {
1858        /* On a data extent, compute sectors to the end of the extent,
1859         * possibly including a partial sector at EOF. */
1860        *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));
1861        ret = BDRV_BLOCK_DATA;
1862    } else {
1863        /* On a hole, compute sectors to the beginning of the next extent.  */
1864        assert(hole == start);
1865        *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);
1866        ret = BDRV_BLOCK_ZERO;
1867    }
1868    return ret | BDRV_BLOCK_OFFSET_VALID | start;
1869}
1870
1871static coroutine_fn BlockAIOCB *raw_aio_discard(BlockDriverState *bs,
1872    int64_t sector_num, int nb_sectors,
1873    BlockCompletionFunc *cb, void *opaque)
1874{
1875    BDRVRawState *s = bs->opaque;
1876
1877    return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
1878                       cb, opaque, QEMU_AIO_DISCARD);
1879}
1880
1881static int coroutine_fn raw_co_write_zeroes(
1882    BlockDriverState *bs, int64_t sector_num,
1883    int nb_sectors, BdrvRequestFlags flags)
1884{
1885    BDRVRawState *s = bs->opaque;
1886
1887    if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1888        return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1889                              QEMU_AIO_WRITE_ZEROES);
1890    } else if (s->discard_zeroes) {
1891        return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
1892                              QEMU_AIO_DISCARD);
1893    }
1894    return -ENOTSUP;
1895}
1896
1897static int raw_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1898{
1899    BDRVRawState *s = bs->opaque;
1900
1901    bdi->unallocated_blocks_are_zero = s->discard_zeroes;
1902    bdi->can_write_zeroes_with_unmap = s->discard_zeroes;
1903    return 0;
1904}
1905
1906static QemuOptsList raw_create_opts = {
1907    .name = "raw-create-opts",
1908    .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
1909    .desc = {
1910        {
1911            .name = BLOCK_OPT_SIZE,
1912            .type = QEMU_OPT_SIZE,
1913            .help = "Virtual disk size"
1914        },
1915        {
1916            .name = BLOCK_OPT_NOCOW,
1917            .type = QEMU_OPT_BOOL,
1918            .help = "Turn off copy-on-write (valid only on btrfs)"
1919        },
1920        {
1921            .name = BLOCK_OPT_PREALLOC,
1922            .type = QEMU_OPT_STRING,
1923            .help = "Preallocation mode (allowed values: off, falloc, full)"
1924        },
1925        { /* end of list */ }
1926    }
1927};
1928
1929BlockDriver bdrv_file = {
1930    .format_name = "file",
1931    .protocol_name = "file",
1932    .instance_size = sizeof(BDRVRawState),
1933    .bdrv_needs_filename = true,
1934    .bdrv_probe = NULL, /* no probe for protocols */
1935    .bdrv_parse_filename = raw_parse_filename,
1936    .bdrv_file_open = raw_open,
1937    .bdrv_reopen_prepare = raw_reopen_prepare,
1938    .bdrv_reopen_commit = raw_reopen_commit,
1939    .bdrv_reopen_abort = raw_reopen_abort,
1940    .bdrv_close = raw_close,
1941    .bdrv_create = raw_create,
1942    .bdrv_has_zero_init = bdrv_has_zero_init_1,
1943    .bdrv_co_get_block_status = raw_co_get_block_status,
1944    .bdrv_co_write_zeroes = raw_co_write_zeroes,
1945
1946    .bdrv_aio_readv = raw_aio_readv,
1947    .bdrv_aio_writev = raw_aio_writev,
1948    .bdrv_aio_flush = raw_aio_flush,
1949    .bdrv_aio_discard = raw_aio_discard,
1950    .bdrv_refresh_limits = raw_refresh_limits,
1951    .bdrv_io_plug = raw_aio_plug,
1952    .bdrv_io_unplug = raw_aio_unplug,
1953    .bdrv_flush_io_queue = raw_aio_flush_io_queue,
1954
1955    .bdrv_truncate = raw_truncate,
1956    .bdrv_getlength = raw_getlength,
1957    .bdrv_get_info = raw_get_info,
1958    .bdrv_get_allocated_file_size
1959                        = raw_get_allocated_file_size,
1960
1961    .bdrv_detach_aio_context = raw_detach_aio_context,
1962    .bdrv_attach_aio_context = raw_attach_aio_context,
1963
1964    .create_opts = &raw_create_opts,
1965};
1966
1967/***********************************************/
1968/* host device */
1969
1970#if defined(__APPLE__) && defined(__MACH__)
1971static kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator );
1972static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
1973                                CFIndex maxPathSize, int flags);
1974kern_return_t FindEjectableCDMedia( io_iterator_t *mediaIterator )
1975{
1976    kern_return_t       kernResult;
1977    mach_port_t     masterPort;
1978    CFMutableDictionaryRef  classesToMatch;
1979
1980    kernResult = IOMasterPort( MACH_PORT_NULL, &masterPort );
1981    if ( KERN_SUCCESS != kernResult ) {
1982        printf( "IOMasterPort returned %d\n", kernResult );
1983    }
1984
1985    classesToMatch = IOServiceMatching( kIOCDMediaClass );
1986    if ( classesToMatch == NULL ) {
1987        printf( "IOServiceMatching returned a NULL dictionary.\n" );
1988    } else {
1989    CFDictionarySetValue( classesToMatch, CFSTR( kIOMediaEjectableKey ), kCFBooleanTrue );
1990    }
1991    kernResult = IOServiceGetMatchingServices( masterPort, classesToMatch, mediaIterator );
1992    if ( KERN_SUCCESS != kernResult )
1993    {
1994        printf( "IOServiceGetMatchingServices returned %d\n", kernResult );
1995    }
1996
1997    return kernResult;
1998}
1999
2000kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
2001                         CFIndex maxPathSize, int flags)
2002{
2003    io_object_t     nextMedia;
2004    kern_return_t   kernResult = KERN_FAILURE;
2005    *bsdPath = '\0';
2006    nextMedia = IOIteratorNext( mediaIterator );
2007    if ( nextMedia )
2008    {
2009        CFTypeRef   bsdPathAsCFString;
2010    bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
2011        if ( bsdPathAsCFString ) {
2012            size_t devPathLength;
2013            strcpy( bsdPath, _PATH_DEV );
2014            if (flags & BDRV_O_NOCACHE) {
2015                strcat(bsdPath, "r");
2016            }
2017            devPathLength = strlen( bsdPath );
2018            if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
2019                kernResult = KERN_SUCCESS;
2020            }
2021            CFRelease( bsdPathAsCFString );
2022        }
2023        IOObjectRelease( nextMedia );
2024    }
2025
2026    return kernResult;
2027}
2028
2029#endif
2030
2031static int hdev_probe_device(const char *filename)
2032{
2033    struct stat st;
2034
2035    /* allow a dedicated CD-ROM driver to match with a higher priority */
2036    if (strstart(filename, "/dev/cdrom", NULL))
2037        return 50;
2038
2039    if (stat(filename, &st) >= 0 &&
2040            (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
2041        return 100;
2042    }
2043
2044    return 0;
2045}
2046
2047static int check_hdev_writable(BDRVRawState *s)
2048{
2049#if defined(BLKROGET)
2050    /* Linux block devices can be configured "read-only" using blockdev(8).
2051     * This is independent of device node permissions and therefore open(2)
2052     * with O_RDWR succeeds.  Actual writes fail with EPERM.
2053     *
2054     * bdrv_open() is supposed to fail if the disk is read-only.  Explicitly
2055     * check for read-only block devices so that Linux block devices behave
2056     * properly.
2057     */
2058    struct stat st;
2059    int readonly = 0;
2060
2061    if (fstat(s->fd, &st)) {
2062        return -errno;
2063    }
2064
2065    if (!S_ISBLK(st.st_mode)) {
2066        return 0;
2067    }
2068
2069    if (ioctl(s->fd, BLKROGET, &readonly) < 0) {
2070        return -errno;
2071    }
2072
2073    if (readonly) {
2074        return -EACCES;
2075    }
2076#endif /* defined(BLKROGET) */
2077    return 0;
2078}
2079
2080static void hdev_parse_filename(const char *filename, QDict *options,
2081                                Error **errp)
2082{
2083    /* The prefix is optional, just as for "file". */
2084    strstart(filename, "host_device:", &filename);
2085
2086    qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2087}
2088
2089static bool hdev_is_sg(BlockDriverState *bs)
2090{
2091
2092#if defined(__linux__)
2093
2094    struct stat st;
2095    struct sg_scsi_id scsiid;
2096    int sg_version;
2097
2098    if (stat(bs->filename, &st) >= 0 && S_ISCHR(st.st_mode) &&
2099        !bdrv_ioctl(bs, SG_GET_VERSION_NUM, &sg_version) &&
2100        !bdrv_ioctl(bs, SG_GET_SCSI_ID, &scsiid)) {
2101        DPRINTF("SG device found: type=%d, version=%d\n",
2102            scsiid.scsi_type, sg_version);
2103        return true;
2104    }
2105
2106#endif
2107
2108    return false;
2109}
2110
2111static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
2112                     Error **errp)
2113{
2114    BDRVRawState *s = bs->opaque;
2115    Error *local_err = NULL;
2116    int ret;
2117
2118#if defined(__APPLE__) && defined(__MACH__)
2119    const char *filename = qdict_get_str(options, "filename");
2120
2121    if (strstart(filename, "/dev/cdrom", NULL)) {
2122        kern_return_t kernResult;
2123        io_iterator_t mediaIterator;
2124        char bsdPath[ MAXPATHLEN ];
2125        int fd;
2126
2127        kernResult = FindEjectableCDMedia( &mediaIterator );
2128        kernResult = GetBSDPath(mediaIterator, bsdPath, sizeof(bsdPath),
2129                                flags);
2130        if ( bsdPath[ 0 ] != '\0' ) {
2131            strcat(bsdPath,"s0");
2132            /* some CDs don't have a partition 0 */
2133            fd = qemu_open(bsdPath, O_RDONLY | O_BINARY | O_LARGEFILE);
2134            if (fd < 0) {
2135                bsdPath[strlen(bsdPath)-1] = '1';
2136            } else {
2137                qemu_close(fd);
2138            }
2139            filename = bsdPath;
2140            qdict_put(options, "filename", qstring_from_str(filename));
2141        }
2142
2143        if ( mediaIterator )
2144            IOObjectRelease( mediaIterator );
2145    }
2146#endif
2147
2148    s->type = FTYPE_FILE;
2149
2150    ret = raw_open_common(bs, options, flags, 0, &local_err);
2151    if (ret < 0) {
2152        if (local_err) {
2153            error_propagate(errp, local_err);
2154        }
2155        return ret;
2156    }
2157
2158    /* Since this does ioctl the device must be already opened */
2159    bs->sg = hdev_is_sg(bs);
2160
2161    if (flags & BDRV_O_RDWR) {
2162        ret = check_hdev_writable(s);
2163        if (ret < 0) {
2164            raw_close(bs);
2165            error_setg_errno(errp, -ret, "The device is not writable");
2166            return ret;
2167        }
2168    }
2169
2170    return ret;
2171}
2172
2173#if defined(__linux__)
2174
2175static BlockAIOCB *hdev_aio_ioctl(BlockDriverState *bs,
2176        unsigned long int req, void *buf,
2177        BlockCompletionFunc *cb, void *opaque)
2178{
2179    BDRVRawState *s = bs->opaque;
2180    RawPosixAIOData *acb;
2181    ThreadPool *pool;
2182
2183    if (fd_open(bs) < 0)
2184        return NULL;
2185
2186    acb = g_new(RawPosixAIOData, 1);
2187    acb->bs = bs;
2188    acb->aio_type = QEMU_AIO_IOCTL;
2189    acb->aio_fildes = s->fd;
2190    acb->aio_offset = 0;
2191    acb->aio_ioctl_buf = buf;
2192    acb->aio_ioctl_cmd = req;
2193    pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
2194    return thread_pool_submit_aio(pool, aio_worker, acb, cb, opaque);
2195}
2196#endif /* linux */
2197
2198static int fd_open(BlockDriverState *bs)
2199{
2200    BDRVRawState *s = bs->opaque;
2201
2202    /* this is just to ensure s->fd is sane (its called by io ops) */
2203    if (s->fd >= 0)
2204        return 0;
2205    return -EIO;
2206}
2207
2208static coroutine_fn BlockAIOCB *hdev_aio_discard(BlockDriverState *bs,
2209    int64_t sector_num, int nb_sectors,
2210    BlockCompletionFunc *cb, void *opaque)
2211{
2212    BDRVRawState *s = bs->opaque;
2213
2214    if (fd_open(bs) < 0) {
2215        return NULL;
2216    }
2217    return paio_submit(bs, s->fd, sector_num, NULL, nb_sectors,
2218                       cb, opaque, QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2219}
2220
2221static coroutine_fn int hdev_co_write_zeroes(BlockDriverState *bs,
2222    int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2223{
2224    BDRVRawState *s = bs->opaque;
2225    int rc;
2226
2227    rc = fd_open(bs);
2228    if (rc < 0) {
2229        return rc;
2230    }
2231    if (!(flags & BDRV_REQ_MAY_UNMAP)) {
2232        return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2233                              QEMU_AIO_WRITE_ZEROES|QEMU_AIO_BLKDEV);
2234    } else if (s->discard_zeroes) {
2235        return paio_submit_co(bs, s->fd, sector_num, NULL, nb_sectors,
2236                              QEMU_AIO_DISCARD|QEMU_AIO_BLKDEV);
2237    }
2238    return -ENOTSUP;
2239}
2240
2241static int hdev_create(const char *filename, QemuOpts *opts,
2242                       Error **errp)
2243{
2244    int fd;
2245    int ret = 0;
2246    struct stat stat_buf;
2247    int64_t total_size = 0;
2248    bool has_prefix;
2249
2250    /* This function is used by both protocol block drivers and therefore either
2251     * of these prefixes may be given.
2252     * The return value has to be stored somewhere, otherwise this is an error
2253     * due to -Werror=unused-value. */
2254    has_prefix =
2255        strstart(filename, "host_device:", &filename) ||
2256        strstart(filename, "host_cdrom:" , &filename);
2257
2258    (void)has_prefix;
2259
2260    ret = raw_normalize_devicepath(&filename);
2261    if (ret < 0) {
2262        error_setg_errno(errp, -ret, "Could not normalize device path");
2263        return ret;
2264    }
2265
2266    /* Read out options */
2267    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2268                          BDRV_SECTOR_SIZE);
2269
2270    fd = qemu_open(filename, O_WRONLY | O_BINARY);
2271    if (fd < 0) {
2272        ret = -errno;
2273        error_setg_errno(errp, -ret, "Could not open device");
2274        return ret;
2275    }
2276
2277    if (fstat(fd, &stat_buf) < 0) {
2278        ret = -errno;
2279        error_setg_errno(errp, -ret, "Could not stat device");
2280    } else if (!S_ISBLK(stat_buf.st_mode) && !S_ISCHR(stat_buf.st_mode)) {
2281        error_setg(errp,
2282                   "The given file is neither a block nor a character device");
2283        ret = -ENODEV;
2284    } else if (lseek(fd, 0, SEEK_END) < total_size) {
2285        error_setg(errp, "Device is too small");
2286        ret = -ENOSPC;
2287    }
2288
2289    qemu_close(fd);
2290    return ret;
2291}
2292
2293static BlockDriver bdrv_host_device = {
2294    .format_name        = "host_device",
2295    .protocol_name        = "host_device",
2296    .instance_size      = sizeof(BDRVRawState),
2297    .bdrv_needs_filename = true,
2298    .bdrv_probe_device  = hdev_probe_device,
2299    .bdrv_parse_filename = hdev_parse_filename,
2300    .bdrv_file_open     = hdev_open,
2301    .bdrv_close         = raw_close,
2302    .bdrv_reopen_prepare = raw_reopen_prepare,
2303    .bdrv_reopen_commit  = raw_reopen_commit,
2304    .bdrv_reopen_abort   = raw_reopen_abort,
2305    .bdrv_create         = hdev_create,
2306    .create_opts         = &raw_create_opts,
2307    .bdrv_co_write_zeroes = hdev_co_write_zeroes,
2308
2309    .bdrv_aio_readv     = raw_aio_readv,
2310    .bdrv_aio_writev    = raw_aio_writev,
2311    .bdrv_aio_flush     = raw_aio_flush,
2312    .bdrv_aio_discard   = hdev_aio_discard,
2313    .bdrv_refresh_limits = raw_refresh_limits,
2314    .bdrv_io_plug = raw_aio_plug,
2315    .bdrv_io_unplug = raw_aio_unplug,
2316    .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2317
2318    .bdrv_truncate      = raw_truncate,
2319    .bdrv_getlength     = raw_getlength,
2320    .bdrv_get_info = raw_get_info,
2321    .bdrv_get_allocated_file_size
2322                        = raw_get_allocated_file_size,
2323    .bdrv_probe_blocksizes = hdev_probe_blocksizes,
2324    .bdrv_probe_geometry = hdev_probe_geometry,
2325
2326    .bdrv_detach_aio_context = raw_detach_aio_context,
2327    .bdrv_attach_aio_context = raw_attach_aio_context,
2328
2329    /* generic scsi device */
2330#ifdef __linux__
2331    .bdrv_aio_ioctl     = hdev_aio_ioctl,
2332#endif
2333};
2334
2335#if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2336static void cdrom_parse_filename(const char *filename, QDict *options,
2337                                 Error **errp)
2338{
2339    /* The prefix is optional, just as for "file". */
2340    strstart(filename, "host_cdrom:", &filename);
2341
2342    qdict_put_obj(options, "filename", QOBJECT(qstring_from_str(filename)));
2343}
2344#endif
2345
2346#ifdef __linux__
2347static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2348                      Error **errp)
2349{
2350    BDRVRawState *s = bs->opaque;
2351    Error *local_err = NULL;
2352    int ret;
2353
2354    s->type = FTYPE_CD;
2355
2356    /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2357    ret = raw_open_common(bs, options, flags, O_NONBLOCK, &local_err);
2358    if (local_err) {
2359        error_propagate(errp, local_err);
2360    }
2361    return ret;
2362}
2363
2364static int cdrom_probe_device(const char *filename)
2365{
2366    int fd, ret;
2367    int prio = 0;
2368    struct stat st;
2369
2370    fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);
2371    if (fd < 0) {
2372        goto out;
2373    }
2374    ret = fstat(fd, &st);
2375    if (ret == -1 || !S_ISBLK(st.st_mode)) {
2376        goto outc;
2377    }
2378
2379    /* Attempt to detect via a CDROM specific ioctl */
2380    ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2381    if (ret >= 0)
2382        prio = 100;
2383
2384outc:
2385    qemu_close(fd);
2386out:
2387    return prio;
2388}
2389
2390static bool cdrom_is_inserted(BlockDriverState *bs)
2391{
2392    BDRVRawState *s = bs->opaque;
2393    int ret;
2394
2395    ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
2396    return ret == CDS_DISC_OK;
2397}
2398
2399static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2400{
2401    BDRVRawState *s = bs->opaque;
2402
2403    if (eject_flag) {
2404        if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
2405            perror("CDROMEJECT");
2406    } else {
2407        if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
2408            perror("CDROMEJECT");
2409    }
2410}
2411
2412static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2413{
2414    BDRVRawState *s = bs->opaque;
2415
2416    if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
2417        /*
2418         * Note: an error can happen if the distribution automatically
2419         * mounts the CD-ROM
2420         */
2421        /* perror("CDROM_LOCKDOOR"); */
2422    }
2423}
2424
2425static BlockDriver bdrv_host_cdrom = {
2426    .format_name        = "host_cdrom",
2427    .protocol_name      = "host_cdrom",
2428    .instance_size      = sizeof(BDRVRawState),
2429    .bdrv_needs_filename = true,
2430    .bdrv_probe_device  = cdrom_probe_device,
2431    .bdrv_parse_filename = cdrom_parse_filename,
2432    .bdrv_file_open     = cdrom_open,
2433    .bdrv_close         = raw_close,
2434    .bdrv_reopen_prepare = raw_reopen_prepare,
2435    .bdrv_reopen_commit  = raw_reopen_commit,
2436    .bdrv_reopen_abort   = raw_reopen_abort,
2437    .bdrv_create         = hdev_create,
2438    .create_opts         = &raw_create_opts,
2439
2440    .bdrv_aio_readv     = raw_aio_readv,
2441    .bdrv_aio_writev    = raw_aio_writev,
2442    .bdrv_aio_flush     = raw_aio_flush,
2443    .bdrv_refresh_limits = raw_refresh_limits,
2444    .bdrv_io_plug = raw_aio_plug,
2445    .bdrv_io_unplug = raw_aio_unplug,
2446    .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2447
2448    .bdrv_truncate      = raw_truncate,
2449    .bdrv_getlength      = raw_getlength,
2450    .has_variable_length = true,
2451    .bdrv_get_allocated_file_size
2452                        = raw_get_allocated_file_size,
2453
2454    .bdrv_detach_aio_context = raw_detach_aio_context,
2455    .bdrv_attach_aio_context = raw_attach_aio_context,
2456
2457    /* removable device support */
2458    .bdrv_is_inserted   = cdrom_is_inserted,
2459    .bdrv_eject         = cdrom_eject,
2460    .bdrv_lock_medium   = cdrom_lock_medium,
2461
2462    /* generic scsi device */
2463    .bdrv_aio_ioctl     = hdev_aio_ioctl,
2464};
2465#endif /* __linux__ */
2466
2467#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2468static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
2469                      Error **errp)
2470{
2471    BDRVRawState *s = bs->opaque;
2472    Error *local_err = NULL;
2473    int ret;
2474
2475    s->type = FTYPE_CD;
2476
2477    ret = raw_open_common(bs, options, flags, 0, &local_err);
2478    if (ret) {
2479        if (local_err) {
2480            error_propagate(errp, local_err);
2481        }
2482        return ret;
2483    }
2484
2485    /* make sure the door isn't locked at this time */
2486    ioctl(s->fd, CDIOCALLOW);
2487    return 0;
2488}
2489
2490static int cdrom_probe_device(const char *filename)
2491{
2492    if (strstart(filename, "/dev/cd", NULL) ||
2493            strstart(filename, "/dev/acd", NULL))
2494        return 100;
2495    return 0;
2496}
2497
2498static int cdrom_reopen(BlockDriverState *bs)
2499{
2500    BDRVRawState *s = bs->opaque;
2501    int fd;
2502
2503    /*
2504     * Force reread of possibly changed/newly loaded disc,
2505     * FreeBSD seems to not notice sometimes...
2506     */
2507    if (s->fd >= 0)
2508        qemu_close(s->fd);
2509    fd = qemu_open(bs->filename, s->open_flags, 0644);
2510    if (fd < 0) {
2511        s->fd = -1;
2512        return -EIO;
2513    }
2514    s->fd = fd;
2515
2516    /* make sure the door isn't locked at this time */
2517    ioctl(s->fd, CDIOCALLOW);
2518    return 0;
2519}
2520
2521static bool cdrom_is_inserted(BlockDriverState *bs)
2522{
2523    return raw_getlength(bs) > 0;
2524}
2525
2526static void cdrom_eject(BlockDriverState *bs, bool eject_flag)
2527{
2528    BDRVRawState *s = bs->opaque;
2529
2530    if (s->fd < 0)
2531        return;
2532
2533    (void) ioctl(s->fd, CDIOCALLOW);
2534
2535    if (eject_flag) {
2536        if (ioctl(s->fd, CDIOCEJECT) < 0)
2537            perror("CDIOCEJECT");
2538    } else {
2539        if (ioctl(s->fd, CDIOCCLOSE) < 0)
2540            perror("CDIOCCLOSE");
2541    }
2542
2543    cdrom_reopen(bs);
2544}
2545
2546static void cdrom_lock_medium(BlockDriverState *bs, bool locked)
2547{
2548    BDRVRawState *s = bs->opaque;
2549
2550    if (s->fd < 0)
2551        return;
2552    if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
2553        /*
2554         * Note: an error can happen if the distribution automatically
2555         * mounts the CD-ROM
2556         */
2557        /* perror("CDROM_LOCKDOOR"); */
2558    }
2559}
2560
2561static BlockDriver bdrv_host_cdrom = {
2562    .format_name        = "host_cdrom",
2563    .protocol_name      = "host_cdrom",
2564    .instance_size      = sizeof(BDRVRawState),
2565    .bdrv_needs_filename = true,
2566    .bdrv_probe_device  = cdrom_probe_device,
2567    .bdrv_parse_filename = cdrom_parse_filename,
2568    .bdrv_file_open     = cdrom_open,
2569    .bdrv_close         = raw_close,
2570    .bdrv_reopen_prepare = raw_reopen_prepare,
2571    .bdrv_reopen_commit  = raw_reopen_commit,
2572    .bdrv_reopen_abort   = raw_reopen_abort,
2573    .bdrv_create        = hdev_create,
2574    .create_opts        = &raw_create_opts,
2575
2576    .bdrv_aio_readv     = raw_aio_readv,
2577    .bdrv_aio_writev    = raw_aio_writev,
2578    .bdrv_aio_flush     = raw_aio_flush,
2579    .bdrv_refresh_limits = raw_refresh_limits,
2580    .bdrv_io_plug = raw_aio_plug,
2581    .bdrv_io_unplug = raw_aio_unplug,
2582    .bdrv_flush_io_queue = raw_aio_flush_io_queue,
2583
2584    .bdrv_truncate      = raw_truncate,
2585    .bdrv_getlength      = raw_getlength,
2586    .has_variable_length = true,
2587    .bdrv_get_allocated_file_size
2588                        = raw_get_allocated_file_size,
2589
2590    .bdrv_detach_aio_context = raw_detach_aio_context,
2591    .bdrv_attach_aio_context = raw_attach_aio_context,
2592
2593    /* removable device support */
2594    .bdrv_is_inserted   = cdrom_is_inserted,
2595    .bdrv_eject         = cdrom_eject,
2596    .bdrv_lock_medium   = cdrom_lock_medium,
2597};
2598#endif /* __FreeBSD__ */
2599
2600static void bdrv_file_init(void)
2601{
2602    /*
2603     * Register all the drivers.  Note that order is important, the driver
2604     * registered last will get probed first.
2605     */
2606    bdrv_register(&bdrv_file);
2607    bdrv_register(&bdrv_host_device);
2608#ifdef __linux__
2609    bdrv_register(&bdrv_host_cdrom);
2610#endif
2611#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2612    bdrv_register(&bdrv_host_cdrom);
2613#endif
2614}
2615
2616block_init(bdrv_file_init);
2617