xref: /openbmc/qemu/block/qed.c (revision 79e42085)
1 /*
2  * QEMU Enhanced Disk Format
3  *
4  * Copyright IBM, Corp. 2010
5  *
6  * Authors:
7  *  Stefan Hajnoczi   <stefanha@linux.vnet.ibm.com>
8  *  Anthony Liguori   <aliguori@us.ibm.com>
9  *
10  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
11  * See the COPYING.LIB file in the top-level directory.
12  *
13  */
14 
15 #include "qemu/osdep.h"
16 #include "block/qdict.h"
17 #include "qapi/error.h"
18 #include "qemu/timer.h"
19 #include "qemu/bswap.h"
20 #include "qemu/option.h"
21 #include "trace.h"
22 #include "qed.h"
23 #include "sysemu/block-backend.h"
24 #include "qapi/qmp/qdict.h"
25 #include "qapi/qobject-input-visitor.h"
26 #include "qapi/qapi-visit-block-core.h"
27 
28 static QemuOptsList qed_create_opts;
29 
30 static int bdrv_qed_probe(const uint8_t *buf, int buf_size,
31                           const char *filename)
32 {
33     const QEDHeader *header = (const QEDHeader *)buf;
34 
35     if (buf_size < sizeof(*header)) {
36         return 0;
37     }
38     if (le32_to_cpu(header->magic) != QED_MAGIC) {
39         return 0;
40     }
41     return 100;
42 }
43 
44 /**
45  * Check whether an image format is raw
46  *
47  * @fmt:    Backing file format, may be NULL
48  */
49 static bool qed_fmt_is_raw(const char *fmt)
50 {
51     return fmt && strcmp(fmt, "raw") == 0;
52 }
53 
54 static void qed_header_le_to_cpu(const QEDHeader *le, QEDHeader *cpu)
55 {
56     cpu->magic = le32_to_cpu(le->magic);
57     cpu->cluster_size = le32_to_cpu(le->cluster_size);
58     cpu->table_size = le32_to_cpu(le->table_size);
59     cpu->header_size = le32_to_cpu(le->header_size);
60     cpu->features = le64_to_cpu(le->features);
61     cpu->compat_features = le64_to_cpu(le->compat_features);
62     cpu->autoclear_features = le64_to_cpu(le->autoclear_features);
63     cpu->l1_table_offset = le64_to_cpu(le->l1_table_offset);
64     cpu->image_size = le64_to_cpu(le->image_size);
65     cpu->backing_filename_offset = le32_to_cpu(le->backing_filename_offset);
66     cpu->backing_filename_size = le32_to_cpu(le->backing_filename_size);
67 }
68 
69 static void qed_header_cpu_to_le(const QEDHeader *cpu, QEDHeader *le)
70 {
71     le->magic = cpu_to_le32(cpu->magic);
72     le->cluster_size = cpu_to_le32(cpu->cluster_size);
73     le->table_size = cpu_to_le32(cpu->table_size);
74     le->header_size = cpu_to_le32(cpu->header_size);
75     le->features = cpu_to_le64(cpu->features);
76     le->compat_features = cpu_to_le64(cpu->compat_features);
77     le->autoclear_features = cpu_to_le64(cpu->autoclear_features);
78     le->l1_table_offset = cpu_to_le64(cpu->l1_table_offset);
79     le->image_size = cpu_to_le64(cpu->image_size);
80     le->backing_filename_offset = cpu_to_le32(cpu->backing_filename_offset);
81     le->backing_filename_size = cpu_to_le32(cpu->backing_filename_size);
82 }
83 
84 int qed_write_header_sync(BDRVQEDState *s)
85 {
86     QEDHeader le;
87     int ret;
88 
89     qed_header_cpu_to_le(&s->header, &le);
90     ret = bdrv_pwrite(s->bs->file, 0, &le, sizeof(le));
91     if (ret != sizeof(le)) {
92         return ret;
93     }
94     return 0;
95 }
96 
97 /**
98  * Update header in-place (does not rewrite backing filename or other strings)
99  *
100  * This function only updates known header fields in-place and does not affect
101  * extra data after the QED header.
102  *
103  * No new allocating reqs can start while this function runs.
104  */
105 static int coroutine_fn qed_write_header(BDRVQEDState *s)
106 {
107     /* We must write full sectors for O_DIRECT but cannot necessarily generate
108      * the data following the header if an unrecognized compat feature is
109      * active.  Therefore, first read the sectors containing the header, update
110      * them, and write back.
111      */
112 
113     int nsectors = DIV_ROUND_UP(sizeof(QEDHeader), BDRV_SECTOR_SIZE);
114     size_t len = nsectors * BDRV_SECTOR_SIZE;
115     uint8_t *buf;
116     int ret;
117 
118     assert(s->allocating_acb || s->allocating_write_reqs_plugged);
119 
120     buf = qemu_blockalign(s->bs, len);
121 
122     ret = bdrv_co_pread(s->bs->file, 0, len, buf, 0);
123     if (ret < 0) {
124         goto out;
125     }
126 
127     /* Update header */
128     qed_header_cpu_to_le(&s->header, (QEDHeader *) buf);
129 
130     ret = bdrv_co_pwrite(s->bs->file, 0, len,  buf, 0);
131     if (ret < 0) {
132         goto out;
133     }
134 
135     ret = 0;
136 out:
137     qemu_vfree(buf);
138     return ret;
139 }
140 
141 static uint64_t qed_max_image_size(uint32_t cluster_size, uint32_t table_size)
142 {
143     uint64_t table_entries;
144     uint64_t l2_size;
145 
146     table_entries = (table_size * cluster_size) / sizeof(uint64_t);
147     l2_size = table_entries * cluster_size;
148 
149     return l2_size * table_entries;
150 }
151 
152 static bool qed_is_cluster_size_valid(uint32_t cluster_size)
153 {
154     if (cluster_size < QED_MIN_CLUSTER_SIZE ||
155         cluster_size > QED_MAX_CLUSTER_SIZE) {
156         return false;
157     }
158     if (cluster_size & (cluster_size - 1)) {
159         return false; /* not power of 2 */
160     }
161     return true;
162 }
163 
164 static bool qed_is_table_size_valid(uint32_t table_size)
165 {
166     if (table_size < QED_MIN_TABLE_SIZE ||
167         table_size > QED_MAX_TABLE_SIZE) {
168         return false;
169     }
170     if (table_size & (table_size - 1)) {
171         return false; /* not power of 2 */
172     }
173     return true;
174 }
175 
176 static bool qed_is_image_size_valid(uint64_t image_size, uint32_t cluster_size,
177                                     uint32_t table_size)
178 {
179     if (image_size % BDRV_SECTOR_SIZE != 0) {
180         return false; /* not multiple of sector size */
181     }
182     if (image_size > qed_max_image_size(cluster_size, table_size)) {
183         return false; /* image is too large */
184     }
185     return true;
186 }
187 
188 /**
189  * Read a string of known length from the image file
190  *
191  * @file:       Image file
192  * @offset:     File offset to start of string, in bytes
193  * @n:          String length in bytes
194  * @buf:        Destination buffer
195  * @buflen:     Destination buffer length in bytes
196  * @ret:        0 on success, -errno on failure
197  *
198  * The string is NUL-terminated.
199  */
200 static int qed_read_string(BdrvChild *file, uint64_t offset, size_t n,
201                            char *buf, size_t buflen)
202 {
203     int ret;
204     if (n >= buflen) {
205         return -EINVAL;
206     }
207     ret = bdrv_pread(file, offset, buf, n);
208     if (ret < 0) {
209         return ret;
210     }
211     buf[n] = '\0';
212     return 0;
213 }
214 
215 /**
216  * Allocate new clusters
217  *
218  * @s:          QED state
219  * @n:          Number of contiguous clusters to allocate
220  * @ret:        Offset of first allocated cluster
221  *
222  * This function only produces the offset where the new clusters should be
223  * written.  It updates BDRVQEDState but does not make any changes to the image
224  * file.
225  *
226  * Called with table_lock held.
227  */
228 static uint64_t qed_alloc_clusters(BDRVQEDState *s, unsigned int n)
229 {
230     uint64_t offset = s->file_size;
231     s->file_size += n * s->header.cluster_size;
232     return offset;
233 }
234 
235 QEDTable *qed_alloc_table(BDRVQEDState *s)
236 {
237     /* Honor O_DIRECT memory alignment requirements */
238     return qemu_blockalign(s->bs,
239                            s->header.cluster_size * s->header.table_size);
240 }
241 
242 /**
243  * Allocate a new zeroed L2 table
244  *
245  * Called with table_lock held.
246  */
247 static CachedL2Table *qed_new_l2_table(BDRVQEDState *s)
248 {
249     CachedL2Table *l2_table = qed_alloc_l2_cache_entry(&s->l2_cache);
250 
251     l2_table->table = qed_alloc_table(s);
252     l2_table->offset = qed_alloc_clusters(s, s->header.table_size);
253 
254     memset(l2_table->table->offsets, 0,
255            s->header.cluster_size * s->header.table_size);
256     return l2_table;
257 }
258 
259 static bool qed_plug_allocating_write_reqs(BDRVQEDState *s)
260 {
261     qemu_co_mutex_lock(&s->table_lock);
262 
263     /* No reentrancy is allowed.  */
264     assert(!s->allocating_write_reqs_plugged);
265     if (s->allocating_acb != NULL) {
266         /* Another allocating write came concurrently.  This cannot happen
267          * from bdrv_qed_co_drain_begin, but it can happen when the timer runs.
268          */
269         qemu_co_mutex_unlock(&s->table_lock);
270         return false;
271     }
272 
273     s->allocating_write_reqs_plugged = true;
274     qemu_co_mutex_unlock(&s->table_lock);
275     return true;
276 }
277 
278 static void qed_unplug_allocating_write_reqs(BDRVQEDState *s)
279 {
280     qemu_co_mutex_lock(&s->table_lock);
281     assert(s->allocating_write_reqs_plugged);
282     s->allocating_write_reqs_plugged = false;
283     qemu_co_queue_next(&s->allocating_write_reqs);
284     qemu_co_mutex_unlock(&s->table_lock);
285 }
286 
287 static void coroutine_fn qed_need_check_timer_entry(void *opaque)
288 {
289     BDRVQEDState *s = opaque;
290     int ret;
291 
292     trace_qed_need_check_timer_cb(s);
293 
294     if (!qed_plug_allocating_write_reqs(s)) {
295         return;
296     }
297 
298     /* Ensure writes are on disk before clearing flag */
299     ret = bdrv_co_flush(s->bs->file->bs);
300     if (ret < 0) {
301         qed_unplug_allocating_write_reqs(s);
302         return;
303     }
304 
305     s->header.features &= ~QED_F_NEED_CHECK;
306     ret = qed_write_header(s);
307     (void) ret;
308 
309     qed_unplug_allocating_write_reqs(s);
310 
311     ret = bdrv_co_flush(s->bs);
312     (void) ret;
313 }
314 
315 static void qed_need_check_timer_cb(void *opaque)
316 {
317     Coroutine *co = qemu_coroutine_create(qed_need_check_timer_entry, opaque);
318     qemu_coroutine_enter(co);
319 }
320 
321 static void qed_start_need_check_timer(BDRVQEDState *s)
322 {
323     trace_qed_start_need_check_timer(s);
324 
325     /* Use QEMU_CLOCK_VIRTUAL so we don't alter the image file while suspended for
326      * migration.
327      */
328     timer_mod(s->need_check_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
329                    NANOSECONDS_PER_SECOND * QED_NEED_CHECK_TIMEOUT);
330 }
331 
332 /* It's okay to call this multiple times or when no timer is started */
333 static void qed_cancel_need_check_timer(BDRVQEDState *s)
334 {
335     trace_qed_cancel_need_check_timer(s);
336     timer_del(s->need_check_timer);
337 }
338 
339 static void bdrv_qed_detach_aio_context(BlockDriverState *bs)
340 {
341     BDRVQEDState *s = bs->opaque;
342 
343     qed_cancel_need_check_timer(s);
344     timer_free(s->need_check_timer);
345 }
346 
347 static void bdrv_qed_attach_aio_context(BlockDriverState *bs,
348                                         AioContext *new_context)
349 {
350     BDRVQEDState *s = bs->opaque;
351 
352     s->need_check_timer = aio_timer_new(new_context,
353                                         QEMU_CLOCK_VIRTUAL, SCALE_NS,
354                                         qed_need_check_timer_cb, s);
355     if (s->header.features & QED_F_NEED_CHECK) {
356         qed_start_need_check_timer(s);
357     }
358 }
359 
360 static void coroutine_fn bdrv_qed_co_drain_begin(BlockDriverState *bs)
361 {
362     BDRVQEDState *s = bs->opaque;
363 
364     /* Fire the timer immediately in order to start doing I/O as soon as the
365      * header is flushed.
366      */
367     if (s->need_check_timer && timer_pending(s->need_check_timer)) {
368         qed_cancel_need_check_timer(s);
369         qed_need_check_timer_entry(s);
370     }
371 }
372 
373 static void bdrv_qed_init_state(BlockDriverState *bs)
374 {
375     BDRVQEDState *s = bs->opaque;
376 
377     memset(s, 0, sizeof(BDRVQEDState));
378     s->bs = bs;
379     qemu_co_mutex_init(&s->table_lock);
380     qemu_co_queue_init(&s->allocating_write_reqs);
381 }
382 
383 /* Called with table_lock held.  */
384 static int coroutine_fn bdrv_qed_do_open(BlockDriverState *bs, QDict *options,
385                                          int flags, Error **errp)
386 {
387     BDRVQEDState *s = bs->opaque;
388     QEDHeader le_header;
389     int64_t file_size;
390     int ret;
391 
392     ret = bdrv_pread(bs->file, 0, &le_header, sizeof(le_header));
393     if (ret < 0) {
394         return ret;
395     }
396     qed_header_le_to_cpu(&le_header, &s->header);
397 
398     if (s->header.magic != QED_MAGIC) {
399         error_setg(errp, "Image not in QED format");
400         return -EINVAL;
401     }
402     if (s->header.features & ~QED_FEATURE_MASK) {
403         /* image uses unsupported feature bits */
404         error_setg(errp, "Unsupported QED features: %" PRIx64,
405                    s->header.features & ~QED_FEATURE_MASK);
406         return -ENOTSUP;
407     }
408     if (!qed_is_cluster_size_valid(s->header.cluster_size)) {
409         return -EINVAL;
410     }
411 
412     /* Round down file size to the last cluster */
413     file_size = bdrv_getlength(bs->file->bs);
414     if (file_size < 0) {
415         return file_size;
416     }
417     s->file_size = qed_start_of_cluster(s, file_size);
418 
419     if (!qed_is_table_size_valid(s->header.table_size)) {
420         return -EINVAL;
421     }
422     if (!qed_is_image_size_valid(s->header.image_size,
423                                  s->header.cluster_size,
424                                  s->header.table_size)) {
425         return -EINVAL;
426     }
427     if (!qed_check_table_offset(s, s->header.l1_table_offset)) {
428         return -EINVAL;
429     }
430 
431     s->table_nelems = (s->header.cluster_size * s->header.table_size) /
432                       sizeof(uint64_t);
433     s->l2_shift = ctz32(s->header.cluster_size);
434     s->l2_mask = s->table_nelems - 1;
435     s->l1_shift = s->l2_shift + ctz32(s->table_nelems);
436 
437     /* Header size calculation must not overflow uint32_t */
438     if (s->header.header_size > UINT32_MAX / s->header.cluster_size) {
439         return -EINVAL;
440     }
441 
442     if ((s->header.features & QED_F_BACKING_FILE)) {
443         if ((uint64_t)s->header.backing_filename_offset +
444             s->header.backing_filename_size >
445             s->header.cluster_size * s->header.header_size) {
446             return -EINVAL;
447         }
448 
449         ret = qed_read_string(bs->file, s->header.backing_filename_offset,
450                               s->header.backing_filename_size,
451                               bs->auto_backing_file,
452                               sizeof(bs->auto_backing_file));
453         if (ret < 0) {
454             return ret;
455         }
456         pstrcpy(bs->backing_file, sizeof(bs->backing_file),
457                 bs->auto_backing_file);
458 
459         if (s->header.features & QED_F_BACKING_FORMAT_NO_PROBE) {
460             pstrcpy(bs->backing_format, sizeof(bs->backing_format), "raw");
461         }
462     }
463 
464     /* Reset unknown autoclear feature bits.  This is a backwards
465      * compatibility mechanism that allows images to be opened by older
466      * programs, which "knock out" unknown feature bits.  When an image is
467      * opened by a newer program again it can detect that the autoclear
468      * feature is no longer valid.
469      */
470     if ((s->header.autoclear_features & ~QED_AUTOCLEAR_FEATURE_MASK) != 0 &&
471         !bdrv_is_read_only(bs->file->bs) && !(flags & BDRV_O_INACTIVE)) {
472         s->header.autoclear_features &= QED_AUTOCLEAR_FEATURE_MASK;
473 
474         ret = qed_write_header_sync(s);
475         if (ret) {
476             return ret;
477         }
478 
479         /* From here on only known autoclear feature bits are valid */
480         bdrv_flush(bs->file->bs);
481     }
482 
483     s->l1_table = qed_alloc_table(s);
484     qed_init_l2_cache(&s->l2_cache);
485 
486     ret = qed_read_l1_table_sync(s);
487     if (ret) {
488         goto out;
489     }
490 
491     /* If image was not closed cleanly, check consistency */
492     if (!(flags & BDRV_O_CHECK) && (s->header.features & QED_F_NEED_CHECK)) {
493         /* Read-only images cannot be fixed.  There is no risk of corruption
494          * since write operations are not possible.  Therefore, allow
495          * potentially inconsistent images to be opened read-only.  This can
496          * aid data recovery from an otherwise inconsistent image.
497          */
498         if (!bdrv_is_read_only(bs->file->bs) &&
499             !(flags & BDRV_O_INACTIVE)) {
500             BdrvCheckResult result = {0};
501 
502             ret = qed_check(s, &result, true);
503             if (ret) {
504                 goto out;
505             }
506         }
507     }
508 
509     bdrv_qed_attach_aio_context(bs, bdrv_get_aio_context(bs));
510 
511 out:
512     if (ret) {
513         qed_free_l2_cache(&s->l2_cache);
514         qemu_vfree(s->l1_table);
515     }
516     return ret;
517 }
518 
519 typedef struct QEDOpenCo {
520     BlockDriverState *bs;
521     QDict *options;
522     int flags;
523     Error **errp;
524     int ret;
525 } QEDOpenCo;
526 
527 static void coroutine_fn bdrv_qed_open_entry(void *opaque)
528 {
529     QEDOpenCo *qoc = opaque;
530     BDRVQEDState *s = qoc->bs->opaque;
531 
532     qemu_co_mutex_lock(&s->table_lock);
533     qoc->ret = bdrv_qed_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
534     qemu_co_mutex_unlock(&s->table_lock);
535 }
536 
537 static int bdrv_qed_open(BlockDriverState *bs, QDict *options, int flags,
538                          Error **errp)
539 {
540     QEDOpenCo qoc = {
541         .bs = bs,
542         .options = options,
543         .flags = flags,
544         .errp = errp,
545         .ret = -EINPROGRESS
546     };
547 
548     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
549                                false, errp);
550     if (!bs->file) {
551         return -EINVAL;
552     }
553 
554     bdrv_qed_init_state(bs);
555     if (qemu_in_coroutine()) {
556         bdrv_qed_open_entry(&qoc);
557     } else {
558         assert(qemu_get_current_aio_context() == qemu_get_aio_context());
559         qemu_coroutine_enter(qemu_coroutine_create(bdrv_qed_open_entry, &qoc));
560         BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
561     }
562     BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
563     return qoc.ret;
564 }
565 
566 static void bdrv_qed_refresh_limits(BlockDriverState *bs, Error **errp)
567 {
568     BDRVQEDState *s = bs->opaque;
569 
570     bs->bl.pwrite_zeroes_alignment = s->header.cluster_size;
571 }
572 
573 /* We have nothing to do for QED reopen, stubs just return
574  * success */
575 static int bdrv_qed_reopen_prepare(BDRVReopenState *state,
576                                    BlockReopenQueue *queue, Error **errp)
577 {
578     return 0;
579 }
580 
581 static void bdrv_qed_close(BlockDriverState *bs)
582 {
583     BDRVQEDState *s = bs->opaque;
584 
585     bdrv_qed_detach_aio_context(bs);
586 
587     /* Ensure writes reach stable storage */
588     bdrv_flush(bs->file->bs);
589 
590     /* Clean shutdown, no check required on next open */
591     if (s->header.features & QED_F_NEED_CHECK) {
592         s->header.features &= ~QED_F_NEED_CHECK;
593         qed_write_header_sync(s);
594     }
595 
596     qed_free_l2_cache(&s->l2_cache);
597     qemu_vfree(s->l1_table);
598 }
599 
600 static int coroutine_fn bdrv_qed_co_create(BlockdevCreateOptions *opts,
601                                            Error **errp)
602 {
603     BlockdevCreateOptionsQed *qed_opts;
604     BlockBackend *blk = NULL;
605     BlockDriverState *bs = NULL;
606 
607     QEDHeader header;
608     QEDHeader le_header;
609     uint8_t *l1_table = NULL;
610     size_t l1_size;
611     int ret = 0;
612 
613     assert(opts->driver == BLOCKDEV_DRIVER_QED);
614     qed_opts = &opts->u.qed;
615 
616     /* Validate options and set default values */
617     if (!qed_opts->has_cluster_size) {
618         qed_opts->cluster_size = QED_DEFAULT_CLUSTER_SIZE;
619     }
620     if (!qed_opts->has_table_size) {
621         qed_opts->table_size = QED_DEFAULT_TABLE_SIZE;
622     }
623 
624     if (!qed_is_cluster_size_valid(qed_opts->cluster_size)) {
625         error_setg(errp, "QED cluster size must be within range [%u, %u] "
626                          "and power of 2",
627                    QED_MIN_CLUSTER_SIZE, QED_MAX_CLUSTER_SIZE);
628         return -EINVAL;
629     }
630     if (!qed_is_table_size_valid(qed_opts->table_size)) {
631         error_setg(errp, "QED table size must be within range [%u, %u] "
632                          "and power of 2",
633                    QED_MIN_TABLE_SIZE, QED_MAX_TABLE_SIZE);
634         return -EINVAL;
635     }
636     if (!qed_is_image_size_valid(qed_opts->size, qed_opts->cluster_size,
637                                  qed_opts->table_size))
638     {
639         error_setg(errp, "QED image size must be a non-zero multiple of "
640                          "cluster size and less than %" PRIu64 " bytes",
641                    qed_max_image_size(qed_opts->cluster_size,
642                                       qed_opts->table_size));
643         return -EINVAL;
644     }
645 
646     /* Create BlockBackend to write to the image */
647     bs = bdrv_open_blockdev_ref(qed_opts->file, errp);
648     if (bs == NULL) {
649         return -EIO;
650     }
651 
652     blk = blk_new(bdrv_get_aio_context(bs),
653                   BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
654     ret = blk_insert_bs(blk, bs, errp);
655     if (ret < 0) {
656         goto out;
657     }
658     blk_set_allow_write_beyond_eof(blk, true);
659 
660     /* Prepare image format */
661     header = (QEDHeader) {
662         .magic = QED_MAGIC,
663         .cluster_size = qed_opts->cluster_size,
664         .table_size = qed_opts->table_size,
665         .header_size = 1,
666         .features = 0,
667         .compat_features = 0,
668         .l1_table_offset = qed_opts->cluster_size,
669         .image_size = qed_opts->size,
670     };
671 
672     l1_size = header.cluster_size * header.table_size;
673 
674     /* File must start empty and grow, check truncate is supported */
675     ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
676     if (ret < 0) {
677         goto out;
678     }
679 
680     if (qed_opts->has_backing_file) {
681         header.features |= QED_F_BACKING_FILE;
682         header.backing_filename_offset = sizeof(le_header);
683         header.backing_filename_size = strlen(qed_opts->backing_file);
684 
685         if (qed_opts->has_backing_fmt) {
686             const char *backing_fmt = BlockdevDriver_str(qed_opts->backing_fmt);
687             if (qed_fmt_is_raw(backing_fmt)) {
688                 header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
689             }
690         }
691     }
692 
693     qed_header_cpu_to_le(&header, &le_header);
694     ret = blk_pwrite(blk, 0, &le_header, sizeof(le_header), 0);
695     if (ret < 0) {
696         goto out;
697     }
698     ret = blk_pwrite(blk, sizeof(le_header), qed_opts->backing_file,
699                      header.backing_filename_size, 0);
700     if (ret < 0) {
701         goto out;
702     }
703 
704     l1_table = g_malloc0(l1_size);
705     ret = blk_pwrite(blk, header.l1_table_offset, l1_table, l1_size, 0);
706     if (ret < 0) {
707         goto out;
708     }
709 
710     ret = 0; /* success */
711 out:
712     g_free(l1_table);
713     blk_unref(blk);
714     bdrv_unref(bs);
715     return ret;
716 }
717 
718 static int coroutine_fn bdrv_qed_co_create_opts(const char *filename,
719                                                 QemuOpts *opts,
720                                                 Error **errp)
721 {
722     BlockdevCreateOptions *create_options = NULL;
723     QDict *qdict;
724     Visitor *v;
725     BlockDriverState *bs = NULL;
726     Error *local_err = NULL;
727     int ret;
728 
729     static const QDictRenames opt_renames[] = {
730         { BLOCK_OPT_BACKING_FILE,       "backing-file" },
731         { BLOCK_OPT_BACKING_FMT,        "backing-fmt" },
732         { BLOCK_OPT_CLUSTER_SIZE,       "cluster-size" },
733         { BLOCK_OPT_TABLE_SIZE,         "table-size" },
734         { NULL, NULL },
735     };
736 
737     /* Parse options and convert legacy syntax */
738     qdict = qemu_opts_to_qdict_filtered(opts, NULL, &qed_create_opts, true);
739 
740     if (!qdict_rename_keys(qdict, opt_renames, errp)) {
741         ret = -EINVAL;
742         goto fail;
743     }
744 
745     /* Create and open the file (protocol layer) */
746     ret = bdrv_create_file(filename, opts, &local_err);
747     if (ret < 0) {
748         error_propagate(errp, local_err);
749         goto fail;
750     }
751 
752     bs = bdrv_open(filename, NULL, NULL,
753                    BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
754     if (bs == NULL) {
755         ret = -EIO;
756         goto fail;
757     }
758 
759     /* Now get the QAPI type BlockdevCreateOptions */
760     qdict_put_str(qdict, "driver", "qed");
761     qdict_put_str(qdict, "file", bs->node_name);
762 
763     v = qobject_input_visitor_new_flat_confused(qdict, errp);
764     if (!v) {
765         ret = -EINVAL;
766         goto fail;
767     }
768 
769     visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
770     visit_free(v);
771 
772     if (local_err) {
773         error_propagate(errp, local_err);
774         ret = -EINVAL;
775         goto fail;
776     }
777 
778     /* Silently round up size */
779     assert(create_options->driver == BLOCKDEV_DRIVER_QED);
780     create_options->u.qed.size =
781         ROUND_UP(create_options->u.qed.size, BDRV_SECTOR_SIZE);
782 
783     /* Create the qed image (format layer) */
784     ret = bdrv_qed_co_create(create_options, errp);
785 
786 fail:
787     qobject_unref(qdict);
788     bdrv_unref(bs);
789     qapi_free_BlockdevCreateOptions(create_options);
790     return ret;
791 }
792 
793 static int coroutine_fn bdrv_qed_co_block_status(BlockDriverState *bs,
794                                                  bool want_zero,
795                                                  int64_t pos, int64_t bytes,
796                                                  int64_t *pnum, int64_t *map,
797                                                  BlockDriverState **file)
798 {
799     BDRVQEDState *s = bs->opaque;
800     size_t len = MIN(bytes, SIZE_MAX);
801     int status;
802     QEDRequest request = { .l2_table = NULL };
803     uint64_t offset;
804     int ret;
805 
806     qemu_co_mutex_lock(&s->table_lock);
807     ret = qed_find_cluster(s, &request, pos, &len, &offset);
808 
809     *pnum = len;
810     switch (ret) {
811     case QED_CLUSTER_FOUND:
812         *map = offset | qed_offset_into_cluster(s, pos);
813         status = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
814         *file = bs->file->bs;
815         break;
816     case QED_CLUSTER_ZERO:
817         status = BDRV_BLOCK_ZERO;
818         break;
819     case QED_CLUSTER_L2:
820     case QED_CLUSTER_L1:
821         status = 0;
822         break;
823     default:
824         assert(ret < 0);
825         status = ret;
826         break;
827     }
828 
829     qed_unref_l2_cache_entry(request.l2_table);
830     qemu_co_mutex_unlock(&s->table_lock);
831 
832     return status;
833 }
834 
835 static BDRVQEDState *acb_to_s(QEDAIOCB *acb)
836 {
837     return acb->bs->opaque;
838 }
839 
840 /**
841  * Read from the backing file or zero-fill if no backing file
842  *
843  * @s:              QED state
844  * @pos:            Byte position in device
845  * @qiov:           Destination I/O vector
846  * @backing_qiov:   Possibly shortened copy of qiov, to be allocated here
847  * @cb:             Completion function
848  * @opaque:         User data for completion function
849  *
850  * This function reads qiov->size bytes starting at pos from the backing file.
851  * If there is no backing file then zeroes are read.
852  */
853 static int coroutine_fn qed_read_backing_file(BDRVQEDState *s, uint64_t pos,
854                                               QEMUIOVector *qiov,
855                                               QEMUIOVector **backing_qiov)
856 {
857     uint64_t backing_length = 0;
858     size_t size;
859     int ret;
860 
861     /* If there is a backing file, get its length.  Treat the absence of a
862      * backing file like a zero length backing file.
863      */
864     if (s->bs->backing) {
865         int64_t l = bdrv_getlength(s->bs->backing->bs);
866         if (l < 0) {
867             return l;
868         }
869         backing_length = l;
870     }
871 
872     /* Zero all sectors if reading beyond the end of the backing file */
873     if (pos >= backing_length ||
874         pos + qiov->size > backing_length) {
875         qemu_iovec_memset(qiov, 0, 0, qiov->size);
876     }
877 
878     /* Complete now if there are no backing file sectors to read */
879     if (pos >= backing_length) {
880         return 0;
881     }
882 
883     /* If the read straddles the end of the backing file, shorten it */
884     size = MIN((uint64_t)backing_length - pos, qiov->size);
885 
886     assert(*backing_qiov == NULL);
887     *backing_qiov = g_new(QEMUIOVector, 1);
888     qemu_iovec_init(*backing_qiov, qiov->niov);
889     qemu_iovec_concat(*backing_qiov, qiov, 0, size);
890 
891     BLKDBG_EVENT(s->bs->file, BLKDBG_READ_BACKING_AIO);
892     ret = bdrv_co_preadv(s->bs->backing, pos, size, *backing_qiov, 0);
893     if (ret < 0) {
894         return ret;
895     }
896     return 0;
897 }
898 
899 /**
900  * Copy data from backing file into the image
901  *
902  * @s:          QED state
903  * @pos:        Byte position in device
904  * @len:        Number of bytes
905  * @offset:     Byte offset in image file
906  */
907 static int coroutine_fn qed_copy_from_backing_file(BDRVQEDState *s,
908                                                    uint64_t pos, uint64_t len,
909                                                    uint64_t offset)
910 {
911     QEMUIOVector qiov;
912     QEMUIOVector *backing_qiov = NULL;
913     int ret;
914 
915     /* Skip copy entirely if there is no work to do */
916     if (len == 0) {
917         return 0;
918     }
919 
920     qemu_iovec_init_buf(&qiov, qemu_blockalign(s->bs, len), len);
921 
922     ret = qed_read_backing_file(s, pos, &qiov, &backing_qiov);
923 
924     if (backing_qiov) {
925         qemu_iovec_destroy(backing_qiov);
926         g_free(backing_qiov);
927         backing_qiov = NULL;
928     }
929 
930     if (ret) {
931         goto out;
932     }
933 
934     BLKDBG_EVENT(s->bs->file, BLKDBG_COW_WRITE);
935     ret = bdrv_co_pwritev(s->bs->file, offset, qiov.size, &qiov, 0);
936     if (ret < 0) {
937         goto out;
938     }
939     ret = 0;
940 out:
941     qemu_vfree(qemu_iovec_buf(&qiov));
942     return ret;
943 }
944 
945 /**
946  * Link one or more contiguous clusters into a table
947  *
948  * @s:              QED state
949  * @table:          L2 table
950  * @index:          First cluster index
951  * @n:              Number of contiguous clusters
952  * @cluster:        First cluster offset
953  *
954  * The cluster offset may be an allocated byte offset in the image file, the
955  * zero cluster marker, or the unallocated cluster marker.
956  *
957  * Called with table_lock held.
958  */
959 static void coroutine_fn qed_update_l2_table(BDRVQEDState *s, QEDTable *table,
960                                              int index, unsigned int n,
961                                              uint64_t cluster)
962 {
963     int i;
964     for (i = index; i < index + n; i++) {
965         table->offsets[i] = cluster;
966         if (!qed_offset_is_unalloc_cluster(cluster) &&
967             !qed_offset_is_zero_cluster(cluster)) {
968             cluster += s->header.cluster_size;
969         }
970     }
971 }
972 
973 /* Called with table_lock held.  */
974 static void coroutine_fn qed_aio_complete(QEDAIOCB *acb)
975 {
976     BDRVQEDState *s = acb_to_s(acb);
977 
978     /* Free resources */
979     qemu_iovec_destroy(&acb->cur_qiov);
980     qed_unref_l2_cache_entry(acb->request.l2_table);
981 
982     /* Free the buffer we may have allocated for zero writes */
983     if (acb->flags & QED_AIOCB_ZERO) {
984         qemu_vfree(acb->qiov->iov[0].iov_base);
985         acb->qiov->iov[0].iov_base = NULL;
986     }
987 
988     /* Start next allocating write request waiting behind this one.  Note that
989      * requests enqueue themselves when they first hit an unallocated cluster
990      * but they wait until the entire request is finished before waking up the
991      * next request in the queue.  This ensures that we don't cycle through
992      * requests multiple times but rather finish one at a time completely.
993      */
994     if (acb == s->allocating_acb) {
995         s->allocating_acb = NULL;
996         if (!qemu_co_queue_empty(&s->allocating_write_reqs)) {
997             qemu_co_queue_next(&s->allocating_write_reqs);
998         } else if (s->header.features & QED_F_NEED_CHECK) {
999             qed_start_need_check_timer(s);
1000         }
1001     }
1002 }
1003 
1004 /**
1005  * Update L1 table with new L2 table offset and write it out
1006  *
1007  * Called with table_lock held.
1008  */
1009 static int coroutine_fn qed_aio_write_l1_update(QEDAIOCB *acb)
1010 {
1011     BDRVQEDState *s = acb_to_s(acb);
1012     CachedL2Table *l2_table = acb->request.l2_table;
1013     uint64_t l2_offset = l2_table->offset;
1014     int index, ret;
1015 
1016     index = qed_l1_index(s, acb->cur_pos);
1017     s->l1_table->offsets[index] = l2_table->offset;
1018 
1019     ret = qed_write_l1_table(s, index, 1);
1020 
1021     /* Commit the current L2 table to the cache */
1022     qed_commit_l2_cache_entry(&s->l2_cache, l2_table);
1023 
1024     /* This is guaranteed to succeed because we just committed the entry to the
1025      * cache.
1026      */
1027     acb->request.l2_table = qed_find_l2_cache_entry(&s->l2_cache, l2_offset);
1028     assert(acb->request.l2_table != NULL);
1029 
1030     return ret;
1031 }
1032 
1033 
1034 /**
1035  * Update L2 table with new cluster offsets and write them out
1036  *
1037  * Called with table_lock held.
1038  */
1039 static int coroutine_fn qed_aio_write_l2_update(QEDAIOCB *acb, uint64_t offset)
1040 {
1041     BDRVQEDState *s = acb_to_s(acb);
1042     bool need_alloc = acb->find_cluster_ret == QED_CLUSTER_L1;
1043     int index, ret;
1044 
1045     if (need_alloc) {
1046         qed_unref_l2_cache_entry(acb->request.l2_table);
1047         acb->request.l2_table = qed_new_l2_table(s);
1048     }
1049 
1050     index = qed_l2_index(s, acb->cur_pos);
1051     qed_update_l2_table(s, acb->request.l2_table->table, index, acb->cur_nclusters,
1052                          offset);
1053 
1054     if (need_alloc) {
1055         /* Write out the whole new L2 table */
1056         ret = qed_write_l2_table(s, &acb->request, 0, s->table_nelems, true);
1057         if (ret) {
1058             return ret;
1059         }
1060         return qed_aio_write_l1_update(acb);
1061     } else {
1062         /* Write out only the updated part of the L2 table */
1063         ret = qed_write_l2_table(s, &acb->request, index, acb->cur_nclusters,
1064                                  false);
1065         if (ret) {
1066             return ret;
1067         }
1068     }
1069     return 0;
1070 }
1071 
1072 /**
1073  * Write data to the image file
1074  *
1075  * Called with table_lock *not* held.
1076  */
1077 static int coroutine_fn qed_aio_write_main(QEDAIOCB *acb)
1078 {
1079     BDRVQEDState *s = acb_to_s(acb);
1080     uint64_t offset = acb->cur_cluster +
1081                       qed_offset_into_cluster(s, acb->cur_pos);
1082 
1083     trace_qed_aio_write_main(s, acb, 0, offset, acb->cur_qiov.size);
1084 
1085     BLKDBG_EVENT(s->bs->file, BLKDBG_WRITE_AIO);
1086     return bdrv_co_pwritev(s->bs->file, offset, acb->cur_qiov.size,
1087                            &acb->cur_qiov, 0);
1088 }
1089 
1090 /**
1091  * Populate untouched regions of new data cluster
1092  *
1093  * Called with table_lock held.
1094  */
1095 static int coroutine_fn qed_aio_write_cow(QEDAIOCB *acb)
1096 {
1097     BDRVQEDState *s = acb_to_s(acb);
1098     uint64_t start, len, offset;
1099     int ret;
1100 
1101     qemu_co_mutex_unlock(&s->table_lock);
1102 
1103     /* Populate front untouched region of new data cluster */
1104     start = qed_start_of_cluster(s, acb->cur_pos);
1105     len = qed_offset_into_cluster(s, acb->cur_pos);
1106 
1107     trace_qed_aio_write_prefill(s, acb, start, len, acb->cur_cluster);
1108     ret = qed_copy_from_backing_file(s, start, len, acb->cur_cluster);
1109     if (ret < 0) {
1110         goto out;
1111     }
1112 
1113     /* Populate back untouched region of new data cluster */
1114     start = acb->cur_pos + acb->cur_qiov.size;
1115     len = qed_start_of_cluster(s, start + s->header.cluster_size - 1) - start;
1116     offset = acb->cur_cluster +
1117              qed_offset_into_cluster(s, acb->cur_pos) +
1118              acb->cur_qiov.size;
1119 
1120     trace_qed_aio_write_postfill(s, acb, start, len, offset);
1121     ret = qed_copy_from_backing_file(s, start, len, offset);
1122     if (ret < 0) {
1123         goto out;
1124     }
1125 
1126     ret = qed_aio_write_main(acb);
1127     if (ret < 0) {
1128         goto out;
1129     }
1130 
1131     if (s->bs->backing) {
1132         /*
1133          * Flush new data clusters before updating the L2 table
1134          *
1135          * This flush is necessary when a backing file is in use.  A crash
1136          * during an allocating write could result in empty clusters in the
1137          * image.  If the write only touched a subregion of the cluster,
1138          * then backing image sectors have been lost in the untouched
1139          * region.  The solution is to flush after writing a new data
1140          * cluster and before updating the L2 table.
1141          */
1142         ret = bdrv_co_flush(s->bs->file->bs);
1143     }
1144 
1145 out:
1146     qemu_co_mutex_lock(&s->table_lock);
1147     return ret;
1148 }
1149 
1150 /**
1151  * Check if the QED_F_NEED_CHECK bit should be set during allocating write
1152  */
1153 static bool qed_should_set_need_check(BDRVQEDState *s)
1154 {
1155     /* The flush before L2 update path ensures consistency */
1156     if (s->bs->backing) {
1157         return false;
1158     }
1159 
1160     return !(s->header.features & QED_F_NEED_CHECK);
1161 }
1162 
1163 /**
1164  * Write new data cluster
1165  *
1166  * @acb:        Write request
1167  * @len:        Length in bytes
1168  *
1169  * This path is taken when writing to previously unallocated clusters.
1170  *
1171  * Called with table_lock held.
1172  */
1173 static int coroutine_fn qed_aio_write_alloc(QEDAIOCB *acb, size_t len)
1174 {
1175     BDRVQEDState *s = acb_to_s(acb);
1176     int ret;
1177 
1178     /* Cancel timer when the first allocating request comes in */
1179     if (s->allocating_acb == NULL) {
1180         qed_cancel_need_check_timer(s);
1181     }
1182 
1183     /* Freeze this request if another allocating write is in progress */
1184     if (s->allocating_acb != acb || s->allocating_write_reqs_plugged) {
1185         if (s->allocating_acb != NULL) {
1186             qemu_co_queue_wait(&s->allocating_write_reqs, &s->table_lock);
1187             assert(s->allocating_acb == NULL);
1188         }
1189         s->allocating_acb = acb;
1190         return -EAGAIN; /* start over with looking up table entries */
1191     }
1192 
1193     acb->cur_nclusters = qed_bytes_to_clusters(s,
1194             qed_offset_into_cluster(s, acb->cur_pos) + len);
1195     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1196 
1197     if (acb->flags & QED_AIOCB_ZERO) {
1198         /* Skip ahead if the clusters are already zero */
1199         if (acb->find_cluster_ret == QED_CLUSTER_ZERO) {
1200             return 0;
1201         }
1202         acb->cur_cluster = 1;
1203     } else {
1204         acb->cur_cluster = qed_alloc_clusters(s, acb->cur_nclusters);
1205     }
1206 
1207     if (qed_should_set_need_check(s)) {
1208         s->header.features |= QED_F_NEED_CHECK;
1209         ret = qed_write_header(s);
1210         if (ret < 0) {
1211             return ret;
1212         }
1213     }
1214 
1215     if (!(acb->flags & QED_AIOCB_ZERO)) {
1216         ret = qed_aio_write_cow(acb);
1217         if (ret < 0) {
1218             return ret;
1219         }
1220     }
1221 
1222     return qed_aio_write_l2_update(acb, acb->cur_cluster);
1223 }
1224 
1225 /**
1226  * Write data cluster in place
1227  *
1228  * @acb:        Write request
1229  * @offset:     Cluster offset in bytes
1230  * @len:        Length in bytes
1231  *
1232  * This path is taken when writing to already allocated clusters.
1233  *
1234  * Called with table_lock held.
1235  */
1236 static int coroutine_fn qed_aio_write_inplace(QEDAIOCB *acb, uint64_t offset,
1237                                               size_t len)
1238 {
1239     BDRVQEDState *s = acb_to_s(acb);
1240     int r;
1241 
1242     qemu_co_mutex_unlock(&s->table_lock);
1243 
1244     /* Allocate buffer for zero writes */
1245     if (acb->flags & QED_AIOCB_ZERO) {
1246         struct iovec *iov = acb->qiov->iov;
1247 
1248         if (!iov->iov_base) {
1249             iov->iov_base = qemu_try_blockalign(acb->bs, iov->iov_len);
1250             if (iov->iov_base == NULL) {
1251                 r = -ENOMEM;
1252                 goto out;
1253             }
1254             memset(iov->iov_base, 0, iov->iov_len);
1255         }
1256     }
1257 
1258     /* Calculate the I/O vector */
1259     acb->cur_cluster = offset;
1260     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1261 
1262     /* Do the actual write.  */
1263     r = qed_aio_write_main(acb);
1264 out:
1265     qemu_co_mutex_lock(&s->table_lock);
1266     return r;
1267 }
1268 
1269 /**
1270  * Write data cluster
1271  *
1272  * @opaque:     Write request
1273  * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2 or QED_CLUSTER_L1
1274  * @offset:     Cluster offset in bytes
1275  * @len:        Length in bytes
1276  *
1277  * Called with table_lock held.
1278  */
1279 static int coroutine_fn qed_aio_write_data(void *opaque, int ret,
1280                                            uint64_t offset, size_t len)
1281 {
1282     QEDAIOCB *acb = opaque;
1283 
1284     trace_qed_aio_write_data(acb_to_s(acb), acb, ret, offset, len);
1285 
1286     acb->find_cluster_ret = ret;
1287 
1288     switch (ret) {
1289     case QED_CLUSTER_FOUND:
1290         return qed_aio_write_inplace(acb, offset, len);
1291 
1292     case QED_CLUSTER_L2:
1293     case QED_CLUSTER_L1:
1294     case QED_CLUSTER_ZERO:
1295         return qed_aio_write_alloc(acb, len);
1296 
1297     default:
1298         g_assert_not_reached();
1299     }
1300 }
1301 
1302 /**
1303  * Read data cluster
1304  *
1305  * @opaque:     Read request
1306  * @ret:        QED_CLUSTER_FOUND, QED_CLUSTER_L2 or QED_CLUSTER_L1
1307  * @offset:     Cluster offset in bytes
1308  * @len:        Length in bytes
1309  *
1310  * Called with table_lock held.
1311  */
1312 static int coroutine_fn qed_aio_read_data(void *opaque, int ret,
1313                                           uint64_t offset, size_t len)
1314 {
1315     QEDAIOCB *acb = opaque;
1316     BDRVQEDState *s = acb_to_s(acb);
1317     BlockDriverState *bs = acb->bs;
1318     int r;
1319 
1320     qemu_co_mutex_unlock(&s->table_lock);
1321 
1322     /* Adjust offset into cluster */
1323     offset += qed_offset_into_cluster(s, acb->cur_pos);
1324 
1325     trace_qed_aio_read_data(s, acb, ret, offset, len);
1326 
1327     qemu_iovec_concat(&acb->cur_qiov, acb->qiov, acb->qiov_offset, len);
1328 
1329     /* Handle zero cluster and backing file reads, otherwise read
1330      * data cluster directly.
1331      */
1332     if (ret == QED_CLUSTER_ZERO) {
1333         qemu_iovec_memset(&acb->cur_qiov, 0, 0, acb->cur_qiov.size);
1334         r = 0;
1335     } else if (ret != QED_CLUSTER_FOUND) {
1336         r = qed_read_backing_file(s, acb->cur_pos, &acb->cur_qiov,
1337                                   &acb->backing_qiov);
1338     } else {
1339         BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1340         r = bdrv_co_preadv(bs->file, offset, acb->cur_qiov.size,
1341                            &acb->cur_qiov, 0);
1342     }
1343 
1344     qemu_co_mutex_lock(&s->table_lock);
1345     return r;
1346 }
1347 
1348 /**
1349  * Begin next I/O or complete the request
1350  */
1351 static int coroutine_fn qed_aio_next_io(QEDAIOCB *acb)
1352 {
1353     BDRVQEDState *s = acb_to_s(acb);
1354     uint64_t offset;
1355     size_t len;
1356     int ret;
1357 
1358     qemu_co_mutex_lock(&s->table_lock);
1359     while (1) {
1360         trace_qed_aio_next_io(s, acb, 0, acb->cur_pos + acb->cur_qiov.size);
1361 
1362         if (acb->backing_qiov) {
1363             qemu_iovec_destroy(acb->backing_qiov);
1364             g_free(acb->backing_qiov);
1365             acb->backing_qiov = NULL;
1366         }
1367 
1368         acb->qiov_offset += acb->cur_qiov.size;
1369         acb->cur_pos += acb->cur_qiov.size;
1370         qemu_iovec_reset(&acb->cur_qiov);
1371 
1372         /* Complete request */
1373         if (acb->cur_pos >= acb->end_pos) {
1374             ret = 0;
1375             break;
1376         }
1377 
1378         /* Find next cluster and start I/O */
1379         len = acb->end_pos - acb->cur_pos;
1380         ret = qed_find_cluster(s, &acb->request, acb->cur_pos, &len, &offset);
1381         if (ret < 0) {
1382             break;
1383         }
1384 
1385         if (acb->flags & QED_AIOCB_WRITE) {
1386             ret = qed_aio_write_data(acb, ret, offset, len);
1387         } else {
1388             ret = qed_aio_read_data(acb, ret, offset, len);
1389         }
1390 
1391         if (ret < 0 && ret != -EAGAIN) {
1392             break;
1393         }
1394     }
1395 
1396     trace_qed_aio_complete(s, acb, ret);
1397     qed_aio_complete(acb);
1398     qemu_co_mutex_unlock(&s->table_lock);
1399     return ret;
1400 }
1401 
1402 static int coroutine_fn qed_co_request(BlockDriverState *bs, int64_t sector_num,
1403                                        QEMUIOVector *qiov, int nb_sectors,
1404                                        int flags)
1405 {
1406     QEDAIOCB acb = {
1407         .bs         = bs,
1408         .cur_pos    = (uint64_t) sector_num * BDRV_SECTOR_SIZE,
1409         .end_pos    = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE,
1410         .qiov       = qiov,
1411         .flags      = flags,
1412     };
1413     qemu_iovec_init(&acb.cur_qiov, qiov->niov);
1414 
1415     trace_qed_aio_setup(bs->opaque, &acb, sector_num, nb_sectors, NULL, flags);
1416 
1417     /* Start request */
1418     return qed_aio_next_io(&acb);
1419 }
1420 
1421 static int coroutine_fn bdrv_qed_co_readv(BlockDriverState *bs,
1422                                           int64_t sector_num, int nb_sectors,
1423                                           QEMUIOVector *qiov)
1424 {
1425     return qed_co_request(bs, sector_num, qiov, nb_sectors, 0);
1426 }
1427 
1428 static int coroutine_fn bdrv_qed_co_writev(BlockDriverState *bs,
1429                                            int64_t sector_num, int nb_sectors,
1430                                            QEMUIOVector *qiov, int flags)
1431 {
1432     assert(!flags);
1433     return qed_co_request(bs, sector_num, qiov, nb_sectors, QED_AIOCB_WRITE);
1434 }
1435 
1436 static int coroutine_fn bdrv_qed_co_pwrite_zeroes(BlockDriverState *bs,
1437                                                   int64_t offset,
1438                                                   int bytes,
1439                                                   BdrvRequestFlags flags)
1440 {
1441     BDRVQEDState *s = bs->opaque;
1442 
1443     /*
1444      * Zero writes start without an I/O buffer.  If a buffer becomes necessary
1445      * then it will be allocated during request processing.
1446      */
1447     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, NULL, bytes);
1448 
1449     /* Fall back if the request is not aligned */
1450     if (qed_offset_into_cluster(s, offset) ||
1451         qed_offset_into_cluster(s, bytes)) {
1452         return -ENOTSUP;
1453     }
1454 
1455     return qed_co_request(bs, offset >> BDRV_SECTOR_BITS, &qiov,
1456                           bytes >> BDRV_SECTOR_BITS,
1457                           QED_AIOCB_WRITE | QED_AIOCB_ZERO);
1458 }
1459 
1460 static int coroutine_fn bdrv_qed_co_truncate(BlockDriverState *bs,
1461                                              int64_t offset,
1462                                              PreallocMode prealloc,
1463                                              Error **errp)
1464 {
1465     BDRVQEDState *s = bs->opaque;
1466     uint64_t old_image_size;
1467     int ret;
1468 
1469     if (prealloc != PREALLOC_MODE_OFF) {
1470         error_setg(errp, "Unsupported preallocation mode '%s'",
1471                    PreallocMode_str(prealloc));
1472         return -ENOTSUP;
1473     }
1474 
1475     if (!qed_is_image_size_valid(offset, s->header.cluster_size,
1476                                  s->header.table_size)) {
1477         error_setg(errp, "Invalid image size specified");
1478         return -EINVAL;
1479     }
1480 
1481     if ((uint64_t)offset < s->header.image_size) {
1482         error_setg(errp, "Shrinking images is currently not supported");
1483         return -ENOTSUP;
1484     }
1485 
1486     old_image_size = s->header.image_size;
1487     s->header.image_size = offset;
1488     ret = qed_write_header_sync(s);
1489     if (ret < 0) {
1490         s->header.image_size = old_image_size;
1491         error_setg_errno(errp, -ret, "Failed to update the image size");
1492     }
1493     return ret;
1494 }
1495 
1496 static int64_t bdrv_qed_getlength(BlockDriverState *bs)
1497 {
1498     BDRVQEDState *s = bs->opaque;
1499     return s->header.image_size;
1500 }
1501 
1502 static int bdrv_qed_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1503 {
1504     BDRVQEDState *s = bs->opaque;
1505 
1506     memset(bdi, 0, sizeof(*bdi));
1507     bdi->cluster_size = s->header.cluster_size;
1508     bdi->is_dirty = s->header.features & QED_F_NEED_CHECK;
1509     bdi->unallocated_blocks_are_zero = true;
1510     return 0;
1511 }
1512 
1513 static int bdrv_qed_change_backing_file(BlockDriverState *bs,
1514                                         const char *backing_file,
1515                                         const char *backing_fmt)
1516 {
1517     BDRVQEDState *s = bs->opaque;
1518     QEDHeader new_header, le_header;
1519     void *buffer;
1520     size_t buffer_len, backing_file_len;
1521     int ret;
1522 
1523     /* Refuse to set backing filename if unknown compat feature bits are
1524      * active.  If the image uses an unknown compat feature then we may not
1525      * know the layout of data following the header structure and cannot safely
1526      * add a new string.
1527      */
1528     if (backing_file && (s->header.compat_features &
1529                          ~QED_COMPAT_FEATURE_MASK)) {
1530         return -ENOTSUP;
1531     }
1532 
1533     memcpy(&new_header, &s->header, sizeof(new_header));
1534 
1535     new_header.features &= ~(QED_F_BACKING_FILE |
1536                              QED_F_BACKING_FORMAT_NO_PROBE);
1537 
1538     /* Adjust feature flags */
1539     if (backing_file) {
1540         new_header.features |= QED_F_BACKING_FILE;
1541 
1542         if (qed_fmt_is_raw(backing_fmt)) {
1543             new_header.features |= QED_F_BACKING_FORMAT_NO_PROBE;
1544         }
1545     }
1546 
1547     /* Calculate new header size */
1548     backing_file_len = 0;
1549 
1550     if (backing_file) {
1551         backing_file_len = strlen(backing_file);
1552     }
1553 
1554     buffer_len = sizeof(new_header);
1555     new_header.backing_filename_offset = buffer_len;
1556     new_header.backing_filename_size = backing_file_len;
1557     buffer_len += backing_file_len;
1558 
1559     /* Make sure we can rewrite header without failing */
1560     if (buffer_len > new_header.header_size * new_header.cluster_size) {
1561         return -ENOSPC;
1562     }
1563 
1564     /* Prepare new header */
1565     buffer = g_malloc(buffer_len);
1566 
1567     qed_header_cpu_to_le(&new_header, &le_header);
1568     memcpy(buffer, &le_header, sizeof(le_header));
1569     buffer_len = sizeof(le_header);
1570 
1571     if (backing_file) {
1572         memcpy(buffer + buffer_len, backing_file, backing_file_len);
1573         buffer_len += backing_file_len;
1574     }
1575 
1576     /* Write new header */
1577     ret = bdrv_pwrite_sync(bs->file, 0, buffer, buffer_len);
1578     g_free(buffer);
1579     if (ret == 0) {
1580         memcpy(&s->header, &new_header, sizeof(new_header));
1581     }
1582     return ret;
1583 }
1584 
1585 static void coroutine_fn bdrv_qed_co_invalidate_cache(BlockDriverState *bs,
1586                                                       Error **errp)
1587 {
1588     BDRVQEDState *s = bs->opaque;
1589     Error *local_err = NULL;
1590     int ret;
1591 
1592     bdrv_qed_close(bs);
1593 
1594     bdrv_qed_init_state(bs);
1595     qemu_co_mutex_lock(&s->table_lock);
1596     ret = bdrv_qed_do_open(bs, NULL, bs->open_flags, &local_err);
1597     qemu_co_mutex_unlock(&s->table_lock);
1598     if (local_err) {
1599         error_propagate_prepend(errp, local_err,
1600                                 "Could not reopen qed layer: ");
1601         return;
1602     } else if (ret < 0) {
1603         error_setg_errno(errp, -ret, "Could not reopen qed layer");
1604         return;
1605     }
1606 }
1607 
1608 static int coroutine_fn bdrv_qed_co_check(BlockDriverState *bs,
1609                                           BdrvCheckResult *result,
1610                                           BdrvCheckMode fix)
1611 {
1612     BDRVQEDState *s = bs->opaque;
1613     int ret;
1614 
1615     qemu_co_mutex_lock(&s->table_lock);
1616     ret = qed_check(s, result, !!fix);
1617     qemu_co_mutex_unlock(&s->table_lock);
1618 
1619     return ret;
1620 }
1621 
1622 static QemuOptsList qed_create_opts = {
1623     .name = "qed-create-opts",
1624     .head = QTAILQ_HEAD_INITIALIZER(qed_create_opts.head),
1625     .desc = {
1626         {
1627             .name = BLOCK_OPT_SIZE,
1628             .type = QEMU_OPT_SIZE,
1629             .help = "Virtual disk size"
1630         },
1631         {
1632             .name = BLOCK_OPT_BACKING_FILE,
1633             .type = QEMU_OPT_STRING,
1634             .help = "File name of a base image"
1635         },
1636         {
1637             .name = BLOCK_OPT_BACKING_FMT,
1638             .type = QEMU_OPT_STRING,
1639             .help = "Image format of the base image"
1640         },
1641         {
1642             .name = BLOCK_OPT_CLUSTER_SIZE,
1643             .type = QEMU_OPT_SIZE,
1644             .help = "Cluster size (in bytes)",
1645             .def_value_str = stringify(QED_DEFAULT_CLUSTER_SIZE)
1646         },
1647         {
1648             .name = BLOCK_OPT_TABLE_SIZE,
1649             .type = QEMU_OPT_SIZE,
1650             .help = "L1/L2 table size (in clusters)"
1651         },
1652         { /* end of list */ }
1653     }
1654 };
1655 
1656 static BlockDriver bdrv_qed = {
1657     .format_name              = "qed",
1658     .instance_size            = sizeof(BDRVQEDState),
1659     .create_opts              = &qed_create_opts,
1660     .supports_backing         = true,
1661 
1662     .bdrv_probe               = bdrv_qed_probe,
1663     .bdrv_open                = bdrv_qed_open,
1664     .bdrv_close               = bdrv_qed_close,
1665     .bdrv_reopen_prepare      = bdrv_qed_reopen_prepare,
1666     .bdrv_child_perm          = bdrv_format_default_perms,
1667     .bdrv_co_create           = bdrv_qed_co_create,
1668     .bdrv_co_create_opts      = bdrv_qed_co_create_opts,
1669     .bdrv_has_zero_init       = bdrv_has_zero_init_1,
1670     .bdrv_co_block_status     = bdrv_qed_co_block_status,
1671     .bdrv_co_readv            = bdrv_qed_co_readv,
1672     .bdrv_co_writev           = bdrv_qed_co_writev,
1673     .bdrv_co_pwrite_zeroes    = bdrv_qed_co_pwrite_zeroes,
1674     .bdrv_co_truncate         = bdrv_qed_co_truncate,
1675     .bdrv_getlength           = bdrv_qed_getlength,
1676     .bdrv_get_info            = bdrv_qed_get_info,
1677     .bdrv_refresh_limits      = bdrv_qed_refresh_limits,
1678     .bdrv_change_backing_file = bdrv_qed_change_backing_file,
1679     .bdrv_co_invalidate_cache = bdrv_qed_co_invalidate_cache,
1680     .bdrv_co_check            = bdrv_qed_co_check,
1681     .bdrv_detach_aio_context  = bdrv_qed_detach_aio_context,
1682     .bdrv_attach_aio_context  = bdrv_qed_attach_aio_context,
1683     .bdrv_co_drain_begin      = bdrv_qed_co_drain_begin,
1684 };
1685 
1686 static void bdrv_qed_init(void)
1687 {
1688     bdrv_register(&bdrv_qed);
1689 }
1690 
1691 block_init(bdrv_qed_init);
1692