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