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