blkdebug.c 22.4 KB
Newer Older
K
Kevin Wolf 已提交
1 2 3
/*
 * Block protocol for I/O error injection
 *
4
 * Copyright (C) 2016-2017 Red Hat, Inc.
K
Kevin Wolf 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * Copyright (c) 2010 Kevin Wolf <kwolf@redhat.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

P
Peter Maydell 已提交
26
#include "qemu/osdep.h"
27
#include "qapi/error.h"
28
#include "qemu/cutils.h"
29
#include "qemu/config-file.h"
30
#include "block/block_int.h"
31
#include "qemu/module.h"
32 33 34 35
#include "qapi/qmp/qbool.h"
#include "qapi/qmp/qdict.h"
#include "qapi/qmp/qint.h"
#include "qapi/qmp/qstring.h"
36
#include "sysemu/qtest.h"
K
Kevin Wolf 已提交
37 38

typedef struct BDRVBlkdebugState {
39
    int state;
40
    int new_state;
41
    int align;
42

43 44 45
    /* For blkdebug_refresh_filename() */
    char *config_file;

46
    QLIST_HEAD(, BlkdebugRule) rules[BLKDBG__MAX];
47
    QSIMPLEQ_HEAD(, BlkdebugRule) active_rules;
48
    QLIST_HEAD(, BlkdebugSuspendedReq) suspended_reqs;
K
Kevin Wolf 已提交
49 50
} BDRVBlkdebugState;

K
Kevin Wolf 已提交
51
typedef struct BlkdebugAIOCB {
52
    BlockAIOCB common;
K
Kevin Wolf 已提交
53 54 55
    int ret;
} BlkdebugAIOCB;

56 57 58 59 60 61
typedef struct BlkdebugSuspendedReq {
    Coroutine *co;
    char *tag;
    QLIST_ENTRY(BlkdebugSuspendedReq) next;
} BlkdebugSuspendedReq;

K
Kevin Wolf 已提交
62 63 64
enum {
    ACTION_INJECT_ERROR,
    ACTION_SET_STATE,
65
    ACTION_SUSPEND,
K
Kevin Wolf 已提交
66 67 68
};

typedef struct BlkdebugRule {
69
    BlkdebugEvent event;
K
Kevin Wolf 已提交
70 71 72 73 74 75 76
    int action;
    int state;
    union {
        struct {
            int error;
            int immediately;
            int once;
77
            int64_t offset;
K
Kevin Wolf 已提交
78 79 80 81
        } inject;
        struct {
            int new_state;
        } set_state;
82 83 84
        struct {
            char *tag;
        } suspend;
K
Kevin Wolf 已提交
85 86
    } options;
    QLIST_ENTRY(BlkdebugRule) next;
87
    QSIMPLEQ_ENTRY(BlkdebugRule) active_next;
K
Kevin Wolf 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
} BlkdebugRule;

static QemuOptsList inject_error_opts = {
    .name = "inject-error",
    .head = QTAILQ_HEAD_INITIALIZER(inject_error_opts.head),
    .desc = {
        {
            .name = "event",
            .type = QEMU_OPT_STRING,
        },
        {
            .name = "state",
            .type = QEMU_OPT_NUMBER,
        },
        {
            .name = "errno",
            .type = QEMU_OPT_NUMBER,
        },
106 107 108 109
        {
            .name = "sector",
            .type = QEMU_OPT_NUMBER,
        },
K
Kevin Wolf 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123
        {
            .name = "once",
            .type = QEMU_OPT_BOOL,
        },
        {
            .name = "immediately",
            .type = QEMU_OPT_BOOL,
        },
        { /* end of list */ }
    },
};

static QemuOptsList set_state_opts = {
    .name = "set-state",
124
    .head = QTAILQ_HEAD_INITIALIZER(set_state_opts.head),
K
Kevin Wolf 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    .desc = {
        {
            .name = "event",
            .type = QEMU_OPT_STRING,
        },
        {
            .name = "state",
            .type = QEMU_OPT_NUMBER,
        },
        {
            .name = "new_state",
            .type = QEMU_OPT_NUMBER,
        },
        { /* end of list */ }
    },
};

static QemuOptsList *config_groups[] = {
    &inject_error_opts,
    &set_state_opts,
    NULL
};

148
static int get_event_by_name(const char *name, BlkdebugEvent *event)
K
Kevin Wolf 已提交
149 150 151
{
    int i;

152
    for (i = 0; i < BLKDBG__MAX; i++) {
153
        if (!strcmp(BlkdebugEvent_lookup[i], name)) {
K
Kevin Wolf 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166
            *event = i;
            return 0;
        }
    }

    return -1;
}

struct add_rule_data {
    BDRVBlkdebugState *s;
    int action;
};

167
static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
K
Kevin Wolf 已提交
168 169 170 171
{
    struct add_rule_data *d = opaque;
    BDRVBlkdebugState *s = d->s;
    const char* event_name;
172
    BlkdebugEvent event;
K
Kevin Wolf 已提交
173
    struct BlkdebugRule *rule;
174
    int64_t sector;
K
Kevin Wolf 已提交
175 176 177

    /* Find the right event for the rule */
    event_name = qemu_opt_get(opts, "event");
178
    if (!event_name) {
179
        error_setg(errp, "Missing event name for rule");
180 181
        return -1;
    } else if (get_event_by_name(event_name, &event) < 0) {
182
        error_setg(errp, "Invalid event name \"%s\"", event_name);
K
Kevin Wolf 已提交
183 184 185 186
        return -1;
    }

    /* Set attributes common for all actions */
187
    rule = g_malloc0(sizeof(*rule));
K
Kevin Wolf 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200
    *rule = (struct BlkdebugRule) {
        .event  = event,
        .action = d->action,
        .state  = qemu_opt_get_number(opts, "state", 0),
    };

    /* Parse action-specific options */
    switch (d->action) {
    case ACTION_INJECT_ERROR:
        rule->options.inject.error = qemu_opt_get_number(opts, "errno", EIO);
        rule->options.inject.once  = qemu_opt_get_bool(opts, "once", 0);
        rule->options.inject.immediately =
            qemu_opt_get_bool(opts, "immediately", 0);
201 202 203
        sector = qemu_opt_get_number(opts, "sector", -1);
        rule->options.inject.offset =
            sector == -1 ? -1 : sector * BDRV_SECTOR_SIZE;
K
Kevin Wolf 已提交
204 205 206 207 208 209
        break;

    case ACTION_SET_STATE:
        rule->options.set_state.new_state =
            qemu_opt_get_number(opts, "new_state", 0);
        break;
210 211 212 213 214

    case ACTION_SUSPEND:
        rule->options.suspend.tag =
            g_strdup(qemu_opt_get(opts, "tag"));
        break;
K
Kevin Wolf 已提交
215 216 217 218 219 220 221 222
    };

    /* Add the rule */
    QLIST_INSERT_HEAD(&s->rules[event], rule, next);

    return 0;
}

K
Kevin Wolf 已提交
223 224 225 226 227 228
static void remove_rule(BlkdebugRule *rule)
{
    switch (rule->action) {
    case ACTION_INJECT_ERROR:
    case ACTION_SET_STATE:
        break;
229 230 231
    case ACTION_SUSPEND:
        g_free(rule->options.suspend.tag);
        break;
K
Kevin Wolf 已提交
232 233 234 235 236 237
    }

    QLIST_REMOVE(rule, next);
    g_free(rule);
}

238 239
static int read_config(BDRVBlkdebugState *s, const char *filename,
                       QDict *options, Error **errp)
K
Kevin Wolf 已提交
240
{
M
Max Reitz 已提交
241
    FILE *f = NULL;
K
Kevin Wolf 已提交
242 243
    int ret;
    struct add_rule_data d;
244
    Error *local_err = NULL;
K
Kevin Wolf 已提交
245

M
Max Reitz 已提交
246 247 248 249 250 251
    if (filename) {
        f = fopen(filename, "r");
        if (f == NULL) {
            error_setg_errno(errp, errno, "Could not read blkdebug config file");
            return -errno;
        }
K
Kevin Wolf 已提交
252

M
Max Reitz 已提交
253 254 255 256 257 258
        ret = qemu_config_parse(f, config_groups, filename);
        if (ret < 0) {
            error_setg(errp, "Could not parse blkdebug config file");
            ret = -EINVAL;
            goto fail;
        }
K
Kevin Wolf 已提交
259 260
    }

261
    qemu_config_parse_qdict(options, config_groups, &local_err);
262
    if (local_err) {
263 264 265 266 267
        error_propagate(errp, local_err);
        ret = -EINVAL;
        goto fail;
    }

K
Kevin Wolf 已提交
268 269
    d.s = s;
    d.action = ACTION_INJECT_ERROR;
270
    qemu_opts_foreach(&inject_error_opts, add_rule, &d, &local_err);
271 272 273 274 275
    if (local_err) {
        error_propagate(errp, local_err);
        ret = -EINVAL;
        goto fail;
    }
K
Kevin Wolf 已提交
276 277

    d.action = ACTION_SET_STATE;
278
    qemu_opts_foreach(&set_state_opts, add_rule, &d, &local_err);
279 280 281 282 283
    if (local_err) {
        error_propagate(errp, local_err);
        ret = -EINVAL;
        goto fail;
    }
K
Kevin Wolf 已提交
284 285 286

    ret = 0;
fail:
287 288
    qemu_opts_reset(&inject_error_opts);
    qemu_opts_reset(&set_state_opts);
M
Max Reitz 已提交
289 290 291
    if (f) {
        fclose(f);
    }
K
Kevin Wolf 已提交
292 293 294 295
    return ret;
}

/* Valid blkdebug filenames look like blkdebug:path/to/config:path/to/image */
296 297
static void blkdebug_parse_filename(const char *filename, QDict *options,
                                    Error **errp)
K
Kevin Wolf 已提交
298
{
299
    const char *c;
K
Kevin Wolf 已提交
300

K
Kevin Wolf 已提交
301
    /* Parse the blkdebug: prefix */
302
    if (!strstart(filename, "blkdebug:", &filename)) {
303 304
        /* There was no prefix; therefore, all options have to be already
           present in the QDict (except for the filename) */
305
        qdict_put_str(options, "x-image", filename);
306
        return;
K
Kevin Wolf 已提交
307 308
    }

309
    /* Parse config file path */
K
Kevin Wolf 已提交
310 311
    c = strchr(filename, ':');
    if (c == NULL) {
312 313
        error_setg(errp, "blkdebug requires both config file and image path");
        return;
K
Kevin Wolf 已提交
314 315
    }

316 317 318 319
    if (c != filename) {
        QString *config_path;
        config_path = qstring_from_substr(filename, 0, c - filename - 1);
        qdict_put(options, "config", config_path);
K
Kevin Wolf 已提交
320
    }
321 322

    /* TODO Allow multi-level nesting and set file.filename here */
K
Kevin Wolf 已提交
323
    filename = c + 1;
324
    qdict_put_str(options, "x-image", filename);
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
}

static QemuOptsList runtime_opts = {
    .name = "blkdebug",
    .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
    .desc = {
        {
            .name = "config",
            .type = QEMU_OPT_STRING,
            .help = "Path to the configuration file",
        },
        {
            .name = "x-image",
            .type = QEMU_OPT_STRING,
            .help = "[internal use only, will be removed]",
        },
341 342 343 344 345
        {
            .name = "align",
            .type = QEMU_OPT_SIZE,
            .help = "Required alignment in bytes",
        },
346 347 348 349
        { /* end of list */ }
    },
};

M
Max Reitz 已提交
350 351
static int blkdebug_open(BlockDriverState *bs, QDict *options, int flags,
                         Error **errp)
352 353 354 355
{
    BDRVBlkdebugState *s = bs->opaque;
    QemuOpts *opts;
    Error *local_err = NULL;
356
    uint64_t align;
357 358
    int ret;

359
    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
360
    qemu_opts_absorb_qdict(opts, options, &local_err);
361
    if (local_err) {
M
Max Reitz 已提交
362
        error_propagate(errp, local_err);
363
        ret = -EINVAL;
364
        goto out;
365 366
    }

367
    /* Read rules from config file or command line options */
368 369
    s->config_file = g_strdup(qemu_opt_get(opts, "config"));
    ret = read_config(s, s->config_file, options, errp);
M
Max Reitz 已提交
370
    if (ret) {
371
        goto out;
372
    }
K
Kevin Wolf 已提交
373

K
Kevin Wolf 已提交
374
    /* Set initial state */
375
    s->state = 1;
K
Kevin Wolf 已提交
376

377
    /* Open the image file */
K
Kevin Wolf 已提交
378 379 380 381
    bs->file = bdrv_open_child(qemu_opt_get(opts, "x-image"), options, "image",
                               bs, &child_file, false, &local_err);
    if (local_err) {
        ret = -EINVAL;
M
Max Reitz 已提交
382
        error_propagate(errp, local_err);
383
        goto out;
K
Kevin Wolf 已提交
384 385
    }

386 387 388 389 390
    bs->supported_write_flags = BDRV_REQ_FUA &
        bs->file->bs->supported_write_flags;
    bs->supported_zero_flags = (BDRV_REQ_FUA | BDRV_REQ_MAY_UNMAP) &
        bs->file->bs->supported_zero_flags;

391
    /* Set request alignment */
392 393 394 395
    align = qemu_opt_get_size(opts, "align", 0);
    if (align < INT_MAX && is_power_of_2(align)) {
        s->align = align;
    } else if (align) {
396 397
        error_setg(errp, "Invalid alignment");
        ret = -EINVAL;
398
        goto out;
399 400
    }

401
    ret = 0;
402 403 404
    goto out;

out:
405 406 407
    if (ret < 0) {
        g_free(s->config_file);
    }
408 409
    qemu_opts_del(opts);
    return ret;
K
Kevin Wolf 已提交
410 411
}

E
Eric Blake 已提交
412
static int rule_check(BlockDriverState *bs, uint64_t offset, uint64_t bytes)
K
Kevin Wolf 已提交
413 414
{
    BDRVBlkdebugState *s = bs->opaque;
E
Eric Blake 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    BlkdebugRule *rule = NULL;
    int error;
    bool immediately;

    QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
        uint64_t inject_offset = rule->options.inject.offset;

        if (inject_offset == -1 ||
            (bytes && inject_offset >= offset &&
             inject_offset < offset + bytes))
        {
            break;
        }
    }

    if (!rule || !rule->options.inject.error) {
        return 0;
    }

    immediately = rule->options.inject.immediately;
    error = rule->options.inject.error;
K
Kevin Wolf 已提交
436

437
    if (rule->options.inject.once) {
J
John Snow 已提交
438 439
        QSIMPLEQ_REMOVE(&s->active_rules, rule, BlkdebugRule, active_next);
        remove_rule(rule);
K
Kevin Wolf 已提交
440 441
    }

442
    if (!immediately) {
443
        aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
444
        qemu_coroutine_yield();
K
Kevin Wolf 已提交
445 446
    }

447
    return -error;
K
Kevin Wolf 已提交
448 449
}

450 451 452
static int coroutine_fn
blkdebug_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
                   QEMUIOVector *qiov, int flags)
K
Kevin Wolf 已提交
453
{
E
Eric Blake 已提交
454
    int err;
455

456 457 458 459 460 461 462
    /* Sanity check block layer guarantees */
    assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));
    assert(QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment));
    if (bs->bl.max_transfer) {
        assert(bytes <= bs->bl.max_transfer);
    }

E
Eric Blake 已提交
463 464 465
    err = rule_check(bs, offset, bytes);
    if (err) {
        return err;
K
Kevin Wolf 已提交
466 467
    }

468
    return bdrv_co_preadv(bs->file, offset, bytes, qiov, flags);
K
Kevin Wolf 已提交
469 470
}

471 472 473
static int coroutine_fn
blkdebug_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
                    QEMUIOVector *qiov, int flags)
K
Kevin Wolf 已提交
474
{
E
Eric Blake 已提交
475
    int err;
476

477 478 479 480 481 482 483
    /* Sanity check block layer guarantees */
    assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));
    assert(QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment));
    if (bs->bl.max_transfer) {
        assert(bytes <= bs->bl.max_transfer);
    }

E
Eric Blake 已提交
484 485 486
    err = rule_check(bs, offset, bytes);
    if (err) {
        return err;
K
Kevin Wolf 已提交
487 488
    }

489
    return bdrv_co_pwritev(bs->file, offset, bytes, qiov, flags);
K
Kevin Wolf 已提交
490 491
}

492
static int blkdebug_co_flush(BlockDriverState *bs)
493
{
E
Eric Blake 已提交
494
    int err = rule_check(bs, 0, 0);
495

E
Eric Blake 已提交
496 497
    if (err) {
        return err;
498 499
    }

500
    return bdrv_co_flush(bs->file->bs);
501 502
}

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
static int coroutine_fn blkdebug_co_pwrite_zeroes(BlockDriverState *bs,
                                                  int64_t offset, int count,
                                                  BdrvRequestFlags flags)
{
    uint32_t align = MAX(bs->bl.request_alignment,
                         bs->bl.pwrite_zeroes_alignment);
    int err;

    /* Only pass through requests that are larger than requested
     * preferred alignment (so that we test the fallback to writes on
     * unaligned portions), and check that the block layer never hands
     * us anything unaligned that crosses an alignment boundary.  */
    if (count < align) {
        assert(QEMU_IS_ALIGNED(offset, align) ||
               QEMU_IS_ALIGNED(offset + count, align) ||
               DIV_ROUND_UP(offset, align) ==
               DIV_ROUND_UP(offset + count, align));
        return -ENOTSUP;
    }
    assert(QEMU_IS_ALIGNED(offset, align));
    assert(QEMU_IS_ALIGNED(count, align));
    if (bs->bl.max_pwrite_zeroes) {
        assert(count <= bs->bl.max_pwrite_zeroes);
    }

    err = rule_check(bs, offset, count);
    if (err) {
        return err;
    }

    return bdrv_co_pwrite_zeroes(bs->file, offset, count, flags);
}

static int coroutine_fn blkdebug_co_pdiscard(BlockDriverState *bs,
                                             int64_t offset, int count)
{
    uint32_t align = bs->bl.pdiscard_alignment;
    int err;

    /* Only pass through requests that are larger than requested
     * minimum alignment, and ensure that unaligned requests do not
     * cross optimum discard boundaries. */
    if (count < bs->bl.request_alignment) {
        assert(QEMU_IS_ALIGNED(offset, align) ||
               QEMU_IS_ALIGNED(offset + count, align) ||
               DIV_ROUND_UP(offset, align) ==
               DIV_ROUND_UP(offset + count, align));
        return -ENOTSUP;
    }
    assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));
    assert(QEMU_IS_ALIGNED(count, bs->bl.request_alignment));
    if (align && count >= align) {
        assert(QEMU_IS_ALIGNED(offset, align));
        assert(QEMU_IS_ALIGNED(count, align));
    }
    if (bs->bl.max_pdiscard) {
        assert(count <= bs->bl.max_pdiscard);
    }

    err = rule_check(bs, offset, count);
    if (err) {
        return err;
    }

    return bdrv_co_pdiscard(bs->file->bs, offset, count);
}
569

K
Kevin Wolf 已提交
570 571 572
static void blkdebug_close(BlockDriverState *bs)
{
    BDRVBlkdebugState *s = bs->opaque;
K
Kevin Wolf 已提交
573 574 575
    BlkdebugRule *rule, *next;
    int i;

576
    for (i = 0; i < BLKDBG__MAX; i++) {
K
Kevin Wolf 已提交
577
        QLIST_FOREACH_SAFE(rule, &s->rules[i], next, next) {
K
Kevin Wolf 已提交
578
            remove_rule(rule);
K
Kevin Wolf 已提交
579 580
        }
    }
581 582

    g_free(s->config_file);
K
Kevin Wolf 已提交
583 584
}

585 586 587 588 589 590 591 592 593 594 595 596 597
static void suspend_request(BlockDriverState *bs, BlkdebugRule *rule)
{
    BDRVBlkdebugState *s = bs->opaque;
    BlkdebugSuspendedReq r;

    r = (BlkdebugSuspendedReq) {
        .co         = qemu_coroutine_self(),
        .tag        = g_strdup(rule->options.suspend.tag),
    };

    remove_rule(rule);
    QLIST_INSERT_HEAD(&s->suspended_reqs, &r, next);

598 599 600
    if (!qtest_enabled()) {
        printf("blkdebug: Suspended request '%s'\n", r.tag);
    }
601
    qemu_coroutine_yield();
602 603 604
    if (!qtest_enabled()) {
        printf("blkdebug: Resuming request '%s'\n", r.tag);
    }
605 606 607 608 609

    QLIST_REMOVE(&r, next);
    g_free(r.tag);
}

610
static bool process_rule(BlockDriverState *bs, struct BlkdebugRule *rule,
611
    bool injected)
K
Kevin Wolf 已提交
612 613 614 615
{
    BDRVBlkdebugState *s = bs->opaque;

    /* Only process rules for the current state */
616
    if (rule->state && rule->state != s->state) {
617
        return injected;
K
Kevin Wolf 已提交
618 619 620 621 622
    }

    /* Take the action */
    switch (rule->action) {
    case ACTION_INJECT_ERROR:
623 624 625 626 627
        if (!injected) {
            QSIMPLEQ_INIT(&s->active_rules);
            injected = true;
        }
        QSIMPLEQ_INSERT_HEAD(&s->active_rules, rule, active_next);
K
Kevin Wolf 已提交
628 629 630
        break;

    case ACTION_SET_STATE:
631
        s->new_state = rule->options.set_state.new_state;
K
Kevin Wolf 已提交
632
        break;
633 634 635 636

    case ACTION_SUSPEND:
        suspend_request(bs, rule);
        break;
K
Kevin Wolf 已提交
637
    }
638
    return injected;
K
Kevin Wolf 已提交
639 640
}

641
static void blkdebug_debug_event(BlockDriverState *bs, BlkdebugEvent event)
K
Kevin Wolf 已提交
642 643
{
    BDRVBlkdebugState *s = bs->opaque;
644
    struct BlkdebugRule *rule, *next;
645
    bool injected;
K
Kevin Wolf 已提交
646

647
    assert((int)event >= 0 && event < BLKDBG__MAX);
K
Kevin Wolf 已提交
648

649
    injected = false;
650
    s->new_state = s->state;
651
    QLIST_FOREACH_SAFE(rule, &s->rules[event], next, next) {
652
        injected = process_rule(bs, rule, injected);
K
Kevin Wolf 已提交
653
    }
654
    s->state = s->new_state;
K
Kevin Wolf 已提交
655 656
}

657 658 659 660 661
static int blkdebug_debug_breakpoint(BlockDriverState *bs, const char *event,
                                     const char *tag)
{
    BDRVBlkdebugState *s = bs->opaque;
    struct BlkdebugRule *rule;
662
    BlkdebugEvent blkdebug_event;
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684

    if (get_event_by_name(event, &blkdebug_event) < 0) {
        return -ENOENT;
    }


    rule = g_malloc(sizeof(*rule));
    *rule = (struct BlkdebugRule) {
        .event  = blkdebug_event,
        .action = ACTION_SUSPEND,
        .state  = 0,
        .options.suspend.tag = g_strdup(tag),
    };

    QLIST_INSERT_HEAD(&s->rules[blkdebug_event], rule, next);

    return 0;
}

static int blkdebug_debug_resume(BlockDriverState *bs, const char *tag)
{
    BDRVBlkdebugState *s = bs->opaque;
685
    BlkdebugSuspendedReq *r, *next;
686

687
    QLIST_FOREACH_SAFE(r, &s->suspended_reqs, next, next) {
688
        if (!strcmp(r->tag, tag)) {
689
            qemu_coroutine_enter(r->co);
690 691 692 693 694 695
            return 0;
        }
    }
    return -ENOENT;
}

F
Fam Zheng 已提交
696 697 698 699
static int blkdebug_debug_remove_breakpoint(BlockDriverState *bs,
                                            const char *tag)
{
    BDRVBlkdebugState *s = bs->opaque;
700
    BlkdebugSuspendedReq *r, *r_next;
F
Fam Zheng 已提交
701 702 703
    BlkdebugRule *rule, *next;
    int i, ret = -ENOENT;

704
    for (i = 0; i < BLKDBG__MAX; i++) {
F
Fam Zheng 已提交
705 706 707 708 709 710 711 712
        QLIST_FOREACH_SAFE(rule, &s->rules[i], next, next) {
            if (rule->action == ACTION_SUSPEND &&
                !strcmp(rule->options.suspend.tag, tag)) {
                remove_rule(rule);
                ret = 0;
            }
        }
    }
713
    QLIST_FOREACH_SAFE(r, &s->suspended_reqs, next, r_next) {
F
Fam Zheng 已提交
714
        if (!strcmp(r->tag, tag)) {
715
            qemu_coroutine_enter(r->co);
F
Fam Zheng 已提交
716 717 718 719 720
            ret = 0;
        }
    }
    return ret;
}
721 722 723 724 725 726 727 728 729 730 731 732 733 734

static bool blkdebug_debug_is_suspended(BlockDriverState *bs, const char *tag)
{
    BDRVBlkdebugState *s = bs->opaque;
    BlkdebugSuspendedReq *r;

    QLIST_FOREACH(r, &s->suspended_reqs, next) {
        if (!strcmp(r->tag, tag)) {
            return true;
        }
    }
    return false;
}

735 736
static int64_t blkdebug_getlength(BlockDriverState *bs)
{
K
Kevin Wolf 已提交
737
    return bdrv_getlength(bs->file->bs);
738 739
}

K
Kevin Wolf 已提交
740 741
static int blkdebug_truncate(BlockDriverState *bs, int64_t offset)
{
742
    return bdrv_truncate(bs->file, offset, NULL);
K
Kevin Wolf 已提交
743 744
}

745
static void blkdebug_refresh_filename(BlockDriverState *bs, QDict *options)
746
{
747
    BDRVBlkdebugState *s = bs->opaque;
748
    QDict *opts;
749 750 751
    const QDictEntry *e;
    bool force_json = false;

752
    for (e = qdict_first(options); e; e = qdict_next(options, e)) {
753
        if (strcmp(qdict_entry_key(e), "config") &&
754
            strcmp(qdict_entry_key(e), "x-image"))
755 756 757 758 759
        {
            force_json = true;
            break;
        }
    }
760

K
Kevin Wolf 已提交
761
    if (force_json && !bs->file->bs->full_open_options) {
762 763 764 765 766
        /* The config file cannot be recreated, so creating a plain filename
         * is impossible */
        return;
    }

K
Kevin Wolf 已提交
767
    if (!force_json && bs->file->bs->exact_filename[0]) {
768
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
769
                 "blkdebug:%s:%s", s->config_file ?: "",
K
Kevin Wolf 已提交
770
                 bs->file->bs->exact_filename);
771 772
    }

773
    opts = qdict_new();
774
    qdict_put_str(opts, "driver", "blkdebug");
775

K
Kevin Wolf 已提交
776
    QINCREF(bs->file->bs->full_open_options);
E
Eric Blake 已提交
777
    qdict_put(opts, "image", bs->file->bs->full_open_options);
778

779 780
    for (e = qdict_first(options); e; e = qdict_next(options, e)) {
        if (strcmp(qdict_entry_key(e), "x-image")) {
781 782
            qobject_incref(qdict_entry_value(e));
            qdict_put_obj(opts, qdict_entry_key(e), qdict_entry_value(e));
783 784 785 786 787 788
        }
    }

    bs->full_open_options = opts;
}

789 790 791 792 793
static void blkdebug_refresh_limits(BlockDriverState *bs, Error **errp)
{
    BDRVBlkdebugState *s = bs->opaque;

    if (s->align) {
794
        bs->bl.request_alignment = s->align;
795 796 797
    }
}

K
Kevin Wolf 已提交
798 799 800 801 802 803
static int blkdebug_reopen_prepare(BDRVReopenState *reopen_state,
                                   BlockReopenQueue *queue, Error **errp)
{
    return 0;
}

K
Kevin Wolf 已提交
804
static BlockDriver bdrv_blkdebug = {
805 806 807
    .format_name            = "blkdebug",
    .protocol_name          = "blkdebug",
    .instance_size          = sizeof(BDRVBlkdebugState),
K
Kevin Wolf 已提交
808

809 810 811
    .bdrv_parse_filename    = blkdebug_parse_filename,
    .bdrv_file_open         = blkdebug_open,
    .bdrv_close             = blkdebug_close,
K
Kevin Wolf 已提交
812
    .bdrv_reopen_prepare    = blkdebug_reopen_prepare,
813 814
    .bdrv_child_perm        = bdrv_filter_default_perms,

815
    .bdrv_getlength         = blkdebug_getlength,
K
Kevin Wolf 已提交
816
    .bdrv_truncate          = blkdebug_truncate,
817
    .bdrv_refresh_filename  = blkdebug_refresh_filename,
818
    .bdrv_refresh_limits    = blkdebug_refresh_limits,
K
Kevin Wolf 已提交
819

820 821 822
    .bdrv_co_preadv         = blkdebug_co_preadv,
    .bdrv_co_pwritev        = blkdebug_co_pwritev,
    .bdrv_co_flush_to_disk  = blkdebug_co_flush,
823 824
    .bdrv_co_pwrite_zeroes  = blkdebug_co_pwrite_zeroes,
    .bdrv_co_pdiscard       = blkdebug_co_pdiscard,
K
Kevin Wolf 已提交
825

826 827
    .bdrv_debug_event           = blkdebug_debug_event,
    .bdrv_debug_breakpoint      = blkdebug_debug_breakpoint,
F
Fam Zheng 已提交
828 829
    .bdrv_debug_remove_breakpoint
                                = blkdebug_debug_remove_breakpoint,
830 831
    .bdrv_debug_resume          = blkdebug_debug_resume,
    .bdrv_debug_is_suspended    = blkdebug_debug_is_suspended,
K
Kevin Wolf 已提交
832 833 834 835 836 837 838 839
};

static void bdrv_blkdebug_init(void)
{
    bdrv_register(&bdrv_blkdebug);
}

block_init(bdrv_blkdebug_init);