block-backend: Retain permissions after migration
[qemu.git] / block / nvme.c
blobdd20de3865b39e43546b82d9eeef8e565a46b077
1 /*
2 * NVMe block driver based on vfio
4 * Copyright 2016 - 2018 Red Hat, Inc.
6 * Authors:
7 * Fam Zheng <famz@redhat.com>
8 * Paolo Bonzini <pbonzini@redhat.com>
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.
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"
29 #include "block/nvme.h"
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
37 * We have to leave one slot empty as that is the full queue case where
38 * head == tail + 1.
40 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
42 typedef struct BDRVNVMeState BDRVNVMeState;
44 /* Same index is used for queues and IRQs */
45 #define INDEX_ADMIN 0
46 #define INDEX_IO(n) (1 + n)
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
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;
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;
71 typedef struct {
72 QemuMutex lock;
74 /* Read from I/O code path, initialized under BQL */
75 BDRVNVMeState *s;
76 int index;
78 /* Fields protected by BQL */
79 uint8_t *prp_list_pages;
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;
90 /* Thread-safe, no lock necessary */
91 QEMUBH *completion_bh;
92 } NVMeQueuePair;
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.
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];
115 uint64_t nsze; /* Namespace size reported by identify command */
116 int nsid; /* The namespace id to read/write data. */
117 int blkshift;
119 uint64_t max_transfer;
120 bool plugged;
122 bool supports_write_zeroes;
123 bool supports_discard;
125 CoMutex dma_map_lock;
126 CoQueue dma_flush_queue;
128 /* Total size of mapped qiov, accessed under dma_map_lock */
129 int dma_map_count;
131 /* PCI address (required for nvme_refresh_filename()) */
132 char *device;
134 struct {
135 uint64_t completion_errors;
136 uint64_t aligned_accesses;
137 uint64_t unaligned_accesses;
138 } stats;
141 #define NVME_BLOCK_OPT_DEVICE "device"
142 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
144 static void nvme_process_completion_bh(void *opaque);
146 static QemuOptsList runtime_opts = {
147 .name = "nvme",
148 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
149 .desc = {
151 .name = NVME_BLOCK_OPT_DEVICE,
152 .type = QEMU_OPT_STRING,
153 .help = "NVMe PCI device address",
156 .name = NVME_BLOCK_OPT_NAMESPACE,
157 .type = QEMU_OPT_NUMBER,
158 .help = "NVMe namespace",
160 { /* end of list */ }
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)
168 size_t bytes;
169 int r;
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;
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: ");
183 return r == 0;
186 static void nvme_free_queue(NVMeQueue *q)
188 qemu_vfree(q->queue);
191 static void nvme_free_queue_pair(NVMeQueuePair *q)
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);
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);
204 static void nvme_free_req_queue_cb(void *opaque)
206 NVMeQueuePair *q = opaque;
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 */
213 qemu_mutex_unlock(&q->lock);
216 static NVMeQueuePair *nvme_create_queue_pair(BDRVNVMeState *s,
217 AioContext *aio_context,
218 unsigned idx, size_t size,
219 Error **errp)
221 int i, r;
222 NVMeQueuePair *q;
223 uint64_t prp_list_iova;
224 size_t bytes;
226 q = g_try_new0(NVMeQueuePair, 1);
227 if (!q) {
228 error_setg(errp, "Cannot allocate queue pair");
229 return NULL;
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;
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;
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;
262 if (!nvme_init_queue(s, &q->sq, size, NVME_SQ_ENTRY_BYTES, errp)) {
263 goto fail;
265 q->sq.doorbell = &s->doorbells[idx * s->doorbell_scale].sq_tail;
267 if (!nvme_init_queue(s, &q->cq, size, NVME_CQ_ENTRY_BYTES, errp)) {
268 goto fail;
270 q->cq.doorbell = &s->doorbells[idx * s->doorbell_scale].cq_head;
272 return q;
273 fail:
274 nvme_free_queue_pair(q);
275 return NULL;
278 /* With q->lock */
279 static void nvme_kick(NVMeQueuePair *q)
281 BDRVNVMeState *s = q->s;
283 if (s->plugged || !q->need_kick) {
284 return;
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;
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;
299 static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
301 NVMeRequest *req;
303 qemu_mutex_lock(&q->lock);
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;
315 req = &q->reqs[q->free_req_head];
316 q->free_req_head = req->free_req_next;
317 req->free_req_next = -1;
319 qemu_mutex_unlock(&q->lock);
320 return req;
323 /* With q->lock */
324 static void nvme_put_free_req_locked(NVMeQueuePair *q, NVMeRequest *req)
326 req->free_req_next = q->free_req_head;
327 q->free_req_head = req - q->reqs;
330 /* With q->lock */
331 static void nvme_wake_free_req_locked(NVMeQueuePair *q)
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);
339 /* Insert a request in the freelist and wake waiters */
340 static void nvme_put_free_req_and_wake(NVMeQueuePair *q, NVMeRequest *req)
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);
348 static inline int nvme_translate_error(const NvmeCqe *c)
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));
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;
370 /* With q->lock */
371 static bool nvme_process_completion(NVMeQueuePair *q)
373 BDRVNVMeState *s = q->s;
374 bool progress = false;
375 NVMeRequest *preq;
376 NVMeRequest req;
377 NvmeCqe *c;
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;
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.
390 * The aio_poll() loop will execute our BH and we'll resume completion
391 * processing there.
393 qemu_bh_schedule(q->completion_bh);
395 assert(q->inflight >= 0);
396 while (q->inflight) {
397 int ret;
398 int16_t cid;
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;
404 ret = nvme_translate_error(c);
405 if (ret) {
406 s->stats.completion_errors++;
408 q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
409 if (!q->cq.head) {
410 q->cq_phase = !q->cq_phase;
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;
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;
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);
438 qemu_bh_cancel(q->completion_bh);
440 return progress;
443 static void nvme_process_completion_bh(void *opaque)
445 NVMeQueuePair *q = opaque;
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.
452 smp_mb_release();
453 *q->cq.doorbell = cpu_to_le32(q->cq.head);
454 nvme_wake_free_req_locked(q);
456 nvme_process_completion(q);
459 static void nvme_trace_command(const NvmeCmd *cmd)
461 int i;
463 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW)) {
464 return;
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]);
473 static void nvme_submit_command(NVMeQueuePair *q, NVMeRequest *req,
474 NvmeCmd *cmd, BlockCompletionFunc cb,
475 void *opaque)
477 assert(!req->cb);
478 req->cb = cb;
479 req->opaque = opaque;
480 cmd->cid = cpu_to_le16(req->cid);
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);
494 static void nvme_admin_cmd_sync_cb(void *opaque, int ret)
496 int *pret = opaque;
497 *pret = ret;
498 aio_wait_kick();
501 static int nvme_admin_cmd_sync(BlockDriverState *bs, NvmeCmd *cmd)
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;
512 nvme_submit_command(q, req, cmd, nvme_admin_cmd_sync_cb, &ret);
514 AIO_WAIT_WHILE(aio_context, ret == -EINPROGRESS);
515 return ret;
518 /* Returns true on success, false on failure. */
519 static bool nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
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),
535 size_t id_size = QEMU_ALIGN_UP(sizeof(*id), qemu_real_host_page_size);
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;
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;
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;
555 if (le32_to_cpu(id->ctrl.nn) < namespace) {
556 error_setg(errp, "Invalid namespace");
557 goto out;
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);
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);
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;
578 s->nsze = le64_to_cpu(id->ns.nsze);
579 lbaf = &id->ns.lbaf[NVME_ID_NS_FLBAS_INDEX(id->ns.flbas)];
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;
587 if (lbaf->ms) {
588 error_setg(errp, "Namespaces with metadata are not yet supported");
589 goto out;
592 if (lbaf->ds < BDRV_SECTOR_BITS || lbaf->ds > 12 ||
593 (1 << lbaf->ds) > s->page_size)
595 error_setg(errp, "Namespace has unsupported block size (2^%d)",
596 lbaf->ds);
597 goto out;
600 ret = true;
601 s->blkshift = lbaf->ds;
602 out:
603 qemu_vfio_dma_unmap(s->vfio, id);
605 return ret;
608 static void nvme_poll_queue(NVMeQueuePair *q)
610 const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
611 NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
613 trace_nvme_poll_queue(q->s, q->index);
615 * Do an early check for completions. q->lock isn't needed because
616 * nvme_process_completion() only runs in the event loop thread and
617 * cannot race with itself.
619 if ((le16_to_cpu(cqe->status) & 0x1) == q->cq_phase) {
620 return;
623 qemu_mutex_lock(&q->lock);
624 while (nvme_process_completion(q)) {
625 /* Keep polling */
627 qemu_mutex_unlock(&q->lock);
630 static void nvme_poll_queues(BDRVNVMeState *s)
632 int i;
634 for (i = 0; i < s->queue_count; i++) {
635 nvme_poll_queue(s->queues[i]);
639 static void nvme_handle_event(EventNotifier *n)
641 BDRVNVMeState *s = container_of(n, BDRVNVMeState,
642 irq_notifier[MSIX_SHARED_IRQ_IDX]);
644 trace_nvme_handle_event(s);
645 event_notifier_test_and_clear(n);
646 nvme_poll_queues(s);
649 static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
651 BDRVNVMeState *s = bs->opaque;
652 unsigned n = s->queue_count;
653 NVMeQueuePair *q;
654 NvmeCmd cmd;
655 unsigned queue_size = NVME_QUEUE_SIZE;
657 assert(n <= UINT16_MAX);
658 q = nvme_create_queue_pair(s, bdrv_get_aio_context(bs),
659 n, queue_size, errp);
660 if (!q) {
661 return false;
663 cmd = (NvmeCmd) {
664 .opcode = NVME_ADM_CMD_CREATE_CQ,
665 .dptr.prp1 = cpu_to_le64(q->cq.iova),
666 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
667 .cdw11 = cpu_to_le32(NVME_CQ_IEN | NVME_CQ_PC),
669 if (nvme_admin_cmd_sync(bs, &cmd)) {
670 error_setg(errp, "Failed to create CQ io queue [%u]", n);
671 goto out_error;
673 cmd = (NvmeCmd) {
674 .opcode = NVME_ADM_CMD_CREATE_SQ,
675 .dptr.prp1 = cpu_to_le64(q->sq.iova),
676 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | n),
677 .cdw11 = cpu_to_le32(NVME_SQ_PC | (n << 16)),
679 if (nvme_admin_cmd_sync(bs, &cmd)) {
680 error_setg(errp, "Failed to create SQ io queue [%u]", n);
681 goto out_error;
683 s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
684 s->queues[n] = q;
685 s->queue_count++;
686 return true;
687 out_error:
688 nvme_free_queue_pair(q);
689 return false;
692 static bool nvme_poll_cb(void *opaque)
694 EventNotifier *e = opaque;
695 BDRVNVMeState *s = container_of(e, BDRVNVMeState,
696 irq_notifier[MSIX_SHARED_IRQ_IDX]);
697 int i;
699 for (i = 0; i < s->queue_count; i++) {
700 NVMeQueuePair *q = s->queues[i];
701 const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
702 NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
705 * q->lock isn't needed because nvme_process_completion() only runs in
706 * the event loop thread and cannot race with itself.
708 if ((le16_to_cpu(cqe->status) & 0x1) != q->cq_phase) {
709 return true;
712 return false;
715 static void nvme_poll_ready(EventNotifier *e)
717 BDRVNVMeState *s = container_of(e, BDRVNVMeState,
718 irq_notifier[MSIX_SHARED_IRQ_IDX]);
720 nvme_poll_queues(s);
723 static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
724 Error **errp)
726 BDRVNVMeState *s = bs->opaque;
727 NVMeQueuePair *q;
728 AioContext *aio_context = bdrv_get_aio_context(bs);
729 int ret;
730 uint64_t cap;
731 uint32_t ver;
732 uint64_t timeout_ms;
733 uint64_t deadline, now;
734 volatile NvmeBar *regs = NULL;
736 qemu_co_mutex_init(&s->dma_map_lock);
737 qemu_co_queue_init(&s->dma_flush_queue);
738 s->device = g_strdup(device);
739 s->nsid = namespace;
740 s->aio_context = bdrv_get_aio_context(bs);
741 ret = event_notifier_init(&s->irq_notifier[MSIX_SHARED_IRQ_IDX], 0);
742 if (ret) {
743 error_setg(errp, "Failed to init event notifier");
744 return ret;
747 s->vfio = qemu_vfio_open_pci(device, errp);
748 if (!s->vfio) {
749 ret = -EINVAL;
750 goto out;
753 regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, sizeof(NvmeBar),
754 PROT_READ | PROT_WRITE, errp);
755 if (!regs) {
756 ret = -EINVAL;
757 goto out;
759 /* Perform initialize sequence as described in NVMe spec "7.6.1
760 * Initialization". */
762 cap = le64_to_cpu(regs->cap);
763 trace_nvme_controller_capability_raw(cap);
764 trace_nvme_controller_capability("Maximum Queue Entries Supported",
765 1 + NVME_CAP_MQES(cap));
766 trace_nvme_controller_capability("Contiguous Queues Required",
767 NVME_CAP_CQR(cap));
768 trace_nvme_controller_capability("Doorbell Stride",
769 1 << (2 + NVME_CAP_DSTRD(cap)));
770 trace_nvme_controller_capability("Subsystem Reset Supported",
771 NVME_CAP_NSSRS(cap));
772 trace_nvme_controller_capability("Memory Page Size Minimum",
773 1 << (12 + NVME_CAP_MPSMIN(cap)));
774 trace_nvme_controller_capability("Memory Page Size Maximum",
775 1 << (12 + NVME_CAP_MPSMAX(cap)));
776 if (!NVME_CAP_CSS(cap)) {
777 error_setg(errp, "Device doesn't support NVMe command set");
778 ret = -EINVAL;
779 goto out;
782 s->page_size = 1u << (12 + NVME_CAP_MPSMIN(cap));
783 s->doorbell_scale = (4 << NVME_CAP_DSTRD(cap)) / sizeof(uint32_t);
784 bs->bl.opt_mem_alignment = s->page_size;
785 bs->bl.request_alignment = s->page_size;
786 timeout_ms = MIN(500 * NVME_CAP_TO(cap), 30000);
788 ver = le32_to_cpu(regs->vs);
789 trace_nvme_controller_spec_version(extract32(ver, 16, 16),
790 extract32(ver, 8, 8),
791 extract32(ver, 0, 8));
793 /* Reset device to get a clean state. */
794 regs->cc = cpu_to_le32(le32_to_cpu(regs->cc) & 0xFE);
795 /* Wait for CSTS.RDY = 0. */
796 deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * SCALE_MS;
797 while (NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
798 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
799 error_setg(errp, "Timeout while waiting for device to reset (%"
800 PRId64 " ms)",
801 timeout_ms);
802 ret = -ETIMEDOUT;
803 goto out;
807 s->bar0_wo_map = qemu_vfio_pci_map_bar(s->vfio, 0, 0,
808 sizeof(NvmeBar) + NVME_DOORBELL_SIZE,
809 PROT_WRITE, errp);
810 s->doorbells = (void *)((uintptr_t)s->bar0_wo_map + sizeof(NvmeBar));
811 if (!s->doorbells) {
812 ret = -EINVAL;
813 goto out;
816 /* Set up admin queue. */
817 s->queues = g_new(NVMeQueuePair *, 1);
818 q = nvme_create_queue_pair(s, aio_context, 0, NVME_QUEUE_SIZE, errp);
819 if (!q) {
820 ret = -EINVAL;
821 goto out;
823 s->queues[INDEX_ADMIN] = q;
824 s->queue_count = 1;
825 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE - 1) & 0xF000);
826 regs->aqa = cpu_to_le32(((NVME_QUEUE_SIZE - 1) << AQA_ACQS_SHIFT) |
827 ((NVME_QUEUE_SIZE - 1) << AQA_ASQS_SHIFT));
828 regs->asq = cpu_to_le64(q->sq.iova);
829 regs->acq = cpu_to_le64(q->cq.iova);
831 /* After setting up all control registers we can enable device now. */
832 regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << CC_IOCQES_SHIFT) |
833 (ctz32(NVME_SQ_ENTRY_BYTES) << CC_IOSQES_SHIFT) |
834 CC_EN_MASK);
835 /* Wait for CSTS.RDY = 1. */
836 now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
837 deadline = now + timeout_ms * SCALE_MS;
838 while (!NVME_CSTS_RDY(le32_to_cpu(regs->csts))) {
839 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
840 error_setg(errp, "Timeout while waiting for device to start (%"
841 PRId64 " ms)",
842 timeout_ms);
843 ret = -ETIMEDOUT;
844 goto out;
848 ret = qemu_vfio_pci_init_irq(s->vfio, s->irq_notifier,
849 VFIO_PCI_MSIX_IRQ_INDEX, errp);
850 if (ret) {
851 goto out;
853 aio_set_event_notifier(bdrv_get_aio_context(bs),
854 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
855 false, nvme_handle_event, nvme_poll_cb,
856 nvme_poll_ready);
858 if (!nvme_identify(bs, namespace, errp)) {
859 ret = -EIO;
860 goto out;
863 /* Set up command queues. */
864 if (!nvme_add_io_queue(bs, errp)) {
865 ret = -EIO;
867 out:
868 if (regs) {
869 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)regs, 0, sizeof(NvmeBar));
872 /* Cleaning up is done in nvme_file_open() upon error. */
873 return ret;
876 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
878 * nvme://0000:44:00.0/1
880 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
881 * is the PCI address, and the last part is the namespace number starting from
882 * 1 according to the NVMe spec. */
883 static void nvme_parse_filename(const char *filename, QDict *options,
884 Error **errp)
886 int pref = strlen("nvme://");
888 if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
889 const char *tmp = filename + pref;
890 char *device;
891 const char *namespace;
892 unsigned long ns;
893 const char *slash = strchr(tmp, '/');
894 if (!slash) {
895 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
896 return;
898 device = g_strndup(tmp, slash - tmp);
899 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
900 g_free(device);
901 namespace = slash + 1;
902 if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
903 error_setg(errp, "Invalid namespace '%s', positive number expected",
904 namespace);
905 return;
907 qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
908 *namespace ? namespace : "1");
912 static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
913 Error **errp)
915 int ret;
916 BDRVNVMeState *s = bs->opaque;
917 NvmeCmd cmd = {
918 .opcode = NVME_ADM_CMD_SET_FEATURES,
919 .nsid = cpu_to_le32(s->nsid),
920 .cdw10 = cpu_to_le32(0x06),
921 .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
924 ret = nvme_admin_cmd_sync(bs, &cmd);
925 if (ret) {
926 error_setg(errp, "Failed to configure NVMe write cache");
928 return ret;
931 static void nvme_close(BlockDriverState *bs)
933 BDRVNVMeState *s = bs->opaque;
935 for (unsigned i = 0; i < s->queue_count; ++i) {
936 nvme_free_queue_pair(s->queues[i]);
938 g_free(s->queues);
939 aio_set_event_notifier(bdrv_get_aio_context(bs),
940 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
941 false, NULL, NULL, NULL);
942 event_notifier_cleanup(&s->irq_notifier[MSIX_SHARED_IRQ_IDX]);
943 qemu_vfio_pci_unmap_bar(s->vfio, 0, s->bar0_wo_map,
944 0, sizeof(NvmeBar) + NVME_DOORBELL_SIZE);
945 qemu_vfio_close(s->vfio);
947 g_free(s->device);
950 static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
951 Error **errp)
953 const char *device;
954 QemuOpts *opts;
955 int namespace;
956 int ret;
957 BDRVNVMeState *s = bs->opaque;
959 bs->supported_write_flags = BDRV_REQ_FUA;
961 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
962 qemu_opts_absorb_qdict(opts, options, &error_abort);
963 device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
964 if (!device) {
965 error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
966 qemu_opts_del(opts);
967 return -EINVAL;
970 namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
971 ret = nvme_init(bs, device, namespace, errp);
972 qemu_opts_del(opts);
973 if (ret) {
974 goto fail;
976 if (flags & BDRV_O_NOCACHE) {
977 if (!s->write_cache_supported) {
978 error_setg(errp,
979 "NVMe controller doesn't support write cache configuration");
980 ret = -EINVAL;
981 } else {
982 ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
983 errp);
985 if (ret) {
986 goto fail;
989 return 0;
990 fail:
991 nvme_close(bs);
992 return ret;
995 static int64_t nvme_getlength(BlockDriverState *bs)
997 BDRVNVMeState *s = bs->opaque;
998 return s->nsze << s->blkshift;
1001 static uint32_t nvme_get_blocksize(BlockDriverState *bs)
1003 BDRVNVMeState *s = bs->opaque;
1004 assert(s->blkshift >= BDRV_SECTOR_BITS && s->blkshift <= 12);
1005 return UINT32_C(1) << s->blkshift;
1008 static int nvme_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1010 uint32_t blocksize = nvme_get_blocksize(bs);
1011 bsz->phys = blocksize;
1012 bsz->log = blocksize;
1013 return 0;
1016 /* Called with s->dma_map_lock */
1017 static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
1018 QEMUIOVector *qiov)
1020 int r = 0;
1021 BDRVNVMeState *s = bs->opaque;
1023 s->dma_map_count -= qiov->size;
1024 if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
1025 r = qemu_vfio_dma_reset_temporary(s->vfio);
1026 if (!r) {
1027 qemu_co_queue_restart_all(&s->dma_flush_queue);
1030 return r;
1033 /* Called with s->dma_map_lock */
1034 static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
1035 NVMeRequest *req, QEMUIOVector *qiov)
1037 BDRVNVMeState *s = bs->opaque;
1038 uint64_t *pagelist = req->prp_list_page;
1039 int i, j, r;
1040 int entries = 0;
1041 Error *local_err = NULL, **errp = NULL;
1043 assert(qiov->size);
1044 assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
1045 assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
1046 for (i = 0; i < qiov->niov; ++i) {
1047 bool retry = true;
1048 uint64_t iova;
1049 size_t len = QEMU_ALIGN_UP(qiov->iov[i].iov_len,
1050 qemu_real_host_page_size);
1051 try_map:
1052 r = qemu_vfio_dma_map(s->vfio,
1053 qiov->iov[i].iov_base,
1054 len, true, &iova, errp);
1055 if (r == -ENOSPC) {
1057 * In addition to the -ENOMEM error, the VFIO_IOMMU_MAP_DMA
1058 * ioctl returns -ENOSPC to signal the user exhausted the DMA
1059 * mappings available for a container since Linux kernel commit
1060 * 492855939bdb ("vfio/type1: Limit DMA mappings per container",
1061 * April 2019, see CVE-2019-3882).
1063 * This block driver already handles this error path by checking
1064 * for the -ENOMEM error, so we directly replace -ENOSPC by
1065 * -ENOMEM. Beside, -ENOSPC has a specific meaning for blockdev
1066 * coroutines: it triggers BLOCKDEV_ON_ERROR_ENOSPC and
1067 * BLOCK_ERROR_ACTION_STOP which stops the VM, asking the operator
1068 * to add more storage to the blockdev. Not something we can do
1069 * easily with an IOMMU :)
1071 r = -ENOMEM;
1073 if (r == -ENOMEM && retry) {
1075 * We exhausted the DMA mappings available for our container:
1076 * recycle the volatile IOVA mappings.
1078 retry = false;
1079 trace_nvme_dma_flush_queue_wait(s);
1080 if (s->dma_map_count) {
1081 trace_nvme_dma_map_flush(s);
1082 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
1083 } else {
1084 r = qemu_vfio_dma_reset_temporary(s->vfio);
1085 if (r) {
1086 goto fail;
1089 errp = &local_err;
1091 goto try_map;
1093 if (r) {
1094 goto fail;
1097 for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
1098 pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
1100 trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
1101 qiov->iov[i].iov_len / s->page_size);
1104 s->dma_map_count += qiov->size;
1106 assert(entries <= s->page_size / sizeof(uint64_t));
1107 switch (entries) {
1108 case 0:
1109 abort();
1110 case 1:
1111 cmd->dptr.prp1 = pagelist[0];
1112 cmd->dptr.prp2 = 0;
1113 break;
1114 case 2:
1115 cmd->dptr.prp1 = pagelist[0];
1116 cmd->dptr.prp2 = pagelist[1];
1117 break;
1118 default:
1119 cmd->dptr.prp1 = pagelist[0];
1120 cmd->dptr.prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
1121 break;
1123 trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
1124 for (i = 0; i < entries; ++i) {
1125 trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
1127 return 0;
1128 fail:
1129 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1130 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1131 * because they are already mapped before calling this function; for
1132 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1133 * calling qemu_vfio_dma_reset_temporary when necessary. */
1134 if (local_err) {
1135 error_reportf_err(local_err, "Cannot map buffer for DMA: ");
1137 return r;
1140 typedef struct {
1141 Coroutine *co;
1142 int ret;
1143 AioContext *ctx;
1144 } NVMeCoData;
1146 static void nvme_rw_cb_bh(void *opaque)
1148 NVMeCoData *data = opaque;
1149 qemu_coroutine_enter(data->co);
1152 static void nvme_rw_cb(void *opaque, int ret)
1154 NVMeCoData *data = opaque;
1155 data->ret = ret;
1156 if (!data->co) {
1157 /* The rw coroutine hasn't yielded, don't try to enter. */
1158 return;
1160 replay_bh_schedule_oneshot_event(data->ctx, nvme_rw_cb_bh, data);
1163 static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
1164 uint64_t offset, uint64_t bytes,
1165 QEMUIOVector *qiov,
1166 bool is_write,
1167 int flags)
1169 int r;
1170 BDRVNVMeState *s = bs->opaque;
1171 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1172 NVMeRequest *req;
1174 uint32_t cdw12 = (((bytes >> s->blkshift) - 1) & 0xFFFF) |
1175 (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
1176 NvmeCmd cmd = {
1177 .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
1178 .nsid = cpu_to_le32(s->nsid),
1179 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1180 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1181 .cdw12 = cpu_to_le32(cdw12),
1183 NVMeCoData data = {
1184 .ctx = bdrv_get_aio_context(bs),
1185 .ret = -EINPROGRESS,
1188 trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
1189 assert(s->queue_count > 1);
1190 req = nvme_get_free_req(ioq);
1191 assert(req);
1193 qemu_co_mutex_lock(&s->dma_map_lock);
1194 r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
1195 qemu_co_mutex_unlock(&s->dma_map_lock);
1196 if (r) {
1197 nvme_put_free_req_and_wake(ioq, req);
1198 return r;
1200 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1202 data.co = qemu_coroutine_self();
1203 while (data.ret == -EINPROGRESS) {
1204 qemu_coroutine_yield();
1207 qemu_co_mutex_lock(&s->dma_map_lock);
1208 r = nvme_cmd_unmap_qiov(bs, qiov);
1209 qemu_co_mutex_unlock(&s->dma_map_lock);
1210 if (r) {
1211 return r;
1214 trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
1215 return data.ret;
1218 static inline bool nvme_qiov_aligned(BlockDriverState *bs,
1219 const QEMUIOVector *qiov)
1221 int i;
1222 BDRVNVMeState *s = bs->opaque;
1224 for (i = 0; i < qiov->niov; ++i) {
1225 if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base,
1226 qemu_real_host_page_size) ||
1227 !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, qemu_real_host_page_size)) {
1228 trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
1229 qiov->iov[i].iov_len, s->page_size);
1230 return false;
1233 return true;
1236 static int nvme_co_prw(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1237 QEMUIOVector *qiov, bool is_write, int flags)
1239 BDRVNVMeState *s = bs->opaque;
1240 int r;
1241 QEMU_AUTO_VFREE uint8_t *buf = NULL;
1242 QEMUIOVector local_qiov;
1243 size_t len = QEMU_ALIGN_UP(bytes, qemu_real_host_page_size);
1244 assert(QEMU_IS_ALIGNED(offset, s->page_size));
1245 assert(QEMU_IS_ALIGNED(bytes, s->page_size));
1246 assert(bytes <= s->max_transfer);
1247 if (nvme_qiov_aligned(bs, qiov)) {
1248 s->stats.aligned_accesses++;
1249 return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
1251 s->stats.unaligned_accesses++;
1252 trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
1253 buf = qemu_try_memalign(qemu_real_host_page_size, len);
1255 if (!buf) {
1256 return -ENOMEM;
1258 qemu_iovec_init(&local_qiov, 1);
1259 if (is_write) {
1260 qemu_iovec_to_buf(qiov, 0, buf, bytes);
1262 qemu_iovec_add(&local_qiov, buf, bytes);
1263 r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
1264 qemu_iovec_destroy(&local_qiov);
1265 if (!r && !is_write) {
1266 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1268 return r;
1271 static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1272 int64_t offset, int64_t bytes,
1273 QEMUIOVector *qiov,
1274 BdrvRequestFlags flags)
1276 return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1279 static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1280 int64_t offset, int64_t bytes,
1281 QEMUIOVector *qiov,
1282 BdrvRequestFlags flags)
1284 return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1287 static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1289 BDRVNVMeState *s = bs->opaque;
1290 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1291 NVMeRequest *req;
1292 NvmeCmd cmd = {
1293 .opcode = NVME_CMD_FLUSH,
1294 .nsid = cpu_to_le32(s->nsid),
1296 NVMeCoData data = {
1297 .ctx = bdrv_get_aio_context(bs),
1298 .ret = -EINPROGRESS,
1301 assert(s->queue_count > 1);
1302 req = nvme_get_free_req(ioq);
1303 assert(req);
1304 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1306 data.co = qemu_coroutine_self();
1307 if (data.ret == -EINPROGRESS) {
1308 qemu_coroutine_yield();
1311 return data.ret;
1315 static coroutine_fn int nvme_co_pwrite_zeroes(BlockDriverState *bs,
1316 int64_t offset,
1317 int64_t bytes,
1318 BdrvRequestFlags flags)
1320 BDRVNVMeState *s = bs->opaque;
1321 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1322 NVMeRequest *req;
1323 uint32_t cdw12;
1325 if (!s->supports_write_zeroes) {
1326 return -ENOTSUP;
1329 if (bytes == 0) {
1330 return 0;
1333 cdw12 = ((bytes >> s->blkshift) - 1) & 0xFFFF;
1335 * We should not lose information. pwrite_zeroes_alignment and
1336 * max_pwrite_zeroes guarantees it.
1338 assert(((cdw12 + 1) << s->blkshift) == bytes);
1340 NvmeCmd cmd = {
1341 .opcode = NVME_CMD_WRITE_ZEROES,
1342 .nsid = cpu_to_le32(s->nsid),
1343 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1344 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1347 NVMeCoData data = {
1348 .ctx = bdrv_get_aio_context(bs),
1349 .ret = -EINPROGRESS,
1352 if (flags & BDRV_REQ_MAY_UNMAP) {
1353 cdw12 |= (1 << 25);
1356 if (flags & BDRV_REQ_FUA) {
1357 cdw12 |= (1 << 30);
1360 cmd.cdw12 = cpu_to_le32(cdw12);
1362 trace_nvme_write_zeroes(s, offset, bytes, flags);
1363 assert(s->queue_count > 1);
1364 req = nvme_get_free_req(ioq);
1365 assert(req);
1367 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1369 data.co = qemu_coroutine_self();
1370 while (data.ret == -EINPROGRESS) {
1371 qemu_coroutine_yield();
1374 trace_nvme_rw_done(s, true, offset, bytes, data.ret);
1375 return data.ret;
1379 static int coroutine_fn nvme_co_pdiscard(BlockDriverState *bs,
1380 int64_t offset,
1381 int64_t bytes)
1383 BDRVNVMeState *s = bs->opaque;
1384 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
1385 NVMeRequest *req;
1386 QEMU_AUTO_VFREE NvmeDsmRange *buf = NULL;
1387 QEMUIOVector local_qiov;
1388 int ret;
1390 NvmeCmd cmd = {
1391 .opcode = NVME_CMD_DSM,
1392 .nsid = cpu_to_le32(s->nsid),
1393 .cdw10 = cpu_to_le32(0), /*number of ranges - 0 based*/
1394 .cdw11 = cpu_to_le32(1 << 2), /*deallocate bit*/
1397 NVMeCoData data = {
1398 .ctx = bdrv_get_aio_context(bs),
1399 .ret = -EINPROGRESS,
1402 if (!s->supports_discard) {
1403 return -ENOTSUP;
1406 assert(s->queue_count > 1);
1409 * Filling the @buf requires @offset and @bytes to satisfy restrictions
1410 * defined in nvme_refresh_limits().
1412 assert(QEMU_IS_ALIGNED(bytes, 1UL << s->blkshift));
1413 assert(QEMU_IS_ALIGNED(offset, 1UL << s->blkshift));
1414 assert((bytes >> s->blkshift) <= UINT32_MAX);
1416 buf = qemu_try_memalign(s->page_size, s->page_size);
1417 if (!buf) {
1418 return -ENOMEM;
1420 memset(buf, 0, s->page_size);
1421 buf->nlb = cpu_to_le32(bytes >> s->blkshift);
1422 buf->slba = cpu_to_le64(offset >> s->blkshift);
1423 buf->cattr = 0;
1425 qemu_iovec_init(&local_qiov, 1);
1426 qemu_iovec_add(&local_qiov, buf, 4096);
1428 req = nvme_get_free_req(ioq);
1429 assert(req);
1431 qemu_co_mutex_lock(&s->dma_map_lock);
1432 ret = nvme_cmd_map_qiov(bs, &cmd, req, &local_qiov);
1433 qemu_co_mutex_unlock(&s->dma_map_lock);
1435 if (ret) {
1436 nvme_put_free_req_and_wake(ioq, req);
1437 goto out;
1440 trace_nvme_dsm(s, offset, bytes);
1442 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
1444 data.co = qemu_coroutine_self();
1445 while (data.ret == -EINPROGRESS) {
1446 qemu_coroutine_yield();
1449 qemu_co_mutex_lock(&s->dma_map_lock);
1450 ret = nvme_cmd_unmap_qiov(bs, &local_qiov);
1451 qemu_co_mutex_unlock(&s->dma_map_lock);
1453 if (ret) {
1454 goto out;
1457 ret = data.ret;
1458 trace_nvme_dsm_done(s, offset, bytes, ret);
1459 out:
1460 qemu_iovec_destroy(&local_qiov);
1461 return ret;
1465 static int coroutine_fn nvme_co_truncate(BlockDriverState *bs, int64_t offset,
1466 bool exact, PreallocMode prealloc,
1467 BdrvRequestFlags flags, Error **errp)
1469 int64_t cur_length;
1471 if (prealloc != PREALLOC_MODE_OFF) {
1472 error_setg(errp, "Unsupported preallocation mode '%s'",
1473 PreallocMode_str(prealloc));
1474 return -ENOTSUP;
1477 cur_length = nvme_getlength(bs);
1478 if (offset != cur_length && exact) {
1479 error_setg(errp, "Cannot resize NVMe devices");
1480 return -ENOTSUP;
1481 } else if (offset > cur_length) {
1482 error_setg(errp, "Cannot grow NVMe devices");
1483 return -EINVAL;
1486 return 0;
1489 static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1490 BlockReopenQueue *queue, Error **errp)
1492 return 0;
1495 static void nvme_refresh_filename(BlockDriverState *bs)
1497 BDRVNVMeState *s = bs->opaque;
1499 snprintf(bs->exact_filename, sizeof(bs->exact_filename), "nvme://%s/%i",
1500 s->device, s->nsid);
1503 static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1505 BDRVNVMeState *s = bs->opaque;
1507 bs->bl.opt_mem_alignment = s->page_size;
1508 bs->bl.request_alignment = s->page_size;
1509 bs->bl.max_transfer = s->max_transfer;
1512 * Look at nvme_co_pwrite_zeroes: after shift and decrement we should get
1513 * at most 0xFFFF
1515 bs->bl.max_pwrite_zeroes = 1ULL << (s->blkshift + 16);
1516 bs->bl.pwrite_zeroes_alignment = MAX(bs->bl.request_alignment,
1517 1UL << s->blkshift);
1519 bs->bl.max_pdiscard = (uint64_t)UINT32_MAX << s->blkshift;
1520 bs->bl.pdiscard_alignment = MAX(bs->bl.request_alignment,
1521 1UL << s->blkshift);
1524 static void nvme_detach_aio_context(BlockDriverState *bs)
1526 BDRVNVMeState *s = bs->opaque;
1528 for (unsigned i = 0; i < s->queue_count; i++) {
1529 NVMeQueuePair *q = s->queues[i];
1531 qemu_bh_delete(q->completion_bh);
1532 q->completion_bh = NULL;
1535 aio_set_event_notifier(bdrv_get_aio_context(bs),
1536 &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1537 false, NULL, NULL, NULL);
1540 static void nvme_attach_aio_context(BlockDriverState *bs,
1541 AioContext *new_context)
1543 BDRVNVMeState *s = bs->opaque;
1545 s->aio_context = new_context;
1546 aio_set_event_notifier(new_context, &s->irq_notifier[MSIX_SHARED_IRQ_IDX],
1547 false, nvme_handle_event, nvme_poll_cb,
1548 nvme_poll_ready);
1550 for (unsigned i = 0; i < s->queue_count; i++) {
1551 NVMeQueuePair *q = s->queues[i];
1553 q->completion_bh =
1554 aio_bh_new(new_context, nvme_process_completion_bh, q);
1558 static void nvme_aio_plug(BlockDriverState *bs)
1560 BDRVNVMeState *s = bs->opaque;
1561 assert(!s->plugged);
1562 s->plugged = true;
1565 static void nvme_aio_unplug(BlockDriverState *bs)
1567 BDRVNVMeState *s = bs->opaque;
1568 assert(s->plugged);
1569 s->plugged = false;
1570 for (unsigned i = INDEX_IO(0); i < s->queue_count; i++) {
1571 NVMeQueuePair *q = s->queues[i];
1572 qemu_mutex_lock(&q->lock);
1573 nvme_kick(q);
1574 nvme_process_completion(q);
1575 qemu_mutex_unlock(&q->lock);
1579 static void nvme_register_buf(BlockDriverState *bs, void *host, size_t size)
1581 int ret;
1582 Error *local_err = NULL;
1583 BDRVNVMeState *s = bs->opaque;
1585 ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL, &local_err);
1586 if (ret) {
1587 /* FIXME: we may run out of IOVA addresses after repeated
1588 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1589 * doesn't reclaim addresses for fixed mappings. */
1590 error_reportf_err(local_err, "nvme_register_buf failed: ");
1594 static void nvme_unregister_buf(BlockDriverState *bs, void *host)
1596 BDRVNVMeState *s = bs->opaque;
1598 qemu_vfio_dma_unmap(s->vfio, host);
1601 static BlockStatsSpecific *nvme_get_specific_stats(BlockDriverState *bs)
1603 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
1604 BDRVNVMeState *s = bs->opaque;
1606 stats->driver = BLOCKDEV_DRIVER_NVME;
1607 stats->u.nvme = (BlockStatsSpecificNvme) {
1608 .completion_errors = s->stats.completion_errors,
1609 .aligned_accesses = s->stats.aligned_accesses,
1610 .unaligned_accesses = s->stats.unaligned_accesses,
1613 return stats;
1616 static const char *const nvme_strong_runtime_opts[] = {
1617 NVME_BLOCK_OPT_DEVICE,
1618 NVME_BLOCK_OPT_NAMESPACE,
1620 NULL
1623 static BlockDriver bdrv_nvme = {
1624 .format_name = "nvme",
1625 .protocol_name = "nvme",
1626 .instance_size = sizeof(BDRVNVMeState),
1628 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
1629 .create_opts = &bdrv_create_opts_simple,
1631 .bdrv_parse_filename = nvme_parse_filename,
1632 .bdrv_file_open = nvme_file_open,
1633 .bdrv_close = nvme_close,
1634 .bdrv_getlength = nvme_getlength,
1635 .bdrv_probe_blocksizes = nvme_probe_blocksizes,
1636 .bdrv_co_truncate = nvme_co_truncate,
1638 .bdrv_co_preadv = nvme_co_preadv,
1639 .bdrv_co_pwritev = nvme_co_pwritev,
1641 .bdrv_co_pwrite_zeroes = nvme_co_pwrite_zeroes,
1642 .bdrv_co_pdiscard = nvme_co_pdiscard,
1644 .bdrv_co_flush_to_disk = nvme_co_flush,
1645 .bdrv_reopen_prepare = nvme_reopen_prepare,
1647 .bdrv_refresh_filename = nvme_refresh_filename,
1648 .bdrv_refresh_limits = nvme_refresh_limits,
1649 .strong_runtime_opts = nvme_strong_runtime_opts,
1650 .bdrv_get_specific_stats = nvme_get_specific_stats,
1652 .bdrv_detach_aio_context = nvme_detach_aio_context,
1653 .bdrv_attach_aio_context = nvme_attach_aio_context,
1655 .bdrv_io_plug = nvme_aio_plug,
1656 .bdrv_io_unplug = nvme_aio_unplug,
1658 .bdrv_register_buf = nvme_register_buf,
1659 .bdrv_unregister_buf = nvme_unregister_buf,
1662 static void bdrv_nvme_init(void)
1664 bdrv_register(&bdrv_nvme);
1667 block_init(bdrv_nvme_init);