xref: /openbmc/qemu/block/nvme.c (revision 784155cd)
1 /*
2  * NVMe block driver based on vfio
3  *
4  * Copyright 2016 - 2018 Red Hat, Inc.
5  *
6  * Authors:
7  *   Fam Zheng <famz@redhat.com>
8  *   Paolo Bonzini <pbonzini@redhat.com>
9  *
10  * This work is licensed under the terms of the GNU GPL, version 2 or later.
11  * See the COPYING file in the top-level directory.
12  */
13 
14 #include "qemu/osdep.h"
15 #include <linux/vfio.h>
16 #include "qapi/error.h"
17 #include "qapi/qmp/qdict.h"
18 #include "qapi/qmp/qstring.h"
19 #include "qemu/error-report.h"
20 #include "qemu/main-loop.h"
21 #include "qemu/module.h"
22 #include "qemu/cutils.h"
23 #include "qemu/option.h"
24 #include "qemu/memalign.h"
25 #include "qemu/vfio-helpers.h"
26 #include "block/block-io.h"
27 #include "block/block_int.h"
28 #include "sysemu/block-backend.h"
29 #include "sysemu/replay.h"
30 #include "trace.h"
31 
32 #include "block/nvme.h"
33 
34 #define NVME_SQ_ENTRY_BYTES 64
35 #define NVME_CQ_ENTRY_BYTES 16
36 #define NVME_QUEUE_SIZE 128
37 #define NVME_DOORBELL_SIZE 4096
38 
39 /*
40  * We have to leave one slot empty as that is the full queue case where
41  * head == tail + 1.
42  */
43 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
44 
45 typedef struct BDRVNVMeState BDRVNVMeState;
46 
47 /* Same index is used for queues and IRQs */
48 #define INDEX_ADMIN     0
49 #define INDEX_IO(n)     (1 + n)
50 
51 /* This driver shares a single MSIX IRQ for the admin and I/O queues */
52 enum {
53     MSIX_SHARED_IRQ_IDX = 0,
54     MSIX_IRQ_COUNT = 1
55 };
56 
57 typedef struct {
58     int32_t  head, tail;
59     uint8_t  *queue;
60     uint64_t iova;
61     /* Hardware MMIO register */
62     volatile uint32_t *doorbell;
63 } NVMeQueue;
64 
65 typedef struct {
66     BlockCompletionFunc *cb;
67     void *opaque;
68     int cid;
69     void *prp_list_page;
70     uint64_t prp_list_iova;
71     int free_req_next; /* q->reqs[] index of next free req */
72 } NVMeRequest;
73 
74 typedef struct {
75     QemuMutex   lock;
76 
77     /* Read from I/O code path, initialized under BQL */
78     BDRVNVMeState   *s;
79     int             index;
80 
81     /* Fields protected by BQL */
82     uint8_t     *prp_list_pages;
83 
84     /* Fields protected by @lock */
85     CoQueue     free_req_queue;
86     NVMeQueue   sq, cq;
87     int         cq_phase;
88     int         free_req_head;
89     NVMeRequest reqs[NVME_NUM_REQS];
90     int         need_kick;
91     int         inflight;
92 
93     /* Thread-safe, no lock necessary */
94     QEMUBH      *completion_bh;
95 } NVMeQueuePair;
96 
97 struct BDRVNVMeState {
98     AioContext *aio_context;
99     QEMUVFIOState *vfio;
100     void *bar0_wo_map;
101     /* Memory mapped registers */
102     volatile struct {
103         uint32_t sq_tail;
104         uint32_t cq_head;
105     } *doorbells;
106     /* The submission/completion queue pairs.
107      * [0]: admin queue.
108      * [1..]: io queues.
109      */
110     NVMeQueuePair **queues;
111     unsigned queue_count;
112     size_t page_size;
113     /* How many uint32_t elements does each doorbell entry take. */
114     size_t doorbell_scale;
115     bool write_cache_supported;
116     EventNotifier irq_notifier[MSIX_IRQ_COUNT];
117 
118     uint64_t nsze; /* Namespace size reported by identify command */
119     int nsid;      /* The namespace id to read/write data. */
120     int blkshift;
121 
122     uint64_t max_transfer;
123 
124     bool supports_write_zeroes;
125     bool supports_discard;
126 
127     CoMutex dma_map_lock;
128     CoQueue dma_flush_queue;
129 
130     /* Total size of mapped qiov, accessed under dma_map_lock */
131     int dma_map_count;
132 
133     /* PCI address (required for nvme_refresh_filename()) */
134     char *device;
135 
136     struct {
137         uint64_t completion_errors;
138         uint64_t aligned_accesses;
139         uint64_t unaligned_accesses;
140     } stats;
141 };
142 
143 #define NVME_BLOCK_OPT_DEVICE "device"
144 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
145 
146 static void nvme_process_completion_bh(void *opaque);
147 
148 static QemuOptsList runtime_opts = {
149     .name = "nvme",
150     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
151     .desc = {
152         {
153             .name = NVME_BLOCK_OPT_DEVICE,
154             .type = QEMU_OPT_STRING,
155             .help = "NVMe PCI device address",
156         },
157         {
158             .name = NVME_BLOCK_OPT_NAMESPACE,
159             .type = QEMU_OPT_NUMBER,
160             .help = "NVMe namespace",
161         },
162         { /* end of list */ }
163     },
164 };
165 
166 /* Returns true on success, false on failure. */
167 static bool nvme_init_queue(BDRVNVMeState *s, NVMeQueue *q,
168                             unsigned nentries, size_t entry_bytes, Error **errp)
169 {
170     size_t bytes;
171     int r;
172 
173     bytes = ROUND_UP(nentries * entry_bytes, qemu_real_host_page_size());
174     q->head = q->tail = 0;
175     q->queue = qemu_try_memalign(qemu_real_host_page_size(), bytes);
176     if (!q->queue) {
177         error_setg(errp, "Cannot allocate queue");
178         return false;
179     }
180     memset(q->queue, 0, bytes);
181     r = qemu_vfio_dma_map(s->vfio, q->queue, bytes, false, &q->iova, errp);
182     if (r) {
183         error_prepend(errp, "Cannot map queue: ");
184     }
185     return r == 0;
186 }
187 
188 static void nvme_free_queue(NVMeQueue *q)
189 {
190     qemu_vfree(q->queue);
191 }
192 
193 static void nvme_free_queue_pair(NVMeQueuePair *q)
194 {
195     trace_nvme_free_queue_pair(q->index, q, &q->cq, &q->sq);
196     if (q->completion_bh) {
197         qemu_bh_delete(q->completion_bh);
198     }
199     nvme_free_queue(&q->sq);
200     nvme_free_queue(&q->cq);
201     qemu_vfree(q->prp_list_pages);
202     qemu_mutex_destroy(&q->lock);
203     g_free(q);
204 }
205 
206 static void nvme_free_req_queue_cb(void *opaque)
207 {
208     NVMeQueuePair *q = opaque;
209 
210     qemu_mutex_lock(&q->lock);
211     while (q->free_req_head != -1 &&
212            qemu_co_enter_next(&q->free_req_queue, &q->lock)) {
213         /* Retry waiting requests */
214     }
215     qemu_mutex_unlock(&q->lock);
216 }
217 
218 static NVMeQueuePair *nvme_create_queue_pair(BDRVNVMeState *s,
219                                              AioContext *aio_context,
220                                              unsigned idx, size_t size,
221                                              Error **errp)
222 {
223     int i, r;
224     NVMeQueuePair *q;
225     uint64_t prp_list_iova;
226     size_t bytes;
227 
228     q = g_try_new0(NVMeQueuePair, 1);
229     if (!q) {
230         error_setg(errp, "Cannot allocate queue pair");
231         return NULL;
232     }
233     trace_nvme_create_queue_pair(idx, q, size, aio_context,
234                                  event_notifier_get_fd(s->irq_notifier));
235     bytes = QEMU_ALIGN_UP(s->page_size * NVME_NUM_REQS,
236                           qemu_real_host_page_size());
237     q->prp_list_pages = qemu_try_memalign(qemu_real_host_page_size(), bytes);
238     if (!q->prp_list_pages) {
239         error_setg(errp, "Cannot allocate PRP page list");
240         goto fail;
241     }
242     memset(q->prp_list_pages, 0, bytes);
243     qemu_mutex_init(&q->lock);
244     q->s = s;
245     q->index = idx;
246     qemu_co_queue_init(&q->free_req_queue);
247     q->completion_bh = aio_bh_new(aio_context, nvme_process_completion_bh, q);
248     r = qemu_vfio_dma_map(s->vfio, q->prp_list_pages, bytes,
249                           false, &prp_list_iova, errp);
250     if (r) {
251         error_prepend(errp, "Cannot map buffer for DMA: ");
252         goto fail;
253     }
254     q->free_req_head = -1;
255     for (i = 0; i < NVME_NUM_REQS; i++) {
256         NVMeRequest *req = &q->reqs[i];
257         req->cid = i + 1;
258         req->free_req_next = q->free_req_head;
259         q->free_req_head = i;
260         req->prp_list_page = q->prp_list_pages + i * s->page_size;
261         req->prp_list_iova = prp_list_iova + i * s->page_size;
262     }
263 
264     if (!nvme_init_queue(s, &q->sq, size, NVME_SQ_ENTRY_BYTES, errp)) {
265         goto fail;
266     }
267     q->sq.doorbell = &s->doorbells[idx * s->doorbell_scale].sq_tail;
268 
269     if (!nvme_init_queue(s, &q->cq, size, NVME_CQ_ENTRY_BYTES, errp)) {
270         goto fail;
271     }
272     q->cq.doorbell = &s->doorbells[idx * s->doorbell_scale].cq_head;
273 
274     return q;
275 fail:
276     nvme_free_queue_pair(q);
277     return NULL;
278 }
279 
280 /* With q->lock */
281 static void nvme_kick(NVMeQueuePair *q)
282 {
283     BDRVNVMeState *s = q->s;
284 
285     if (!q->need_kick) {
286         return;
287     }
288     trace_nvme_kick(s, q->index);
289     assert(!(q->sq.tail & 0xFF00));
290     /* Fence the write to submission queue entry before notifying the device. */
291     smp_wmb();
292     *q->sq.doorbell = cpu_to_le32(q->sq.tail);
293     q->inflight += q->need_kick;
294     q->need_kick = 0;
295 }
296 
297 static NVMeRequest *nvme_get_free_req_nofail_locked(NVMeQueuePair *q)
298 {
299     NVMeRequest *req;
300 
301     req = &q->reqs[q->free_req_head];
302     q->free_req_head = req->free_req_next;
303     req->free_req_next = -1;
304     return req;
305 }
306 
307 /* Return a free request element if any, otherwise return NULL.  */
308 static NVMeRequest *nvme_get_free_req_nowait(NVMeQueuePair *q)
309 {
310     QEMU_LOCK_GUARD(&q->lock);
311     if (q->free_req_head == -1) {
312         return NULL;
313     }
314     return nvme_get_free_req_nofail_locked(q);
315 }
316 
317 /*
318  * Wait for a free request to become available if necessary, then
319  * return it.
320  */
321 static coroutine_fn NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
322 {
323     QEMU_LOCK_GUARD(&q->lock);
324 
325     while (q->free_req_head == -1) {
326         trace_nvme_free_req_queue_wait(q->s, q->index);
327         qemu_co_queue_wait(&q->free_req_queue, &q->lock);
328     }
329 
330     return nvme_get_free_req_nofail_locked(q);
331 }
332 
333 /* With q->lock */
334 static void nvme_put_free_req_locked(NVMeQueuePair *q, NVMeRequest *req)
335 {
336     req->free_req_next = q->free_req_head;
337     q->free_req_head = req - q->reqs;
338 }
339 
340 /* With q->lock */
341 static void nvme_wake_free_req_locked(NVMeQueuePair *q)
342 {
343     if (!qemu_co_queue_empty(&q->free_req_queue)) {
344         replay_bh_schedule_oneshot_event(q->s->aio_context,
345                 nvme_free_req_queue_cb, q);
346     }
347 }
348 
349 /* Insert a request in the freelist and wake waiters */
350 static void nvme_put_free_req_and_wake(NVMeQueuePair *q, NVMeRequest *req)
351 {
352     qemu_mutex_lock(&q->lock);
353     nvme_put_free_req_locked(q, req);
354     nvme_wake_free_req_locked(q);
355     qemu_mutex_unlock(&q->lock);
356 }
357 
358 static inline int nvme_translate_error(const NvmeCqe *c)
359 {
360     uint16_t status = (le16_to_cpu(c->status) >> 1) & 0xFF;
361     if (status) {
362         trace_nvme_error(le32_to_cpu(c->result),
363                          le16_to_cpu(c->sq_head),
364                          le16_to_cpu(c->sq_id),
365                          le16_to_cpu(c->cid),
366                          le16_to_cpu(status));
367     }
368     switch (status) {
369     case 0:
370         return 0;
371     case 1:
372         return -ENOSYS;
373     case 2:
374         return -EINVAL;
375     default:
376         return -EIO;
377     }
378 }
379 
380 /* With q->lock */
381 static bool nvme_process_completion(NVMeQueuePair *q)
382 {
383     BDRVNVMeState *s = q->s;
384     bool progress = false;
385     NVMeRequest *preq;
386     NVMeRequest req;
387     NvmeCqe *c;
388 
389     trace_nvme_process_completion(s, q->index, q->inflight);
390 
391     /*
392      * Support re-entrancy when a request cb() function invokes aio_poll().
393      * Pending completions must be visible to aio_poll() so that a cb()
394      * function can wait for the completion of another request.
395      *
396      * The aio_poll() loop will execute our BH and we'll resume completion
397      * processing there.
398      */
399     qemu_bh_schedule(q->completion_bh);
400 
401     assert(q->inflight >= 0);
402     while (q->inflight) {
403         int ret;
404         int16_t cid;
405 
406         c = (NvmeCqe *)&q->cq.queue[q->cq.head * NVME_CQ_ENTRY_BYTES];
407         if ((le16_to_cpu(c->status) & 0x1) == q->cq_phase) {
408             break;
409         }
410         ret = nvme_translate_error(c);
411         if (ret) {
412             s->stats.completion_errors++;
413         }
414         q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
415         if (!q->cq.head) {
416             q->cq_phase = !q->cq_phase;
417         }
418         cid = le16_to_cpu(c->cid);
419         if (cid == 0 || cid > NVME_QUEUE_SIZE) {
420             warn_report("NVMe: Unexpected CID in completion queue: %"PRIu32", "
421                         "queue size: %u", cid, NVME_QUEUE_SIZE);
422             continue;
423         }
424         trace_nvme_complete_command(s, q->index, cid);
425         preq = &q->reqs[cid - 1];
426         req = *preq;
427         assert(req.cid == cid);
428         assert(req.cb);
429         nvme_put_free_req_locked(q, preq);
430         preq->cb = preq->opaque = NULL;
431         q->inflight--;
432         qemu_mutex_unlock(&q->lock);
433         req.cb(req.opaque, ret);
434         qemu_mutex_lock(&q->lock);
435         progress = true;
436     }
437     if (progress) {
438         /* Notify the device so it can post more completions. */
439         smp_mb_release();
440         *q->cq.doorbell = cpu_to_le32(q->cq.head);
441         nvme_wake_free_req_locked(q);
442     }
443 
444     qemu_bh_cancel(q->completion_bh);
445 
446     return progress;
447 }
448 
449 static void nvme_process_completion_bh(void *opaque)
450 {
451     NVMeQueuePair *q = opaque;
452 
453     /*
454      * We're being invoked because a nvme_process_completion() cb() function
455      * called aio_poll(). The callback may be waiting for further completions
456      * so notify the device that it has space to fill in more completions now.
457      */
458     smp_mb_release();
459     *q->cq.doorbell = cpu_to_le32(q->cq.head);
460     nvme_wake_free_req_locked(q);
461 
462     nvme_process_completion(q);
463 }
464 
465 static void nvme_trace_command(const NvmeCmd *cmd)
466 {
467     int i;
468 
469     if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW)) {
470         return;
471     }
472     for (i = 0; i < 8; ++i) {
473         uint8_t *cmdp = (uint8_t *)cmd + i * 8;
474         trace_nvme_submit_command_raw(cmdp[0], cmdp[1], cmdp[2], cmdp[3],
475                                       cmdp[4], cmdp[5], cmdp[6], cmdp[7]);
476     }
477 }
478 
479 static void nvme_unplug_fn(void *opaque)
480 {
481     NVMeQueuePair *q = opaque;
482 
483     QEMU_LOCK_GUARD(&q->lock);
484     nvme_kick(q);
485     nvme_process_completion(q);
486 }
487 
488 static void nvme_submit_command(NVMeQueuePair *q, NVMeRequest *req,
489                                 NvmeCmd *cmd, BlockCompletionFunc cb,
490                                 void *opaque)
491 {
492     assert(!req->cb);
493     req->cb = cb;
494     req->opaque = opaque;
495     cmd->cid = cpu_to_le16(req->cid);
496 
497     trace_nvme_submit_command(q->s, q->index, req->cid);
498     nvme_trace_command(cmd);
499     qemu_mutex_lock(&q->lock);
500     memcpy((uint8_t *)q->sq.queue +
501            q->sq.tail * NVME_SQ_ENTRY_BYTES, cmd, sizeof(*cmd));
502     q->sq.tail = (q->sq.tail + 1) % NVME_QUEUE_SIZE;
503     q->need_kick++;
504     qemu_mutex_unlock(&q->lock);
505 
506     blk_io_plug_call(nvme_unplug_fn, q);
507 }
508 
509 static void nvme_admin_cmd_sync_cb(void *opaque, int ret)
510 {
511     int *pret = opaque;
512     *pret = ret;
513     aio_wait_kick();
514 }
515 
516 static int nvme_admin_cmd_sync(BlockDriverState *bs, NvmeCmd *cmd)
517 {
518     BDRVNVMeState *s = bs->opaque;
519     NVMeQueuePair *q = s->queues[INDEX_ADMIN];
520     AioContext *aio_context = bdrv_get_aio_context(bs);
521     NVMeRequest *req;
522     int ret = -EINPROGRESS;
523     req = nvme_get_free_req_nowait(q);
524     if (!req) {
525         return -EBUSY;
526     }
527     nvme_submit_command(q, req, cmd, nvme_admin_cmd_sync_cb, &ret);
528 
529     AIO_WAIT_WHILE(aio_context, ret == -EINPROGRESS);
530     return ret;
531 }
532 
533 /* Returns true on success, false on failure. */
534 static bool nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
535 {
536     BDRVNVMeState *s = bs->opaque;
537     bool ret = false;
538     QEMU_AUTO_VFREE union {
539         NvmeIdCtrl ctrl;
540         NvmeIdNs ns;
541     } *id = NULL;
542     NvmeLBAF *lbaf;
543     uint16_t oncs;
544     int r;
545     uint64_t iova;
546     NvmeCmd cmd = {
547         .opcode = NVME_ADM_CMD_IDENTIFY,
548         .cdw10 = cpu_to_le32(0x1),
549     };
550     size_t id_size = QEMU_ALIGN_UP(sizeof(*id), qemu_real_host_page_size());
551 
552     id = qemu_try_memalign(qemu_real_host_page_size(), id_size);
553     if (!id) {
554         error_setg(errp, "Cannot allocate buffer for identify response");
555         goto out;
556     }
557     r = qemu_vfio_dma_map(s->vfio, id, id_size, true, &iova, errp);
558     if (r) {
559         error_prepend(errp, "Cannot map buffer for DMA: ");
560         goto out;
561     }
562 
563     memset(id, 0, id_size);
564     cmd.dptr.prp1 = cpu_to_le64(iova);
565     if (nvme_admin_cmd_sync(bs, &cmd)) {
566         error_setg(errp, "Failed to identify controller");
567         goto out;
568     }
569 
570     if (le32_to_cpu(id->ctrl.nn) < namespace) {
571         error_setg(errp, "Invalid namespace");
572         goto out;
573     }
574     s->write_cache_supported = le32_to_cpu(id->ctrl.vwc) & 0x1;
575     s->max_transfer = (id->ctrl.mdts ? 1 << id->ctrl.mdts : 0) * s->page_size;
576     /* For now the page list buffer per command is one page, to hold at most
577      * s->page_size / sizeof(uint64_t) entries. */
578     s->max_transfer = MIN_NON_ZERO(s->max_transfer,
579                           s->page_size / sizeof(uint64_t) * s->page_size);
580 
581     oncs = le16_to_cpu(id->ctrl.oncs);
582     s->supports_write_zeroes = !!(oncs & NVME_ONCS_WRITE_ZEROES);
583     s->supports_discard = !!(oncs & NVME_ONCS_DSM);
584 
585     memset(id, 0, id_size);
586     cmd.cdw10 = 0;
587     cmd.nsid = cpu_to_le32(namespace);
588     if (nvme_admin_cmd_sync(bs, &cmd)) {
589         error_setg(errp, "Failed to identify namespace");
590         goto out;
591     }
592 
593     s->nsze = le64_to_cpu(id->ns.nsze);
594     lbaf = &id->ns.lbaf[NVME_ID_NS_FLBAS_INDEX(id->ns.flbas)];
595 
596     if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id->ns.dlfeat) &&
597             NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id->ns.dlfeat) ==
598                     NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES) {
599         bs->supported_write_flags |= BDRV_REQ_MAY_UNMAP;
600     }
601 
602     if (lbaf->ms) {
603         error_setg(errp, "Namespaces with metadata are not yet supported");
604         goto out;
605     }
606 
607     if (lbaf->ds < BDRV_SECTOR_BITS || lbaf->ds > 12 ||
608         (1 << lbaf->ds) > s->page_size)
609     {
610         error_setg(errp, "Namespace has unsupported block size (2^%d)",
611                    lbaf->ds);
612         goto out;
613     }
614 
615     ret = true;
616     s->blkshift = lbaf->ds;
617 out:
618     qemu_vfio_dma_unmap(s->vfio, id);
619 
620     return ret;
621 }
622 
623 static void nvme_poll_queue(NVMeQueuePair *q)
624 {
625     const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
626     NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
627 
628     trace_nvme_poll_queue(q->s, q->index);
629     /*
630      * Do an early check for completions. q->lock isn't needed because
631      * nvme_process_completion() only runs in the event loop thread and
632      * cannot race with itself.
633      */
634     if ((le16_to_cpu(cqe->status) & 0x1) == q->cq_phase) {
635         return;
636     }
637 
638     qemu_mutex_lock(&q->lock);
639     while (nvme_process_completion(q)) {
640         /* Keep polling */
641     }
642     qemu_mutex_unlock(&q->lock);
643 }
644 
645 static void nvme_poll_queues(BDRVNVMeState *s)
646 {
647     int i;
648 
649     for (i = 0; i < s->queue_count; i++) {
650         nvme_poll_queue(s->queues[i]);
651     }
652 }
653 
654 static void nvme_handle_event(EventNotifier *n)
655 {
656     BDRVNVMeState *s = container_of(n, BDRVNVMeState,
657                                     irq_notifier[MSIX_SHARED_IRQ_IDX]);
658 
659     trace_nvme_handle_event(s);
660     event_notifier_test_and_clear(n);
661     nvme_poll_queues(s);
662 }
663 
664 static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
665 {
666     BDRVNVMeState *s = bs->opaque;
667     unsigned n = s->queue_count;
668     NVMeQueuePair *q;
669     NvmeCmd cmd;
670     unsigned queue_size = NVME_QUEUE_SIZE;
671 
672     assert(n <= UINT16_MAX);
673     q = nvme_create_queue_pair(s, bdrv_get_aio_context(bs),
674                                n, queue_size, errp);
675     if (!q) {
676         return false;
677     }
678     cmd = (NvmeCmd) {
679         .opcode = NVME_ADM_CMD_CREATE_CQ,
680         .dptr.prp1 = cpu_to_le64(q->cq.iova),
681         .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
682         .cdw11 = cpu_to_le32(NVME_CQ_IEN | NVME_CQ_PC),
683     };
684     if (nvme_admin_cmd_sync(bs, &cmd)) {
685         error_setg(errp, "Failed to create CQ io queue [%u]", n);
686         goto out_error;
687     }
688     cmd = (NvmeCmd) {
689         .opcode = NVME_ADM_CMD_CREATE_SQ,
690         .dptr.prp1 = cpu_to_le64(q->sq.iova),
691         .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
692         .cdw11 = cpu_to_le32(NVME_SQ_PC | (n << 16)),
693     };
694     if (nvme_admin_cmd_sync(bs, &cmd)) {
695         error_setg(errp, "Failed to create SQ io queue [%u]", n);
696         goto out_error;
697     }
698     s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
699     s->queues[n] = q;
700     s->queue_count++;
701     return true;
702 out_error:
703     nvme_free_queue_pair(q);
704     return false;
705 }
706 
707 static bool nvme_poll_cb(void *opaque)
708 {
709     EventNotifier *e = opaque;
710     BDRVNVMeState *s = container_of(e, BDRVNVMeState,
711                                     irq_notifier[MSIX_SHARED_IRQ_IDX]);
712     int i;
713 
714     for (i = 0; i < s->queue_count; i++) {
715         NVMeQueuePair *q = s->queues[i];
716         const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
717         NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
718 
719         /*
720          * q->lock isn't needed because nvme_process_completion() only runs in
721          * the event loop thread and cannot race with itself.
722          */
723         if ((le16_to_cpu(cqe->status) & 0x1) != q->cq_phase) {
724             return true;
725         }
726     }
727     return false;
728 }
729 
730 static void nvme_poll_ready(EventNotifier *e)
731 {
732     BDRVNVMeState *s = container_of(e, BDRVNVMeState,
733                                     irq_notifier[MSIX_SHARED_IRQ_IDX]);
734 
735     nvme_poll_queues(s);
736 }
737 
738 static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
739                      Error **errp)
740 {
741     BDRVNVMeState *s = bs->opaque;
742     NVMeQueuePair *q;
743     AioContext *aio_context = bdrv_get_aio_context(bs);
744     int ret;
745     uint64_t cap;
746     uint32_t ver;
747     uint64_t timeout_ms;
748     uint64_t deadline, now;
749     volatile NvmeBar *regs = NULL;
750 
751     qemu_co_mutex_init(&s->dma_map_lock);
752     qemu_co_queue_init(&s->dma_flush_queue);
753     s->device = g_strdup(device);
754     s->nsid = namespace;
755     s->aio_context = bdrv_get_aio_context(bs);
756     ret = event_notifier_init(&s->irq_notifier[MSIX_SHARED_IRQ_IDX], 0);
757     if (ret) {
758         error_setg(errp, "Failed to init event notifier");
759         return ret;
760     }
761 
762     s->vfio = qemu_vfio_open_pci(device, errp);
763     if (!s->vfio) {
764         ret = -EINVAL;
765         goto out;
766     }
767 
768     regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, sizeof(NvmeBar),
769                                  PROT_READ | PROT_WRITE, errp);
770     if (!regs) {
771         ret = -EINVAL;
772         goto out;
773     }
774     /* Perform initialize sequence as described in NVMe spec "7.6.1
775      * Initialization". */
776 
777     cap = le64_to_cpu(regs->cap);
778     trace_nvme_controller_capability_raw(cap);
779     trace_nvme_controller_capability("Maximum Queue Entries Supported",
780                                      1 + NVME_CAP_MQES(cap));
781     trace_nvme_controller_capability("Contiguous Queues Required",
782                                      NVME_CAP_CQR(cap));
783     trace_nvme_controller_capability("Doorbell Stride",
784                                      1 << (2 + NVME_CAP_DSTRD(cap)));
785     trace_nvme_controller_capability("Subsystem Reset Supported",
786                                      NVME_CAP_NSSRS(cap));
787     trace_nvme_controller_capability("Memory Page Size Minimum",
788                                      1 << (12 + NVME_CAP_MPSMIN(cap)));
789     trace_nvme_controller_capability("Memory Page Size Maximum",
790                                      1 << (12 + NVME_CAP_MPSMAX(cap)));
791     if (!NVME_CAP_CSS(cap)) {
792         error_setg(errp, "Device doesn't support NVMe command set");
793         ret = -EINVAL;
794         goto out;
795     }
796 
797     s->page_size = 1u << (12 + NVME_CAP_MPSMIN(cap));
798     s->doorbell_scale = (4 << NVME_CAP_DSTRD(cap)) / sizeof(uint32_t);
799     bs->bl.opt_mem_alignment = s->page_size;
800     bs->bl.request_alignment = s->page_size;
801     timeout_ms = MIN(500 * NVME_CAP_TO(cap), 30000);
802 
803     ver = le32_to_cpu(regs->vs);
804     trace_nvme_controller_spec_version(extract32(ver, 16, 16),
805                                        extract32(ver, 8, 8),
806                                        extract32(ver, 0, 8));
807 
808     /* Reset device to get a clean state. */
809     regs->cc = cpu_to_le32(le32_to_cpu(regs->cc) & 0xFE);
810     /* Wait for CSTS.RDY = 0. */
811     deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * SCALE_MS;
812     while (NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
813         if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
814             error_setg(errp, "Timeout while waiting for device to reset (%"
815                              PRId64 " ms)",
816                        timeout_ms);
817             ret = -ETIMEDOUT;
818             goto out;
819         }
820     }
821 
822     s->bar0_wo_map = qemu_vfio_pci_map_bar(s->vfio, 0, 0,
823                                            sizeof(NvmeBar) + NVME_DOORBELL_SIZE,
824                                            PROT_WRITE, errp);
825     s->doorbells = (void *)((uintptr_t)s->bar0_wo_map + sizeof(NvmeBar));
826     if (!s->doorbells) {
827         ret = -EINVAL;
828         goto out;
829     }
830 
831     /* Set up admin queue. */
832     s->queues = g_new(NVMeQueuePair *, 1);
833     q = nvme_create_queue_pair(s, aio_context, 0, NVME_QUEUE_SIZE, errp);
834     if (!q) {
835         ret = -EINVAL;
836         goto out;
837     }
838     s->queues[INDEX_ADMIN] = q;
839     s->queue_count = 1;
840     QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE - 1) & 0xF000);
841     regs->aqa = cpu_to_le32(((NVME_QUEUE_SIZE - 1) << AQA_ACQS_SHIFT) |
842                             ((NVME_QUEUE_SIZE - 1) << AQA_ASQS_SHIFT));
843     regs->asq = cpu_to_le64(q->sq.iova);
844     regs->acq = cpu_to_le64(q->cq.iova);
845 
846     /* After setting up all control registers we can enable device now. */
847     regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << CC_IOCQES_SHIFT) |
848                            (ctz32(NVME_SQ_ENTRY_BYTES) << CC_IOSQES_SHIFT) |
849                            CC_EN_MASK);
850     /* Wait for CSTS.RDY = 1. */
851     now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
852     deadline = now + timeout_ms * SCALE_MS;
853     while (!NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
854         if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
855             error_setg(errp, "Timeout while waiting for device to start (%"
856                              PRId64 " ms)",
857                        timeout_ms);
858             ret = -ETIMEDOUT;
859             goto out;
860         }
861     }
862 
863     ret = qemu_vfio_pci_init_irq(s->vfio, s->irq_notifier,
864                                  VFIO_PCI_MSIX_IRQ_INDEX, errp);
865     if (ret) {
866         goto out;
867     }
868     aio_set_event_notifier(bdrv_get_aio_context(bs),
869                            &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
870                            nvme_handle_event, nvme_poll_cb,
871                            nvme_poll_ready);
872 
873     if (!nvme_identify(bs, namespace, errp)) {
874         ret = -EIO;
875         goto out;
876     }
877 
878     /* Set up command queues. */
879     if (!nvme_add_io_queue(bs, errp)) {
880         ret = -EIO;
881     }
882 out:
883     if (regs) {
884         qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)regs, 0, sizeof(NvmeBar));
885     }
886 
887     /* Cleaning up is done in nvme_file_open() upon error. */
888     return ret;
889 }
890 
891 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
892  *
893  *     nvme://0000:44:00.0/1
894  *
895  * where the "nvme://" is a fixed form of the protocol prefix, the middle part
896  * is the PCI address, and the last part is the namespace number starting from
897  * 1 according to the NVMe spec. */
898 static void nvme_parse_filename(const char *filename, QDict *options,
899                                 Error **errp)
900 {
901     int pref = strlen("nvme://");
902 
903     if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
904         const char *tmp = filename + pref;
905         char *device;
906         const char *namespace;
907         unsigned long ns;
908         const char *slash = strchr(tmp, '/');
909         if (!slash) {
910             qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
911             return;
912         }
913         device = g_strndup(tmp, slash - tmp);
914         qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
915         g_free(device);
916         namespace = slash + 1;
917         if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
918             error_setg(errp, "Invalid namespace '%s', positive number expected",
919                        namespace);
920             return;
921         }
922         qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
923                       *namespace ? namespace : "1");
924     }
925 }
926 
927 static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
928                                            Error **errp)
929 {
930     int ret;
931     BDRVNVMeState *s = bs->opaque;
932     NvmeCmd cmd = {
933         .opcode = NVME_ADM_CMD_SET_FEATURES,
934         .nsid = cpu_to_le32(s->nsid),
935         .cdw10 = cpu_to_le32(0x06),
936         .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
937     };
938 
939     ret = nvme_admin_cmd_sync(bs, &cmd);
940     if (ret) {
941         error_setg(errp, "Failed to configure NVMe write cache");
942     }
943     return ret;
944 }
945 
946 static void nvme_close(BlockDriverState *bs)
947 {
948     BDRVNVMeState *s = bs->opaque;
949 
950     for (unsigned i = 0; i < s->queue_count; ++i) {
951         nvme_free_queue_pair(s->queues[i]);
952     }
953     g_free(s->queues);
954     aio_set_event_notifier(bdrv_get_aio_context(bs),
955                            &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
956                            NULL, NULL, NULL);
957     event_notifier_cleanup(&s->irq_notifier[MSIX_SHARED_IRQ_IDX]);
958     qemu_vfio_pci_unmap_bar(s->vfio, 0, s->bar0_wo_map,
959                             0, sizeof(NvmeBar) + NVME_DOORBELL_SIZE);
960     qemu_vfio_close(s->vfio);
961 
962     g_free(s->device);
963 }
964 
965 static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
966                           Error **errp)
967 {
968     const char *device;
969     QemuOpts *opts;
970     int namespace;
971     int ret;
972     BDRVNVMeState *s = bs->opaque;
973 
974     bs->supported_write_flags = BDRV_REQ_FUA;
975 
976     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
977     qemu_opts_absorb_qdict(opts, options, &error_abort);
978     device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
979     if (!device) {
980         error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
981         qemu_opts_del(opts);
982         return -EINVAL;
983     }
984 
985     namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
986     ret = nvme_init(bs, device, namespace, errp);
987     qemu_opts_del(opts);
988     if (ret) {
989         goto fail;
990     }
991     if (flags & BDRV_O_NOCACHE) {
992         if (!s->write_cache_supported) {
993             error_setg(errp,
994                        "NVMe controller doesn't support write cache configuration");
995             ret = -EINVAL;
996         } else {
997             ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
998                                                   errp);
999         }
1000         if (ret) {
1001             goto fail;
1002         }
1003     }
1004     return 0;
1005 fail:
1006     nvme_close(bs);
1007     return ret;
1008 }
1009 
1010 static int64_t coroutine_fn nvme_co_getlength(BlockDriverState *bs)
1011 {
1012     BDRVNVMeState *s = bs->opaque;
1013     return s->nsze << s->blkshift;
1014 }
1015 
1016 static uint32_t nvme_get_blocksize(BlockDriverState *bs)
1017 {
1018     BDRVNVMeState *s = bs->opaque;
1019     assert(s->blkshift >= BDRV_SECTOR_BITS && s->blkshift <= 12);
1020     return UINT32_C(1) << s->blkshift;
1021 }
1022 
1023 static int nvme_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1024 {
1025     uint32_t blocksize = nvme_get_blocksize(bs);
1026     bsz->phys = blocksize;
1027     bsz->log = blocksize;
1028     return 0;
1029 }
1030 
1031 /* Called with s->dma_map_lock */
1032 static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
1033                                             QEMUIOVector *qiov)
1034 {
1035     int r = 0;
1036     BDRVNVMeState *s = bs->opaque;
1037 
1038     s->dma_map_count -= qiov->size;
1039     if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
1040         r = qemu_vfio_dma_reset_temporary(s->vfio);
1041         if (!r) {
1042             qemu_co_queue_restart_all(&s->dma_flush_queue);
1043         }
1044     }
1045     return r;
1046 }
1047 
1048 /* Called with s->dma_map_lock */
1049 static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
1050                                           NVMeRequest *req, QEMUIOVector *qiov)
1051 {
1052     BDRVNVMeState *s = bs->opaque;
1053     uint64_t *pagelist = req->prp_list_page;
1054     int i, j, r;
1055     int entries = 0;
1056     Error *local_err = NULL, **errp = NULL;
1057 
1058     assert(qiov->size);
1059     assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
1060     assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
1061     for (i = 0; i < qiov->niov; ++i) {
1062         bool retry = true;
1063         uint64_t iova;
1064         size_t len = QEMU_ALIGN_UP(qiov->iov[i].iov_len,
1065                                    qemu_real_host_page_size());
1066 try_map:
1067         r = qemu_vfio_dma_map(s->vfio,
1068                               qiov->iov[i].iov_base,
1069                               len, true, &iova, errp);
1070         if (r == -ENOSPC) {
1071             /*
1072              * In addition to the -ENOMEM error, the VFIO_IOMMU_MAP_DMA
1073              * ioctl returns -ENOSPC to signal the user exhausted the DMA
1074              * mappings available for a container since Linux kernel commit
1075              * 492855939bdb ("vfio/type1: Limit DMA mappings per container",
1076              * April 2019, see CVE-2019-3882).
1077              *
1078              * This block driver already handles this error path by checking
1079              * for the -ENOMEM error, so we directly replace -ENOSPC by
1080              * -ENOMEM. Beside, -ENOSPC has a specific meaning for blockdev
1081              * coroutines: it triggers BLOCKDEV_ON_ERROR_ENOSPC and
1082              * BLOCK_ERROR_ACTION_STOP which stops the VM, asking the operator
1083              * to add more storage to the blockdev. Not something we can do
1084              * easily with an IOMMU :)
1085              */
1086             r = -ENOMEM;
1087         }
1088         if (r == -ENOMEM && retry) {
1089             /*
1090              * We exhausted the DMA mappings available for our container:
1091              * recycle the volatile IOVA mappings.
1092              */
1093             retry = false;
1094             trace_nvme_dma_flush_queue_wait(s);
1095             if (s->dma_map_count) {
1096                 trace_nvme_dma_map_flush(s);
1097                 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
1098             } else {
1099                 r = qemu_vfio_dma_reset_temporary(s->vfio);
1100                 if (r) {
1101                     goto fail;
1102                 }
1103             }
1104             errp = &local_err;
1105 
1106             goto try_map;
1107         }
1108         if (r) {
1109             goto fail;
1110         }
1111 
1112         for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
1113             pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
1114         }
1115         trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
1116                                     qiov->iov[i].iov_len / s->page_size);
1117     }
1118 
1119     s->dma_map_count += qiov->size;
1120 
1121     assert(entries <= s->page_size / sizeof(uint64_t));
1122     switch (entries) {
1123     case 0:
1124         abort();
1125     case 1:
1126         cmd->dptr.prp1 = pagelist[0];
1127         cmd->dptr.prp2 = 0;
1128         break;
1129     case 2:
1130         cmd->dptr.prp1 = pagelist[0];
1131         cmd->dptr.prp2 = pagelist[1];
1132         break;
1133     default:
1134         cmd->dptr.prp1 = pagelist[0];
1135         cmd->dptr.prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
1136         break;
1137     }
1138     trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
1139     for (i = 0; i < entries; ++i) {
1140         trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
1141     }
1142     return 0;
1143 fail:
1144     /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1145      * increment s->dma_map_count. This is okay for fixed mapping memory areas
1146      * because they are already mapped before calling this function; for
1147      * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1148      * calling qemu_vfio_dma_reset_temporary when necessary. */
1149     if (local_err) {
1150         error_reportf_err(local_err, "Cannot map buffer for DMA: ");
1151     }
1152     return r;
1153 }
1154 
1155 typedef struct {
1156     Coroutine *co;
1157     int ret;
1158     AioContext *ctx;
1159 } NVMeCoData;
1160 
1161 static void nvme_rw_cb_bh(void *opaque)
1162 {
1163     NVMeCoData *data = opaque;
1164     qemu_coroutine_enter(data->co);
1165 }
1166 
1167 static void nvme_rw_cb(void *opaque, int ret)
1168 {
1169     NVMeCoData *data = opaque;
1170     data->ret = ret;
1171     if (!data->co) {
1172         /* The rw coroutine hasn't yielded, don't try to enter. */
1173         return;
1174     }
1175     replay_bh_schedule_oneshot_event(data->ctx, nvme_rw_cb_bh, data);
1176 }
1177 
1178 static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
1179                                             uint64_t offset, uint64_t bytes,
1180                                             QEMUIOVector *qiov,
1181                                             bool is_write,
1182                                             int flags)
1183 {
1184     int r;
1185     BDRVNVMeState *s = bs->opaque;
1186     NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1187     NVMeRequest *req;
1188 
1189     uint32_t cdw12 = (((bytes >> s->blkshift) - 1) & 0xFFFF) |
1190                        (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
1191     NvmeCmd cmd = {
1192         .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
1193         .nsid = cpu_to_le32(s->nsid),
1194         .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1195         .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1196         .cdw12 = cpu_to_le32(cdw12),
1197     };
1198     NVMeCoData data = {
1199         .ctx = bdrv_get_aio_context(bs),
1200         .ret = -EINPROGRESS,
1201     };
1202 
1203     trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
1204     assert(s->queue_count > 1);
1205     req = nvme_get_free_req(ioq);
1206     assert(req);
1207 
1208     qemu_co_mutex_lock(&s->dma_map_lock);
1209     r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
1210     qemu_co_mutex_unlock(&s->dma_map_lock);
1211     if (r) {
1212         nvme_put_free_req_and_wake(ioq, req);
1213         return r;
1214     }
1215     nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1216 
1217     data.co = qemu_coroutine_self();
1218     while (data.ret == -EINPROGRESS) {
1219         qemu_coroutine_yield();
1220     }
1221 
1222     qemu_co_mutex_lock(&s->dma_map_lock);
1223     r = nvme_cmd_unmap_qiov(bs, qiov);
1224     qemu_co_mutex_unlock(&s->dma_map_lock);
1225     if (r) {
1226         return r;
1227     }
1228 
1229     trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
1230     return data.ret;
1231 }
1232 
1233 static inline bool nvme_qiov_aligned(BlockDriverState *bs,
1234                                      const QEMUIOVector *qiov)
1235 {
1236     int i;
1237     BDRVNVMeState *s = bs->opaque;
1238 
1239     for (i = 0; i < qiov->niov; ++i) {
1240         if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base,
1241                                  qemu_real_host_page_size()) ||
1242             !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, qemu_real_host_page_size())) {
1243             trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
1244                                       qiov->iov[i].iov_len, s->page_size);
1245             return false;
1246         }
1247     }
1248     return true;
1249 }
1250 
1251 static coroutine_fn int nvme_co_prw(BlockDriverState *bs,
1252                                     uint64_t offset, uint64_t bytes,
1253                                     QEMUIOVector *qiov, bool is_write,
1254                                     int flags)
1255 {
1256     BDRVNVMeState *s = bs->opaque;
1257     int r;
1258     QEMU_AUTO_VFREE uint8_t *buf = NULL;
1259     QEMUIOVector local_qiov;
1260     size_t len = QEMU_ALIGN_UP(bytes, qemu_real_host_page_size());
1261     assert(QEMU_IS_ALIGNED(offset, s->page_size));
1262     assert(QEMU_IS_ALIGNED(bytes, s->page_size));
1263     assert(bytes <= s->max_transfer);
1264     if (nvme_qiov_aligned(bs, qiov)) {
1265         s->stats.aligned_accesses++;
1266         return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
1267     }
1268     s->stats.unaligned_accesses++;
1269     trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
1270     buf = qemu_try_memalign(qemu_real_host_page_size(), len);
1271 
1272     if (!buf) {
1273         return -ENOMEM;
1274     }
1275     qemu_iovec_init(&local_qiov, 1);
1276     if (is_write) {
1277         qemu_iovec_to_buf(qiov, 0, buf, bytes);
1278     }
1279     qemu_iovec_add(&local_qiov, buf, bytes);
1280     r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
1281     qemu_iovec_destroy(&local_qiov);
1282     if (!r && !is_write) {
1283         qemu_iovec_from_buf(qiov, 0, buf, bytes);
1284     }
1285     return r;
1286 }
1287 
1288 static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1289                                        int64_t offset, int64_t bytes,
1290                                        QEMUIOVector *qiov,
1291                                        BdrvRequestFlags flags)
1292 {
1293     return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1294 }
1295 
1296 static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1297                                         int64_t offset, int64_t bytes,
1298                                         QEMUIOVector *qiov,
1299                                         BdrvRequestFlags flags)
1300 {
1301     return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1302 }
1303 
1304 static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1305 {
1306     BDRVNVMeState *s = bs->opaque;
1307     NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1308     NVMeRequest *req;
1309     NvmeCmd cmd = {
1310         .opcode = NVME_CMD_FLUSH,
1311         .nsid = cpu_to_le32(s->nsid),
1312     };
1313     NVMeCoData data = {
1314         .ctx = bdrv_get_aio_context(bs),
1315         .ret = -EINPROGRESS,
1316     };
1317 
1318     assert(s->queue_count > 1);
1319     req = nvme_get_free_req(ioq);
1320     assert(req);
1321     nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1322 
1323     data.co = qemu_coroutine_self();
1324     if (data.ret == -EINPROGRESS) {
1325         qemu_coroutine_yield();
1326     }
1327 
1328     return data.ret;
1329 }
1330 
1331 
1332 static coroutine_fn int nvme_co_pwrite_zeroes(BlockDriverState *bs,
1333                                               int64_t offset,
1334                                               int64_t bytes,
1335                                               BdrvRequestFlags flags)
1336 {
1337     BDRVNVMeState *s = bs->opaque;
1338     NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1339     NVMeRequest *req;
1340     uint32_t cdw12;
1341 
1342     if (!s->supports_write_zeroes) {
1343         return -ENOTSUP;
1344     }
1345 
1346     if (bytes == 0) {
1347         return 0;
1348     }
1349 
1350     cdw12 = ((bytes >> s->blkshift) - 1) & 0xFFFF;
1351     /*
1352      * We should not lose information. pwrite_zeroes_alignment and
1353      * max_pwrite_zeroes guarantees it.
1354      */
1355     assert(((cdw12 + 1) << s->blkshift) == bytes);
1356 
1357     NvmeCmd cmd = {
1358         .opcode = NVME_CMD_WRITE_ZEROES,
1359         .nsid = cpu_to_le32(s->nsid),
1360         .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1361         .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1362     };
1363 
1364     NVMeCoData data = {
1365         .ctx = bdrv_get_aio_context(bs),
1366         .ret = -EINPROGRESS,
1367     };
1368 
1369     if (flags & BDRV_REQ_MAY_UNMAP) {
1370         cdw12 |= (1 << 25);
1371     }
1372 
1373     if (flags & BDRV_REQ_FUA) {
1374         cdw12 |= (1 << 30);
1375     }
1376 
1377     cmd.cdw12 = cpu_to_le32(cdw12);
1378 
1379     trace_nvme_write_zeroes(s, offset, bytes, flags);
1380     assert(s->queue_count > 1);
1381     req = nvme_get_free_req(ioq);
1382     assert(req);
1383 
1384     nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1385 
1386     data.co = qemu_coroutine_self();
1387     while (data.ret == -EINPROGRESS) {
1388         qemu_coroutine_yield();
1389     }
1390 
1391     trace_nvme_rw_done(s, true, offset, bytes, data.ret);
1392     return data.ret;
1393 }
1394 
1395 
1396 static int coroutine_fn nvme_co_pdiscard(BlockDriverState *bs,
1397                                          int64_t offset,
1398                                          int64_t bytes)
1399 {
1400     BDRVNVMeState *s = bs->opaque;
1401     NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1402     NVMeRequest *req;
1403     QEMU_AUTO_VFREE NvmeDsmRange *buf = NULL;
1404     QEMUIOVector local_qiov;
1405     int ret;
1406 
1407     NvmeCmd cmd = {
1408         .opcode = NVME_CMD_DSM,
1409         .nsid = cpu_to_le32(s->nsid),
1410         .cdw10 = cpu_to_le32(0), /*number of ranges - 0 based*/
1411         .cdw11 = cpu_to_le32(1 << 2), /*deallocate bit*/
1412     };
1413 
1414     NVMeCoData data = {
1415         .ctx = bdrv_get_aio_context(bs),
1416         .ret = -EINPROGRESS,
1417     };
1418 
1419     if (!s->supports_discard) {
1420         return -ENOTSUP;
1421     }
1422 
1423     assert(s->queue_count > 1);
1424 
1425     /*
1426      * Filling the @buf requires @offset and @bytes to satisfy restrictions
1427      * defined in nvme_refresh_limits().
1428      */
1429     assert(QEMU_IS_ALIGNED(bytes, 1UL << s->blkshift));
1430     assert(QEMU_IS_ALIGNED(offset, 1UL << s->blkshift));
1431     assert((bytes >> s->blkshift) <= UINT32_MAX);
1432 
1433     buf = qemu_try_memalign(s->page_size, s->page_size);
1434     if (!buf) {
1435         return -ENOMEM;
1436     }
1437     memset(buf, 0, s->page_size);
1438     buf->nlb = cpu_to_le32(bytes >> s->blkshift);
1439     buf->slba = cpu_to_le64(offset >> s->blkshift);
1440     buf->cattr = 0;
1441 
1442     qemu_iovec_init(&local_qiov, 1);
1443     qemu_iovec_add(&local_qiov, buf, 4096);
1444 
1445     req = nvme_get_free_req(ioq);
1446     assert(req);
1447 
1448     qemu_co_mutex_lock(&s->dma_map_lock);
1449     ret = nvme_cmd_map_qiov(bs, &cmd, req, &local_qiov);
1450     qemu_co_mutex_unlock(&s->dma_map_lock);
1451 
1452     if (ret) {
1453         nvme_put_free_req_and_wake(ioq, req);
1454         goto out;
1455     }
1456 
1457     trace_nvme_dsm(s, offset, bytes);
1458 
1459     nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1460 
1461     data.co = qemu_coroutine_self();
1462     while (data.ret == -EINPROGRESS) {
1463         qemu_coroutine_yield();
1464     }
1465 
1466     qemu_co_mutex_lock(&s->dma_map_lock);
1467     ret = nvme_cmd_unmap_qiov(bs, &local_qiov);
1468     qemu_co_mutex_unlock(&s->dma_map_lock);
1469 
1470     if (ret) {
1471         goto out;
1472     }
1473 
1474     ret = data.ret;
1475     trace_nvme_dsm_done(s, offset, bytes, ret);
1476 out:
1477     qemu_iovec_destroy(&local_qiov);
1478     return ret;
1479 
1480 }
1481 
1482 static int coroutine_fn nvme_co_truncate(BlockDriverState *bs, int64_t offset,
1483                                          bool exact, PreallocMode prealloc,
1484                                          BdrvRequestFlags flags, Error **errp)
1485 {
1486     int64_t cur_length;
1487 
1488     if (prealloc != PREALLOC_MODE_OFF) {
1489         error_setg(errp, "Unsupported preallocation mode '%s'",
1490                    PreallocMode_str(prealloc));
1491         return -ENOTSUP;
1492     }
1493 
1494     cur_length = nvme_co_getlength(bs);
1495     if (offset != cur_length && exact) {
1496         error_setg(errp, "Cannot resize NVMe devices");
1497         return -ENOTSUP;
1498     } else if (offset > cur_length) {
1499         error_setg(errp, "Cannot grow NVMe devices");
1500         return -EINVAL;
1501     }
1502 
1503     return 0;
1504 }
1505 
1506 static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1507                                BlockReopenQueue *queue, Error **errp)
1508 {
1509     return 0;
1510 }
1511 
1512 static void nvme_refresh_filename(BlockDriverState *bs)
1513 {
1514     BDRVNVMeState *s = bs->opaque;
1515 
1516     snprintf(bs->exact_filename, sizeof(bs->exact_filename), "nvme://%s/%i",
1517              s->device, s->nsid);
1518 }
1519 
1520 static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1521 {
1522     BDRVNVMeState *s = bs->opaque;
1523 
1524     bs->bl.opt_mem_alignment = s->page_size;
1525     bs->bl.request_alignment = s->page_size;
1526     bs->bl.max_transfer = s->max_transfer;
1527 
1528     /*
1529      * Look at nvme_co_pwrite_zeroes: after shift and decrement we should get
1530      * at most 0xFFFF
1531      */
1532     bs->bl.max_pwrite_zeroes = 1ULL << (s->blkshift + 16);
1533     bs->bl.pwrite_zeroes_alignment = MAX(bs->bl.request_alignment,
1534                                          1UL << s->blkshift);
1535 
1536     bs->bl.max_pdiscard = (uint64_t)UINT32_MAX << s->blkshift;
1537     bs->bl.pdiscard_alignment = MAX(bs->bl.request_alignment,
1538                                     1UL << s->blkshift);
1539 }
1540 
1541 static void nvme_detach_aio_context(BlockDriverState *bs)
1542 {
1543     BDRVNVMeState *s = bs->opaque;
1544 
1545     for (unsigned i = 0; i < s->queue_count; i++) {
1546         NVMeQueuePair *q = s->queues[i];
1547 
1548         qemu_bh_delete(q->completion_bh);
1549         q->completion_bh = NULL;
1550     }
1551 
1552     aio_set_event_notifier(bdrv_get_aio_context(bs),
1553                            &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1554                            NULL, NULL, NULL);
1555 }
1556 
1557 static void nvme_attach_aio_context(BlockDriverState *bs,
1558                                     AioContext *new_context)
1559 {
1560     BDRVNVMeState *s = bs->opaque;
1561 
1562     s->aio_context = new_context;
1563     aio_set_event_notifier(new_context, &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1564                            nvme_handle_event, nvme_poll_cb,
1565                            nvme_poll_ready);
1566 
1567     for (unsigned i = 0; i < s->queue_count; i++) {
1568         NVMeQueuePair *q = s->queues[i];
1569 
1570         q->completion_bh =
1571             aio_bh_new(new_context, nvme_process_completion_bh, q);
1572     }
1573 }
1574 
1575 static bool nvme_register_buf(BlockDriverState *bs, void *host, size_t size,
1576                               Error **errp)
1577 {
1578     int ret;
1579     BDRVNVMeState *s = bs->opaque;
1580 
1581     /*
1582      * FIXME: we may run out of IOVA addresses after repeated
1583      * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1584      * doesn't reclaim addresses for fixed mappings.
1585      */
1586     ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL, errp);
1587     return ret == 0;
1588 }
1589 
1590 static void nvme_unregister_buf(BlockDriverState *bs, void *host, size_t size)
1591 {
1592     BDRVNVMeState *s = bs->opaque;
1593 
1594     qemu_vfio_dma_unmap(s->vfio, host);
1595 }
1596 
1597 static BlockStatsSpecific *nvme_get_specific_stats(BlockDriverState *bs)
1598 {
1599     BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
1600     BDRVNVMeState *s = bs->opaque;
1601 
1602     stats->driver = BLOCKDEV_DRIVER_NVME;
1603     stats->u.nvme = (BlockStatsSpecificNvme) {
1604         .completion_errors = s->stats.completion_errors,
1605         .aligned_accesses = s->stats.aligned_accesses,
1606         .unaligned_accesses = s->stats.unaligned_accesses,
1607     };
1608 
1609     return stats;
1610 }
1611 
1612 static const char *const nvme_strong_runtime_opts[] = {
1613     NVME_BLOCK_OPT_DEVICE,
1614     NVME_BLOCK_OPT_NAMESPACE,
1615 
1616     NULL
1617 };
1618 
1619 static BlockDriver bdrv_nvme = {
1620     .format_name              = "nvme",
1621     .protocol_name            = "nvme",
1622     .instance_size            = sizeof(BDRVNVMeState),
1623 
1624     .bdrv_co_create_opts      = bdrv_co_create_opts_simple,
1625     .create_opts              = &bdrv_create_opts_simple,
1626 
1627     .bdrv_parse_filename      = nvme_parse_filename,
1628     .bdrv_file_open           = nvme_file_open,
1629     .bdrv_close               = nvme_close,
1630     .bdrv_co_getlength        = nvme_co_getlength,
1631     .bdrv_probe_blocksizes    = nvme_probe_blocksizes,
1632     .bdrv_co_truncate         = nvme_co_truncate,
1633 
1634     .bdrv_co_preadv           = nvme_co_preadv,
1635     .bdrv_co_pwritev          = nvme_co_pwritev,
1636 
1637     .bdrv_co_pwrite_zeroes    = nvme_co_pwrite_zeroes,
1638     .bdrv_co_pdiscard         = nvme_co_pdiscard,
1639 
1640     .bdrv_co_flush_to_disk    = nvme_co_flush,
1641     .bdrv_reopen_prepare      = nvme_reopen_prepare,
1642 
1643     .bdrv_refresh_filename    = nvme_refresh_filename,
1644     .bdrv_refresh_limits      = nvme_refresh_limits,
1645     .strong_runtime_opts      = nvme_strong_runtime_opts,
1646     .bdrv_get_specific_stats  = nvme_get_specific_stats,
1647 
1648     .bdrv_detach_aio_context  = nvme_detach_aio_context,
1649     .bdrv_attach_aio_context  = nvme_attach_aio_context,
1650 
1651     .bdrv_register_buf        = nvme_register_buf,
1652     .bdrv_unregister_buf      = nvme_unregister_buf,
1653 };
1654 
1655 static void bdrv_nvme_init(void)
1656 {
1657     bdrv_register(&bdrv_nvme);
1658 }
1659 
1660 block_init(bdrv_nvme_init);
1661