master
c 1,120 lines 31.4 KB
Raw
1 /*
2 * Block protocol for I/O error injection
3 *
4 * Copyright (C) 2016-2017 Red Hat, Inc.
5 * Copyright (c) 2010 Kevin Wolf <kwolf@redhat.com>
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25
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-io.h"
31 #include "block/block_int.h"
32 #include "block/qdict.h"
33 #include "qemu/module.h"
34 #include "qemu/option.h"
35 #include "qapi/qapi-visit-block-core.h"
36 #include "qobject/qdict.h"
37 #include "qobject/qlist.h"
38 #include "qobject/qstring.h"
39 #include "qapi/qobject-input-visitor.h"
40 #include "system/qtest.h"
41
42 /* All APIs are thread-safe */
43
44 typedef struct BDRVBlkdebugState {
45 /* IN: initialized in blkdebug_open() and never changed */
46 uint64_t align;
47 uint64_t max_transfer;
48 uint64_t opt_write_zero;
49 uint64_t max_write_zero;
50 uint64_t opt_discard;
51 uint64_t max_discard;
52 char *config_file; /* For blkdebug_refresh_filename() */
53 /* initialized in blkdebug_parse_perms() */
54 uint64_t take_child_perms;
55 uint64_t unshare_child_perms;
56
57 /* State. Protected by lock */
58 int state;
59 QLIST_HEAD(, BlkdebugRule) rules[BLKDBG__MAX];
60 QSIMPLEQ_HEAD(, BlkdebugRule) active_rules;
61 QLIST_HEAD(, BlkdebugSuspendedReq) suspended_reqs;
62 QemuMutex lock;
63 } BDRVBlkdebugState;
64
65 typedef struct BlkdebugAIOCB {
66 BlockAIOCB common;
67 int ret;
68 } BlkdebugAIOCB;
69
70 typedef struct BlkdebugSuspendedReq {
71 /* IN: initialized in suspend_request() */
72 Coroutine *co;
73 char *tag;
74
75 /* List entry protected BDRVBlkdebugState's lock */
76 QLIST_ENTRY(BlkdebugSuspendedReq) next;
77 } BlkdebugSuspendedReq;
78
79 enum {
80 ACTION_INJECT_ERROR,
81 ACTION_SET_STATE,
82 ACTION_SUSPEND,
83 ACTION__MAX,
84 };
85
86 typedef struct BlkdebugRule {
87 /* IN: initialized in add_rule() or blkdebug_debug_breakpoint() */
88 BlkdebugEvent event;
89 int action;
90 int state;
91 union {
92 struct {
93 uint64_t iotype_mask;
94 int error;
95 int immediately;
96 int once;
97 int64_t offset;
98 int64_t delay_ns;
99 } inject;
100 struct {
101 int new_state;
102 } set_state;
103 struct {
104 char *tag;
105 } suspend;
106 } options;
107
108 /* List entries protected BDRVBlkdebugState's lock */
109 QLIST_ENTRY(BlkdebugRule) next;
110 QSIMPLEQ_ENTRY(BlkdebugRule) active_next;
111 } BlkdebugRule;
112
113 QEMU_BUILD_BUG_MSG(BLKDEBUG_IO_TYPE__MAX > 64,
114 "BlkdebugIOType mask does not fit into an uint64_t");
115
116 static QemuOptsList inject_error_opts = {
117 .name = "inject-error",
118 .head = QTAILQ_HEAD_INITIALIZER(inject_error_opts.head),
119 .desc = {
120 {
121 .name = "event",
122 .type = QEMU_OPT_STRING,
123 },
124 {
125 .name = "state",
126 .type = QEMU_OPT_NUMBER,
127 },
128 {
129 .name = "iotype",
130 .type = QEMU_OPT_STRING,
131 },
132 {
133 .name = "errno",
134 .type = QEMU_OPT_NUMBER,
135 },
136 {
137 .name = "sector",
138 .type = QEMU_OPT_NUMBER,
139 },
140 {
141 .name = "once",
142 .type = QEMU_OPT_BOOL,
143 },
144 {
145 .name = "immediately",
146 .type = QEMU_OPT_BOOL,
147 },
148 {
149 .name = "delay-ns",
150 .type = QEMU_OPT_NUMBER,
151 },
152 { /* end of list */ }
153 },
154 };
155
156 static QemuOptsList set_state_opts = {
157 .name = "set-state",
158 .head = QTAILQ_HEAD_INITIALIZER(set_state_opts.head),
159 .desc = {
160 {
161 .name = "event",
162 .type = QEMU_OPT_STRING,
163 },
164 {
165 .name = "state",
166 .type = QEMU_OPT_NUMBER,
167 },
168 {
169 .name = "new_state",
170 .type = QEMU_OPT_NUMBER,
171 },
172 { /* end of list */ }
173 },
174 };
175
176 static QemuOptsList *config_groups[] = {
177 &inject_error_opts,
178 &set_state_opts,
179 NULL
180 };
181
182 struct add_rule_data {
183 BDRVBlkdebugState *s;
184 int action;
185 };
186
187 static int add_rule(void *opaque, QemuOpts *opts, Error **errp)
188 {
189 struct add_rule_data *d = opaque;
190 BDRVBlkdebugState *s = d->s;
191 const char *event_name;
192 int event;
193 struct BlkdebugRule *rule;
194 int64_t sector;
195 BlkdebugIOType iotype;
196 Error *local_error = NULL;
197
198 /* Find the right event for the rule */
199 event_name = qemu_opt_get(opts, "event");
200 if (!event_name) {
201 error_setg(errp, "Missing event name for rule");
202 return -1;
203 }
204 event = qapi_enum_parse(&BlkdebugEvent_lookup, event_name, -1, errp);
205 if (event < 0) {
206 return -1;
207 }
208
209 /* Set attributes common for all actions */
210 rule = g_malloc0(sizeof(*rule));
211 *rule = (struct BlkdebugRule) {
212 .event = event,
213 .action = d->action,
214 .state = qemu_opt_get_number(opts, "state", 0),
215 };
216
217 /* Parse action-specific options */
218 switch (d->action) {
219 case ACTION_INJECT_ERROR:
220 rule->options.inject.error = qemu_opt_get_number(opts, "errno", EIO);
221 rule->options.inject.once = qemu_opt_get_bool(opts, "once", 0);
222 rule->options.inject.immediately =
223 qemu_opt_get_bool(opts, "immediately", 0);
224 rule->options.inject.delay_ns =
225 qemu_opt_get_number(opts, "delay-ns", 0);
226 sector = qemu_opt_get_number(opts, "sector", -1);
227 rule->options.inject.offset =
228 sector == -1 ? -1 : sector * BDRV_SECTOR_SIZE;
229
230 iotype = qapi_enum_parse(&BlkdebugIOType_lookup,
231 qemu_opt_get(opts, "iotype"),
232 BLKDEBUG_IO_TYPE__MAX, &local_error);
233 if (local_error) {
234 error_propagate(errp, local_error);
235 g_free(rule);
236 return -1;
237 }
238 if (iotype != BLKDEBUG_IO_TYPE__MAX) {
239 rule->options.inject.iotype_mask = (1ull << iotype);
240 } else {
241 /* Apply the default */
242 rule->options.inject.iotype_mask =
243 (1ull << BLKDEBUG_IO_TYPE_READ)
244 | (1ull << BLKDEBUG_IO_TYPE_WRITE)
245 | (1ull << BLKDEBUG_IO_TYPE_WRITE_ZEROES)
246 | (1ull << BLKDEBUG_IO_TYPE_DISCARD)
247 | (1ull << BLKDEBUG_IO_TYPE_FLUSH);
248 }
249
250 break;
251
252 case ACTION_SET_STATE:
253 rule->options.set_state.new_state =
254 qemu_opt_get_number(opts, "new_state", 0);
255 break;
256
257 case ACTION_SUSPEND:
258 rule->options.suspend.tag =
259 g_strdup(qemu_opt_get(opts, "tag"));
260 break;
261 };
262
263 /* Add the rule */
264 qemu_mutex_lock(&s->lock);
265 QLIST_INSERT_HEAD(&s->rules[event], rule, next);
266 qemu_mutex_unlock(&s->lock);
267
268 return 0;
269 }
270
271 /* Called with lock held or from .bdrv_close */
272 static void remove_rule(BlkdebugRule *rule)
273 {
274 switch (rule->action) {
275 case ACTION_INJECT_ERROR:
276 case ACTION_SET_STATE:
277 break;
278 case ACTION_SUSPEND:
279 g_free(rule->options.suspend.tag);
280 break;
281 }
282
283 QLIST_REMOVE(rule, next);
284 g_free(rule);
285 }
286
287 static int read_config(BDRVBlkdebugState *s, const char *filename,
288 QDict *options, Error **errp)
289 {
290 FILE *f = NULL;
291 int ret;
292 struct add_rule_data d;
293 Error *local_err = NULL;
294
295 if (filename) {
296 f = fopen(filename, "r");
297 if (f == NULL) {
298 error_setg_file_open(errp, errno, filename);
299 return -errno;
300 }
301
302 ret = qemu_config_parse(f, config_groups, filename, errp);
303 if (ret < 0) {
304 goto fail;
305 }
306 }
307
308 if (!qemu_config_parse_qdict(options, config_groups, errp)) {
309 ret = -EINVAL;
310 goto fail;
311 }
312
313 d.s = s;
314 d.action = ACTION_INJECT_ERROR;
315 qemu_opts_foreach(&inject_error_opts, add_rule, &d, &local_err);
316 if (local_err) {
317 error_propagate(errp, local_err);
318 ret = -EINVAL;
319 goto fail;
320 }
321
322 d.action = ACTION_SET_STATE;
323 qemu_opts_foreach(&set_state_opts, add_rule, &d, &local_err);
324 if (local_err) {
325 error_propagate(errp, local_err);
326 ret = -EINVAL;
327 goto fail;
328 }
329
330 ret = 0;
331 fail:
332 qemu_opts_reset(&inject_error_opts);
333 qemu_opts_reset(&set_state_opts);
334 if (f) {
335 fclose(f);
336 }
337 return ret;
338 }
339
340 /* Valid blkdebug filenames look like blkdebug:path/to/config:path/to/image */
341 static void blkdebug_parse_filename(const char *filename, QDict *options,
342 Error **errp)
343 {
344 const char *c;
345
346 /* Parse the blkdebug: prefix */
347 if (!strstart(filename, "blkdebug:", &filename)) {
348 /* There was no prefix; therefore, all options have to be already
349 present in the QDict (except for the filename) */
350 qdict_put_str(options, "x-image", filename);
351 return;
352 }
353
354 /* Parse config file path */
355 c = strchr(filename, ':');
356 if (c == NULL) {
357 error_setg(errp, "blkdebug requires both config file and image path");
358 return;
359 }
360
361 if (c != filename) {
362 QString *config_path;
363 config_path = qstring_from_substr(filename, 0, c - filename);
364 qdict_put(options, "config", config_path);
365 }
366
367 /* TODO Allow multi-level nesting and set file.filename here */
368 filename = c + 1;
369 qdict_put_str(options, "x-image", filename);
370 }
371
372 static int blkdebug_parse_perm_list(uint64_t *dest, QDict *options,
373 const char *prefix, Error **errp)
374 {
375 int ret = 0;
376 QDict *subqdict = NULL;
377 QObject *crumpled_subqdict = NULL;
378 Visitor *v = NULL;
379 BlockPermissionList *perm_list = NULL, *element;
380
381 *dest = 0;
382
383 qdict_extract_subqdict(options, &subqdict, prefix);
384 if (!qdict_size(subqdict)) {
385 goto out;
386 }
387
388 crumpled_subqdict = qdict_crumple(subqdict, errp);
389 if (!crumpled_subqdict) {
390 ret = -EINVAL;
391 goto out;
392 }
393
394 v = qobject_input_visitor_new(crumpled_subqdict);
395 if (!visit_type_BlockPermissionList(v, NULL, &perm_list, errp)) {
396 ret = -EINVAL;
397 goto out;
398 }
399
400 for (element = perm_list; element; element = element->next) {
401 *dest |= bdrv_qapi_perm_to_blk_perm(element->value);
402 }
403
404 out:
405 qapi_free_BlockPermissionList(perm_list);
406 visit_free(v);
407 qobject_unref(subqdict);
408 qobject_unref(crumpled_subqdict);
409 return ret;
410 }
411
412 static int blkdebug_parse_perms(BDRVBlkdebugState *s, QDict *options,
413 Error **errp)
414 {
415 int ret;
416
417 ret = blkdebug_parse_perm_list(&s->take_child_perms, options,
418 "take-child-perms.", errp);
419 if (ret < 0) {
420 return ret;
421 }
422
423 ret = blkdebug_parse_perm_list(&s->unshare_child_perms, options,
424 "unshare-child-perms.", errp);
425 if (ret < 0) {
426 return ret;
427 }
428
429 return 0;
430 }
431
432 static QemuOptsList runtime_opts = {
433 .name = "blkdebug",
434 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
435 .desc = {
436 {
437 .name = "config",
438 .type = QEMU_OPT_STRING,
439 .help = "Path to the configuration file",
440 },
441 {
442 .name = "x-image",
443 .type = QEMU_OPT_STRING,
444 .help = "[internal use only, will be removed]",
445 },
446 {
447 .name = "align",
448 .type = QEMU_OPT_SIZE,
449 .help = "Required alignment in bytes",
450 },
451 {
452 .name = "max-transfer",
453 .type = QEMU_OPT_SIZE,
454 .help = "Maximum transfer size in bytes",
455 },
456 {
457 .name = "opt-write-zero",
458 .type = QEMU_OPT_SIZE,
459 .help = "Optimum write zero alignment in bytes",
460 },
461 {
462 .name = "max-write-zero",
463 .type = QEMU_OPT_SIZE,
464 .help = "Maximum write zero size in bytes",
465 },
466 {
467 .name = "opt-discard",
468 .type = QEMU_OPT_SIZE,
469 .help = "Optimum discard alignment in bytes",
470 },
471 {
472 .name = "max-discard",
473 .type = QEMU_OPT_SIZE,
474 .help = "Maximum discard size in bytes",
475 },
476 { /* end of list */ }
477 },
478 };
479
480 static int blkdebug_open(BlockDriverState *bs, QDict *options, int flags,
481 Error **errp)
482 {
483 BDRVBlkdebugState *s = bs->opaque;
484 QemuOpts *opts;
485 int ret;
486 uint64_t align;
487
488 qemu_mutex_init(&s->lock);
489 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
490 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
491 ret = -EINVAL;
492 goto out;
493 }
494
495 /* Read rules from config file or command line options */
496 s->config_file = g_strdup(qemu_opt_get(opts, "config"));
497 ret = read_config(s, s->config_file, options, errp);
498 if (ret) {
499 goto out;
500 }
501
502 /* Set initial state */
503 s->state = 1;
504
505 /* Parse permissions modifiers before opening the image file */
506 ret = blkdebug_parse_perms(s, options, errp);
507 if (ret < 0) {
508 goto out;
509 }
510
511 /* Open the image file */
512 ret = bdrv_open_file_child(qemu_opt_get(opts, "x-image"), options, "image",
513 bs, errp);
514 if (ret < 0) {
515 goto out;
516 }
517
518 bdrv_graph_rdlock_main_loop();
519
520 bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED |
521 (BDRV_REQ_FUA & bs->file->bs->supported_write_flags);
522 bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED |
523 ((BDRV_REQ_FUA | BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK) &
524 bs->file->bs->supported_zero_flags);
525 ret = -EINVAL;
526
527 /* Set alignment overrides */
528 s->align = qemu_opt_get_size(opts, "align", 0);
529 if (s->align && (s->align >= INT_MAX || !is_power_of_2(s->align))) {
530 error_setg(errp, "Cannot meet constraints with align %" PRIu64,
531 s->align);
532 goto out_rdlock;
533 }
534 align = MAX(s->align, bs->file->bs->bl.request_alignment);
535
536 s->max_transfer = qemu_opt_get_size(opts, "max-transfer", 0);
537 if (s->max_transfer &&
538 (s->max_transfer >= INT_MAX ||
539 !QEMU_IS_ALIGNED(s->max_transfer, align))) {
540 error_setg(errp, "Cannot meet constraints with max-transfer %" PRIu64,
541 s->max_transfer);
542 goto out_rdlock;
543 }
544
545 s->opt_write_zero = qemu_opt_get_size(opts, "opt-write-zero", 0);
546 if (s->opt_write_zero &&
547 (s->opt_write_zero >= INT_MAX ||
548 !QEMU_IS_ALIGNED(s->opt_write_zero, align))) {
549 error_setg(errp, "Cannot meet constraints with opt-write-zero %" PRIu64,
550 s->opt_write_zero);
551 goto out_rdlock;
552 }
553
554 s->max_write_zero = qemu_opt_get_size(opts, "max-write-zero", 0);
555 if (s->max_write_zero &&
556 (s->max_write_zero >= INT_MAX ||
557 !QEMU_IS_ALIGNED(s->max_write_zero,
558 MAX(s->opt_write_zero, align)))) {
559 error_setg(errp, "Cannot meet constraints with max-write-zero %" PRIu64,
560 s->max_write_zero);
561 goto out_rdlock;
562 }
563
564 s->opt_discard = qemu_opt_get_size(opts, "opt-discard", 0);
565 if (s->opt_discard &&
566 (s->opt_discard >= INT_MAX ||
567 !QEMU_IS_ALIGNED(s->opt_discard, align))) {
568 error_setg(errp, "Cannot meet constraints with opt-discard %" PRIu64,
569 s->opt_discard);
570 goto out_rdlock;
571 }
572
573 s->max_discard = qemu_opt_get_size(opts, "max-discard", 0);
574 if (s->max_discard &&
575 (s->max_discard >= INT_MAX ||
576 !QEMU_IS_ALIGNED(s->max_discard,
577 MAX(s->opt_discard, align)))) {
578 error_setg(errp, "Cannot meet constraints with max-discard %" PRIu64,
579 s->max_discard);
580 goto out_rdlock;
581 }
582
583 bdrv_debug_event(bs, BLKDBG_NONE);
584
585 ret = 0;
586 out_rdlock:
587 bdrv_graph_rdunlock_main_loop();
588 out:
589 if (ret < 0) {
590 qemu_mutex_destroy(&s->lock);
591 g_free(s->config_file);
592 }
593 qemu_opts_del(opts);
594 return ret;
595 }
596
597 static int coroutine_fn rule_check(BlockDriverState *bs, uint64_t offset,
598 uint64_t bytes, BlkdebugIOType iotype)
599 {
600 BDRVBlkdebugState *s = bs->opaque;
601 BlkdebugRule *rule;
602 int error;
603 bool immediately;
604 int64_t delay_ns;
605
606 qemu_mutex_lock(&s->lock);
607 QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
608 uint64_t inject_offset = rule->options.inject.offset;
609
610 if ((inject_offset == -1 ||
611 (bytes && inject_offset >= offset &&
612 inject_offset < offset + bytes)) &&
613 (rule->options.inject.iotype_mask & (1ull << iotype)))
614 {
615 break;
616 }
617 }
618
619 if (!rule) {
620 qemu_mutex_unlock(&s->lock);
621 return 0;
622 }
623
624 immediately = rule->options.inject.immediately;
625 error = rule->options.inject.error;
626 delay_ns = rule->options.inject.delay_ns;
627
628 if (rule->options.inject.once) {
629 QSIMPLEQ_REMOVE(&s->active_rules, rule, BlkdebugRule, active_next);
630 remove_rule(rule);
631 }
632
633 qemu_mutex_unlock(&s->lock);
634
635 if (delay_ns) {
636 qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, delay_ns);
637 }
638 if (!immediately) {
639 aio_co_schedule(qemu_get_current_aio_context(), qemu_coroutine_self());
640 qemu_coroutine_yield();
641 }
642
643 return -error;
644 }
645
646 static int coroutine_fn GRAPH_RDLOCK
647 blkdebug_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
648 QEMUIOVector *qiov, BdrvRequestFlags flags)
649 {
650 int err;
651
652 /* Sanity check block layer guarantees */
653 assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));
654 assert(QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment));
655 if (bs->bl.max_transfer) {
656 assert(bytes <= bs->bl.max_transfer);
657 }
658
659 err = rule_check(bs, offset, bytes, BLKDEBUG_IO_TYPE_READ);
660 if (err) {
661 return err;
662 }
663
664 return bdrv_co_preadv(bs->file, offset, bytes, qiov, flags);
665 }
666
667 static int coroutine_fn GRAPH_RDLOCK
668 blkdebug_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
669 QEMUIOVector *qiov, BdrvRequestFlags flags)
670 {
671 int err;
672
673 /* Sanity check block layer guarantees */
674 assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));
675 assert(QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment));
676 if (bs->bl.max_transfer) {
677 assert(bytes <= bs->bl.max_transfer);
678 }
679
680 err = rule_check(bs, offset, bytes, BLKDEBUG_IO_TYPE_WRITE);
681 if (err) {
682 return err;
683 }
684
685 return bdrv_co_pwritev(bs->file, offset, bytes, qiov, flags);
686 }
687
688 static int GRAPH_RDLOCK coroutine_fn blkdebug_co_flush(BlockDriverState *bs)
689 {
690 int err = rule_check(bs, 0, 0, BLKDEBUG_IO_TYPE_FLUSH);
691
692 if (err) {
693 return err;
694 }
695
696 return bdrv_co_flush(bs->file->bs);
697 }
698
699 static int coroutine_fn GRAPH_RDLOCK
700 blkdebug_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
701 BdrvRequestFlags flags)
702 {
703 uint32_t align = MAX(bs->bl.request_alignment,
704 bs->bl.pwrite_zeroes_alignment);
705 int err;
706
707 /* Only pass through requests that are larger than requested
708 * preferred alignment (so that we test the fallback to writes on
709 * unaligned portions), and check that the block layer never hands
710 * us anything unaligned that crosses an alignment boundary. */
711 if (bytes < align) {
712 assert(QEMU_IS_ALIGNED(offset, align) ||
713 QEMU_IS_ALIGNED(offset + bytes, align) ||
714 DIV_ROUND_UP(offset, align) ==
715 DIV_ROUND_UP(offset + bytes, align));
716 return -ENOTSUP;
717 }
718 assert(QEMU_IS_ALIGNED(offset, align));
719 assert(QEMU_IS_ALIGNED(bytes, align));
720 if (bs->bl.max_pwrite_zeroes) {
721 assert(bytes <= bs->bl.max_pwrite_zeroes);
722 }
723
724 err = rule_check(bs, offset, bytes, BLKDEBUG_IO_TYPE_WRITE_ZEROES);
725 if (err) {
726 return err;
727 }
728
729 return bdrv_co_pwrite_zeroes(bs->file, offset, bytes, flags);
730 }
731
732 static int coroutine_fn GRAPH_RDLOCK
733 blkdebug_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
734 {
735 uint32_t align = bs->bl.pdiscard_alignment;
736 int err;
737
738 /* Only pass through requests that are larger than requested
739 * minimum alignment, and ensure that unaligned requests do not
740 * cross optimum discard boundaries. */
741 if (bytes < bs->bl.request_alignment) {
742 assert(QEMU_IS_ALIGNED(offset, align) ||
743 QEMU_IS_ALIGNED(offset + bytes, align) ||
744 DIV_ROUND_UP(offset, align) ==
745 DIV_ROUND_UP(offset + bytes, align));
746 return -ENOTSUP;
747 }
748 assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));
749 assert(QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment));
750 if (align && bytes >= align) {
751 assert(QEMU_IS_ALIGNED(offset, align));
752 assert(QEMU_IS_ALIGNED(bytes, align));
753 }
754 if (bs->bl.max_pdiscard) {
755 assert(bytes <= bs->bl.max_pdiscard);
756 }
757
758 err = rule_check(bs, offset, bytes, BLKDEBUG_IO_TYPE_DISCARD);
759 if (err) {
760 return err;
761 }
762
763 return bdrv_co_pdiscard(bs->file, offset, bytes);
764 }
765
766 static int coroutine_fn GRAPH_RDLOCK
767 blkdebug_co_block_status(BlockDriverState *bs, unsigned int mode,
768 int64_t offset, int64_t bytes, int64_t *pnum,
769 int64_t *map, BlockDriverState **file)
770 {
771 int err;
772
773 assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
774
775 err = rule_check(bs, offset, bytes, BLKDEBUG_IO_TYPE_BLOCK_STATUS);
776 if (err) {
777 return err;
778 }
779
780 assert(bs->file && bs->file->bs);
781 *pnum = bytes;
782 *map = offset;
783 *file = bs->file->bs;
784 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
785 }
786
787 static void blkdebug_close(BlockDriverState *bs)
788 {
789 BDRVBlkdebugState *s = bs->opaque;
790 BlkdebugRule *rule, *next;
791 int i;
792
793 for (i = 0; i < BLKDBG__MAX; i++) {
794 QLIST_FOREACH_SAFE(rule, &s->rules[i], next, next) {
795 remove_rule(rule);
796 }
797 }
798
799 g_free(s->config_file);
800 qemu_mutex_destroy(&s->lock);
801 }
802
803 /* Called with lock held. */
804 static void suspend_request(BlockDriverState *bs, BlkdebugRule *rule)
805 {
806 BDRVBlkdebugState *s = bs->opaque;
807 BlkdebugSuspendedReq *r;
808
809 r = g_new(BlkdebugSuspendedReq, 1);
810
811 r->co = qemu_coroutine_self();
812 r->tag = g_strdup(rule->options.suspend.tag);
813
814 remove_rule(rule);
815 QLIST_INSERT_HEAD(&s->suspended_reqs, r, next);
816
817 if (!qtest_enabled()) {
818 printf("blkdebug: Suspended request '%s'\n", r->tag);
819 }
820 }
821
822 /* Called with lock held. */
823 static void process_rule(BlockDriverState *bs, struct BlkdebugRule *rule,
824 int *action_count, int *new_state)
825 {
826 BDRVBlkdebugState *s = bs->opaque;
827
828 /* Only process rules for the current state */
829 if (rule->state && rule->state != s->state) {
830 return;
831 }
832
833 /* Take the action */
834 action_count[rule->action]++;
835 switch (rule->action) {
836 case ACTION_INJECT_ERROR:
837 if (action_count[ACTION_INJECT_ERROR] == 1) {
838 QSIMPLEQ_INIT(&s->active_rules);
839 }
840 QSIMPLEQ_INSERT_HEAD(&s->active_rules, rule, active_next);
841 break;
842
843 case ACTION_SET_STATE:
844 *new_state = rule->options.set_state.new_state;
845 break;
846
847 case ACTION_SUSPEND:
848 suspend_request(bs, rule);
849 break;
850 }
851 }
852
853 static void coroutine_fn
854 blkdebug_co_debug_event(BlockDriverState *bs, BlkdebugEvent event)
855 {
856 BDRVBlkdebugState *s = bs->opaque;
857 struct BlkdebugRule *rule, *next;
858 int new_state;
859 int actions_count[ACTION__MAX] = { 0 };
860
861 assert((int)event >= 0 && event < BLKDBG__MAX);
862
863 WITH_QEMU_LOCK_GUARD(&s->lock) {
864 new_state = s->state;
865 QLIST_FOREACH_SAFE(rule, &s->rules[event], next, next) {
866 process_rule(bs, rule, actions_count, &new_state);
867 }
868 s->state = new_state;
869 }
870
871 while (actions_count[ACTION_SUSPEND] > 0) {
872 qemu_coroutine_yield();
873 actions_count[ACTION_SUSPEND]--;
874 }
875 }
876
877 static int blkdebug_debug_breakpoint(BlockDriverState *bs, const char *event,
878 const char *tag)
879 {
880 BDRVBlkdebugState *s = bs->opaque;
881 struct BlkdebugRule *rule;
882 int blkdebug_event;
883
884 blkdebug_event = qapi_enum_parse(&BlkdebugEvent_lookup, event, -1, NULL);
885 if (blkdebug_event < 0) {
886 return -ENOENT;
887 }
888
889 rule = g_malloc(sizeof(*rule));
890 *rule = (struct BlkdebugRule) {
891 .event = blkdebug_event,
892 .action = ACTION_SUSPEND,
893 .state = 0,
894 .options.suspend.tag = g_strdup(tag),
895 };
896
897 qemu_mutex_lock(&s->lock);
898 QLIST_INSERT_HEAD(&s->rules[blkdebug_event], rule, next);
899 qemu_mutex_unlock(&s->lock);
900
901 return 0;
902 }
903
904 /* Called with lock held. May temporarily release lock. */
905 static int resume_req_by_tag(BDRVBlkdebugState *s, const char *tag, bool all)
906 {
907 BlkdebugSuspendedReq *r;
908
909 retry:
910 /*
911 * No need for _SAFE, since a different coroutine can remove another node
912 * (not the current one) in this list, and when the current one is removed
913 * the iteration starts back from beginning anyways.
914 */
915 QLIST_FOREACH(r, &s->suspended_reqs, next) {
916 if (!strcmp(r->tag, tag)) {
917 Coroutine *co = r->co;
918
919 if (!qtest_enabled()) {
920 printf("blkdebug: Resuming request '%s'\n", r->tag);
921 }
922
923 QLIST_REMOVE(r, next);
924 g_free(r->tag);
925 g_free(r);
926
927 qemu_mutex_unlock(&s->lock);
928 qemu_coroutine_enter(co);
929 qemu_mutex_lock(&s->lock);
930
931 if (all) {
932 goto retry;
933 }
934 return 0;
935 }
936 }
937 return -ENOENT;
938 }
939
940 static int blkdebug_debug_resume(BlockDriverState *bs, const char *tag)
941 {
942 BDRVBlkdebugState *s = bs->opaque;
943 QEMU_LOCK_GUARD(&s->lock);
944 return resume_req_by_tag(s, tag, false);
945 }
946
947 static int blkdebug_debug_remove_breakpoint(BlockDriverState *bs,
948 const char *tag)
949 {
950 BDRVBlkdebugState *s = bs->opaque;
951 BlkdebugRule *rule, *next;
952 int i, ret = -ENOENT;
953
954 QEMU_LOCK_GUARD(&s->lock);
955 for (i = 0; i < BLKDBG__MAX; i++) {
956 QLIST_FOREACH_SAFE(rule, &s->rules[i], next, next) {
957 if (rule->action == ACTION_SUSPEND &&
958 !strcmp(rule->options.suspend.tag, tag)) {
959 remove_rule(rule);
960 ret = 0;
961 }
962 }
963 }
964 if (resume_req_by_tag(s, tag, true) == 0) {
965 ret = 0;
966 }
967 return ret;
968 }
969
970 static bool blkdebug_debug_is_suspended(BlockDriverState *bs, const char *tag)
971 {
972 BDRVBlkdebugState *s = bs->opaque;
973 BlkdebugSuspendedReq *r;
974
975 QEMU_LOCK_GUARD(&s->lock);
976 QLIST_FOREACH(r, &s->suspended_reqs, next) {
977 if (!strcmp(r->tag, tag)) {
978 return true;
979 }
980 }
981 return false;
982 }
983
984 static int64_t coroutine_fn GRAPH_RDLOCK
985 blkdebug_co_getlength(BlockDriverState *bs)
986 {
987 return bdrv_co_getlength(bs->file->bs);
988 }
989
990 static void GRAPH_RDLOCK blkdebug_refresh_filename(BlockDriverState *bs)
991 {
992 BDRVBlkdebugState *s = bs->opaque;
993 const QDictEntry *e;
994 int ret;
995
996 if (!bs->file->bs->exact_filename[0]) {
997 return;
998 }
999
1000 for (e = qdict_first(bs->full_open_options); e;
1001 e = qdict_next(bs->full_open_options, e))
1002 {
1003 /* Real child options are under "image", but "x-image" may
1004 * contain a filename */
1005 if (strcmp(qdict_entry_key(e), "config") &&
1006 strcmp(qdict_entry_key(e), "image") &&
1007 strcmp(qdict_entry_key(e), "x-image") &&
1008 strcmp(qdict_entry_key(e), "driver"))
1009 {
1010 return;
1011 }
1012 }
1013
1014 ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1015 "blkdebug:%s:%s",
1016 s->config_file ?: "", bs->file->bs->exact_filename);
1017 if (ret >= sizeof(bs->exact_filename)) {
1018 /* An overflow makes the filename unusable, so do not report any */
1019 bs->exact_filename[0] = 0;
1020 }
1021 }
1022
1023 static void blkdebug_refresh_limits(BlockDriverState *bs, Error **errp)
1024 {
1025 BDRVBlkdebugState *s = bs->opaque;
1026
1027 if (s->align) {
1028 bs->bl.request_alignment = s->align;
1029 }
1030 if (s->max_transfer) {
1031 bs->bl.max_transfer = s->max_transfer;
1032 }
1033 if (s->opt_write_zero) {
1034 bs->bl.pwrite_zeroes_alignment = s->opt_write_zero;
1035 }
1036 if (s->max_write_zero) {
1037 bs->bl.max_pwrite_zeroes = s->max_write_zero;
1038 }
1039 if (s->opt_discard) {
1040 bs->bl.pdiscard_alignment = s->opt_discard;
1041 }
1042 if (s->max_discard) {
1043 bs->bl.max_pdiscard = s->max_discard;
1044 }
1045 }
1046
1047 static int blkdebug_reopen_prepare(BDRVReopenState *reopen_state,
1048 BlockReopenQueue *queue, Error **errp)
1049 {
1050 return 0;
1051 }
1052
1053 static void blkdebug_child_perm(BlockDriverState *bs, BdrvChild *c,
1054 BdrvChildRole role,
1055 BlockReopenQueue *reopen_queue,
1056 uint64_t perm, uint64_t shared,
1057 uint64_t *nperm, uint64_t *nshared)
1058 {
1059 BDRVBlkdebugState *s = bs->opaque;
1060
1061 bdrv_default_perms(bs, c, role, reopen_queue,
1062 perm, shared, nperm, nshared);
1063
1064 *nperm |= s->take_child_perms;
1065 *nshared &= ~s->unshare_child_perms;
1066 }
1067
1068 static const char *const blkdebug_strong_runtime_opts[] = {
1069 "config",
1070 "inject-error.",
1071 "set-state.",
1072 "align",
1073 "max-transfer",
1074 "opt-write-zero",
1075 "max-write-zero",
1076 "opt-discard",
1077 "max-discard",
1078
1079 NULL
1080 };
1081
1082 static BlockDriver bdrv_blkdebug = {
1083 .format_name = "blkdebug",
1084 .protocol_name = "blkdebug",
1085 .instance_size = sizeof(BDRVBlkdebugState),
1086 .is_filter = true,
1087
1088 .bdrv_parse_filename = blkdebug_parse_filename,
1089 .bdrv_open = blkdebug_open,
1090 .bdrv_close = blkdebug_close,
1091 .bdrv_reopen_prepare = blkdebug_reopen_prepare,
1092 .bdrv_child_perm = blkdebug_child_perm,
1093
1094 .bdrv_co_getlength = blkdebug_co_getlength,
1095 .bdrv_refresh_filename = blkdebug_refresh_filename,
1096 .bdrv_refresh_limits = blkdebug_refresh_limits,
1097
1098 .bdrv_co_preadv = blkdebug_co_preadv,
1099 .bdrv_co_pwritev = blkdebug_co_pwritev,
1100 .bdrv_co_flush_to_disk = blkdebug_co_flush,
1101 .bdrv_co_pwrite_zeroes = blkdebug_co_pwrite_zeroes,
1102 .bdrv_co_pdiscard = blkdebug_co_pdiscard,
1103 .bdrv_co_block_status = blkdebug_co_block_status,
1104
1105 .bdrv_co_debug_event = blkdebug_co_debug_event,
1106 .bdrv_debug_breakpoint = blkdebug_debug_breakpoint,
1107 .bdrv_debug_remove_breakpoint
1108 = blkdebug_debug_remove_breakpoint,
1109 .bdrv_debug_resume = blkdebug_debug_resume,
1110 .bdrv_debug_is_suspended = blkdebug_debug_is_suspended,
1111
1112 .strong_runtime_opts = blkdebug_strong_runtime_opts,
1113 };
1114
1115 static void bdrv_blkdebug_init(void)
1116 {
1117 bdrv_register(&bdrv_blkdebug);
1118 }
1119
1120 block_init(bdrv_blkdebug_init);