2 * NVMe block driver based on vfio
4 * Copyright 2016 - 2018 Red Hat, Inc.
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/memalign.h"
25 #include "qemu/vfio-helpers.h"
26 #include "block/block-io.h"
27 #include "block/block_int.h"
28 #include "sysemu/replay.h"
31 #include "block/nvme.h"
33 #define NVME_SQ_ENTRY_BYTES 64
34 #define NVME_CQ_ENTRY_BYTES 16
35 #define NVME_QUEUE_SIZE 128
36 #define NVME_DOORBELL_SIZE 4096
39 * We have to leave one slot empty as that is the full queue case where
42 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
44 typedef struct BDRVNVMeState BDRVNVMeState
;
46 /* Same index is used for queues and IRQs */
48 #define INDEX_IO(n) (1 + n)
50 /* This driver shares a single MSIX IRQ for the admin and I/O queues */
52 MSIX_SHARED_IRQ_IDX
= 0,
60 /* Hardware MMIO register */
61 volatile uint32_t *doorbell
;
65 BlockCompletionFunc
*cb
;
69 uint64_t prp_list_iova
;
70 int free_req_next
; /* q->reqs[] index of next free req */
76 /* Read from I/O code path, initialized under BQL */
80 /* Fields protected by BQL */
81 uint8_t *prp_list_pages
;
83 /* Fields protected by @lock */
84 CoQueue free_req_queue
;
88 NVMeRequest reqs
[NVME_NUM_REQS
];
92 /* Thread-safe, no lock necessary */
93 QEMUBH
*completion_bh
;
96 struct BDRVNVMeState
{
97 AioContext
*aio_context
;
100 /* Memory mapped registers */
105 /* The submission/completion queue pairs.
109 NVMeQueuePair
**queues
;
110 unsigned queue_count
;
112 /* How many uint32_t elements does each doorbell entry take. */
113 size_t doorbell_scale
;
114 bool write_cache_supported
;
115 EventNotifier irq_notifier
[MSIX_IRQ_COUNT
];
117 uint64_t nsze
; /* Namespace size reported by identify command */
118 int nsid
; /* The namespace id to read/write data. */
121 uint64_t max_transfer
;
124 bool supports_write_zeroes
;
125 bool supports_discard
;
127 CoMutex dma_map_lock
;
128 CoQueue dma_flush_queue
;
130 /* Total size of mapped qiov, accessed under dma_map_lock */
133 /* PCI address (required for nvme_refresh_filename()) */
137 uint64_t completion_errors
;
138 uint64_t aligned_accesses
;
139 uint64_t unaligned_accesses
;
143 #define NVME_BLOCK_OPT_DEVICE "device"
144 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
146 static void nvme_process_completion_bh(void *opaque
);
148 static QemuOptsList runtime_opts
= {
150 .head
= QTAILQ_HEAD_INITIALIZER(runtime_opts
.head
),
153 .name
= NVME_BLOCK_OPT_DEVICE
,
154 .type
= QEMU_OPT_STRING
,
155 .help
= "NVMe PCI device address",
158 .name
= NVME_BLOCK_OPT_NAMESPACE
,
159 .type
= QEMU_OPT_NUMBER
,
160 .help
= "NVMe namespace",
162 { /* end of list */ }
166 /* Returns true on success, false on failure. */
167 static bool nvme_init_queue(BDRVNVMeState
*s
, NVMeQueue
*q
,
168 unsigned nentries
, size_t entry_bytes
, Error
**errp
)
173 bytes
= ROUND_UP(nentries
* entry_bytes
, qemu_real_host_page_size());
174 q
->head
= q
->tail
= 0;
175 q
->queue
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
177 error_setg(errp
, "Cannot allocate queue");
180 memset(q
->queue
, 0, bytes
);
181 r
= qemu_vfio_dma_map(s
->vfio
, q
->queue
, bytes
, false, &q
->iova
, errp
);
183 error_prepend(errp
, "Cannot map queue: ");
188 static void nvme_free_queue(NVMeQueue
*q
)
190 qemu_vfree(q
->queue
);
193 static void nvme_free_queue_pair(NVMeQueuePair
*q
)
195 trace_nvme_free_queue_pair(q
->index
, q
, &q
->cq
, &q
->sq
);
196 if (q
->completion_bh
) {
197 qemu_bh_delete(q
->completion_bh
);
199 nvme_free_queue(&q
->sq
);
200 nvme_free_queue(&q
->cq
);
201 qemu_vfree(q
->prp_list_pages
);
202 qemu_mutex_destroy(&q
->lock
);
206 static void nvme_free_req_queue_cb(void *opaque
)
208 NVMeQueuePair
*q
= opaque
;
210 qemu_mutex_lock(&q
->lock
);
211 while (q
->free_req_head
!= -1 &&
212 qemu_co_enter_next(&q
->free_req_queue
, &q
->lock
)) {
213 /* Retry waiting requests */
215 qemu_mutex_unlock(&q
->lock
);
218 static NVMeQueuePair
*nvme_create_queue_pair(BDRVNVMeState
*s
,
219 AioContext
*aio_context
,
220 unsigned idx
, size_t size
,
225 uint64_t prp_list_iova
;
228 q
= g_try_new0(NVMeQueuePair
, 1);
230 error_setg(errp
, "Cannot allocate queue pair");
233 trace_nvme_create_queue_pair(idx
, q
, size
, aio_context
,
234 event_notifier_get_fd(s
->irq_notifier
));
235 bytes
= QEMU_ALIGN_UP(s
->page_size
* NVME_NUM_REQS
,
236 qemu_real_host_page_size());
237 q
->prp_list_pages
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
238 if (!q
->prp_list_pages
) {
239 error_setg(errp
, "Cannot allocate PRP page list");
242 memset(q
->prp_list_pages
, 0, bytes
);
243 qemu_mutex_init(&q
->lock
);
246 qemu_co_queue_init(&q
->free_req_queue
);
247 q
->completion_bh
= aio_bh_new(aio_context
, nvme_process_completion_bh
, q
);
248 r
= qemu_vfio_dma_map(s
->vfio
, q
->prp_list_pages
, bytes
,
249 false, &prp_list_iova
, errp
);
251 error_prepend(errp
, "Cannot map buffer for DMA: ");
254 q
->free_req_head
= -1;
255 for (i
= 0; i
< NVME_NUM_REQS
; i
++) {
256 NVMeRequest
*req
= &q
->reqs
[i
];
258 req
->free_req_next
= q
->free_req_head
;
259 q
->free_req_head
= i
;
260 req
->prp_list_page
= q
->prp_list_pages
+ i
* s
->page_size
;
261 req
->prp_list_iova
= prp_list_iova
+ i
* s
->page_size
;
264 if (!nvme_init_queue(s
, &q
->sq
, size
, NVME_SQ_ENTRY_BYTES
, errp
)) {
267 q
->sq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].sq_tail
;
269 if (!nvme_init_queue(s
, &q
->cq
, size
, NVME_CQ_ENTRY_BYTES
, errp
)) {
272 q
->cq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].cq_head
;
276 nvme_free_queue_pair(q
);
281 static void nvme_kick(NVMeQueuePair
*q
)
283 BDRVNVMeState
*s
= q
->s
;
285 if (s
->plugged
|| !q
->need_kick
) {
288 trace_nvme_kick(s
, q
->index
);
289 assert(!(q
->sq
.tail
& 0xFF00));
290 /* Fence the write to submission queue entry before notifying the device. */
292 *q
->sq
.doorbell
= cpu_to_le32(q
->sq
.tail
);
293 q
->inflight
+= q
->need_kick
;
297 static NVMeRequest
*nvme_get_free_req_nofail_locked(NVMeQueuePair
*q
)
301 req
= &q
->reqs
[q
->free_req_head
];
302 q
->free_req_head
= req
->free_req_next
;
303 req
->free_req_next
= -1;
307 /* Return a free request element if any, otherwise return NULL. */
308 static NVMeRequest
*nvme_get_free_req_nowait(NVMeQueuePair
*q
)
310 QEMU_LOCK_GUARD(&q
->lock
);
311 if (q
->free_req_head
== -1) {
314 return nvme_get_free_req_nofail_locked(q
);
318 * Wait for a free request to become available if necessary, then
321 static coroutine_fn NVMeRequest
*nvme_get_free_req(NVMeQueuePair
*q
)
323 QEMU_LOCK_GUARD(&q
->lock
);
325 while (q
->free_req_head
== -1) {
326 trace_nvme_free_req_queue_wait(q
->s
, q
->index
);
327 qemu_co_queue_wait(&q
->free_req_queue
, &q
->lock
);
330 return nvme_get_free_req_nofail_locked(q
);
334 static void nvme_put_free_req_locked(NVMeQueuePair
*q
, NVMeRequest
*req
)
336 req
->free_req_next
= q
->free_req_head
;
337 q
->free_req_head
= req
- q
->reqs
;
341 static void nvme_wake_free_req_locked(NVMeQueuePair
*q
)
343 if (!qemu_co_queue_empty(&q
->free_req_queue
)) {
344 replay_bh_schedule_oneshot_event(q
->s
->aio_context
,
345 nvme_free_req_queue_cb
, q
);
349 /* Insert a request in the freelist and wake waiters */
350 static void nvme_put_free_req_and_wake(NVMeQueuePair
*q
, NVMeRequest
*req
)
352 qemu_mutex_lock(&q
->lock
);
353 nvme_put_free_req_locked(q
, req
);
354 nvme_wake_free_req_locked(q
);
355 qemu_mutex_unlock(&q
->lock
);
358 static inline int nvme_translate_error(const NvmeCqe
*c
)
360 uint16_t status
= (le16_to_cpu(c
->status
) >> 1) & 0xFF;
362 trace_nvme_error(le32_to_cpu(c
->result
),
363 le16_to_cpu(c
->sq_head
),
364 le16_to_cpu(c
->sq_id
),
366 le16_to_cpu(status
));
381 static bool nvme_process_completion(NVMeQueuePair
*q
)
383 BDRVNVMeState
*s
= q
->s
;
384 bool progress
= false;
389 trace_nvme_process_completion(s
, q
->index
, q
->inflight
);
391 trace_nvme_process_completion_queue_plugged(s
, q
->index
);
396 * Support re-entrancy when a request cb() function invokes aio_poll().
397 * Pending completions must be visible to aio_poll() so that a cb()
398 * function can wait for the completion of another request.
400 * The aio_poll() loop will execute our BH and we'll resume completion
403 qemu_bh_schedule(q
->completion_bh
);
405 assert(q
->inflight
>= 0);
406 while (q
->inflight
) {
410 c
= (NvmeCqe
*)&q
->cq
.queue
[q
->cq
.head
* NVME_CQ_ENTRY_BYTES
];
411 if ((le16_to_cpu(c
->status
) & 0x1) == q
->cq_phase
) {
414 ret
= nvme_translate_error(c
);
416 s
->stats
.completion_errors
++;
418 q
->cq
.head
= (q
->cq
.head
+ 1) % NVME_QUEUE_SIZE
;
420 q
->cq_phase
= !q
->cq_phase
;
422 cid
= le16_to_cpu(c
->cid
);
423 if (cid
== 0 || cid
> NVME_QUEUE_SIZE
) {
424 warn_report("NVMe: Unexpected CID in completion queue: %"PRIu32
", "
425 "queue size: %u", cid
, NVME_QUEUE_SIZE
);
428 trace_nvme_complete_command(s
, q
->index
, cid
);
429 preq
= &q
->reqs
[cid
- 1];
431 assert(req
.cid
== cid
);
433 nvme_put_free_req_locked(q
, preq
);
434 preq
->cb
= preq
->opaque
= NULL
;
436 qemu_mutex_unlock(&q
->lock
);
437 req
.cb(req
.opaque
, ret
);
438 qemu_mutex_lock(&q
->lock
);
442 /* Notify the device so it can post more completions. */
444 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
445 nvme_wake_free_req_locked(q
);
448 qemu_bh_cancel(q
->completion_bh
);
453 static void nvme_process_completion_bh(void *opaque
)
455 NVMeQueuePair
*q
= opaque
;
458 * We're being invoked because a nvme_process_completion() cb() function
459 * called aio_poll(). The callback may be waiting for further completions
460 * so notify the device that it has space to fill in more completions now.
463 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
464 nvme_wake_free_req_locked(q
);
466 nvme_process_completion(q
);
469 static void nvme_trace_command(const NvmeCmd
*cmd
)
473 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW
)) {
476 for (i
= 0; i
< 8; ++i
) {
477 uint8_t *cmdp
= (uint8_t *)cmd
+ i
* 8;
478 trace_nvme_submit_command_raw(cmdp
[0], cmdp
[1], cmdp
[2], cmdp
[3],
479 cmdp
[4], cmdp
[5], cmdp
[6], cmdp
[7]);
483 static void nvme_submit_command(NVMeQueuePair
*q
, NVMeRequest
*req
,
484 NvmeCmd
*cmd
, BlockCompletionFunc cb
,
489 req
->opaque
= opaque
;
490 cmd
->cid
= cpu_to_le16(req
->cid
);
492 trace_nvme_submit_command(q
->s
, q
->index
, req
->cid
);
493 nvme_trace_command(cmd
);
494 qemu_mutex_lock(&q
->lock
);
495 memcpy((uint8_t *)q
->sq
.queue
+
496 q
->sq
.tail
* NVME_SQ_ENTRY_BYTES
, cmd
, sizeof(*cmd
));
497 q
->sq
.tail
= (q
->sq
.tail
+ 1) % NVME_QUEUE_SIZE
;
500 nvme_process_completion(q
);
501 qemu_mutex_unlock(&q
->lock
);
504 static void nvme_admin_cmd_sync_cb(void *opaque
, int ret
)
511 static int nvme_admin_cmd_sync(BlockDriverState
*bs
, NvmeCmd
*cmd
)
513 BDRVNVMeState
*s
= bs
->opaque
;
514 NVMeQueuePair
*q
= s
->queues
[INDEX_ADMIN
];
515 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
517 int ret
= -EINPROGRESS
;
518 req
= nvme_get_free_req_nowait(q
);
522 nvme_submit_command(q
, req
, cmd
, nvme_admin_cmd_sync_cb
, &ret
);
524 AIO_WAIT_WHILE(aio_context
, ret
== -EINPROGRESS
);
528 /* Returns true on success, false on failure. */
529 static bool nvme_identify(BlockDriverState
*bs
, int namespace, Error
**errp
)
531 BDRVNVMeState
*s
= bs
->opaque
;
533 QEMU_AUTO_VFREE
union {
542 .opcode
= NVME_ADM_CMD_IDENTIFY
,
543 .cdw10
= cpu_to_le32(0x1),
545 size_t id_size
= QEMU_ALIGN_UP(sizeof(*id
), qemu_real_host_page_size());
547 id
= qemu_try_memalign(qemu_real_host_page_size(), id_size
);
549 error_setg(errp
, "Cannot allocate buffer for identify response");
552 r
= qemu_vfio_dma_map(s
->vfio
, id
, id_size
, true, &iova
, errp
);
554 error_prepend(errp
, "Cannot map buffer for DMA: ");
558 memset(id
, 0, id_size
);
559 cmd
.dptr
.prp1
= cpu_to_le64(iova
);
560 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
561 error_setg(errp
, "Failed to identify controller");
565 if (le32_to_cpu(id
->ctrl
.nn
) < namespace) {
566 error_setg(errp
, "Invalid namespace");
569 s
->write_cache_supported
= le32_to_cpu(id
->ctrl
.vwc
) & 0x1;
570 s
->max_transfer
= (id
->ctrl
.mdts
? 1 << id
->ctrl
.mdts
: 0) * s
->page_size
;
571 /* For now the page list buffer per command is one page, to hold at most
572 * s->page_size / sizeof(uint64_t) entries. */
573 s
->max_transfer
= MIN_NON_ZERO(s
->max_transfer
,
574 s
->page_size
/ sizeof(uint64_t) * s
->page_size
);
576 oncs
= le16_to_cpu(id
->ctrl
.oncs
);
577 s
->supports_write_zeroes
= !!(oncs
& NVME_ONCS_WRITE_ZEROES
);
578 s
->supports_discard
= !!(oncs
& NVME_ONCS_DSM
);
580 memset(id
, 0, id_size
);
582 cmd
.nsid
= cpu_to_le32(namespace);
583 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
584 error_setg(errp
, "Failed to identify namespace");
588 s
->nsze
= le64_to_cpu(id
->ns
.nsze
);
589 lbaf
= &id
->ns
.lbaf
[NVME_ID_NS_FLBAS_INDEX(id
->ns
.flbas
)];
591 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id
->ns
.dlfeat
) &&
592 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id
->ns
.dlfeat
) ==
593 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES
) {
594 bs
->supported_write_flags
|= BDRV_REQ_MAY_UNMAP
;
598 error_setg(errp
, "Namespaces with metadata are not yet supported");
602 if (lbaf
->ds
< BDRV_SECTOR_BITS
|| lbaf
->ds
> 12 ||
603 (1 << lbaf
->ds
) > s
->page_size
)
605 error_setg(errp
, "Namespace has unsupported block size (2^%d)",
611 s
->blkshift
= lbaf
->ds
;
613 qemu_vfio_dma_unmap(s
->vfio
, id
);
618 static void nvme_poll_queue(NVMeQueuePair
*q
)
620 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
621 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
623 trace_nvme_poll_queue(q
->s
, q
->index
);
625 * Do an early check for completions. q->lock isn't needed because
626 * nvme_process_completion() only runs in the event loop thread and
627 * cannot race with itself.
629 if ((le16_to_cpu(cqe
->status
) & 0x1) == q
->cq_phase
) {
633 qemu_mutex_lock(&q
->lock
);
634 while (nvme_process_completion(q
)) {
637 qemu_mutex_unlock(&q
->lock
);
640 static void nvme_poll_queues(BDRVNVMeState
*s
)
644 for (i
= 0; i
< s
->queue_count
; i
++) {
645 nvme_poll_queue(s
->queues
[i
]);
649 static void nvme_handle_event(EventNotifier
*n
)
651 BDRVNVMeState
*s
= container_of(n
, BDRVNVMeState
,
652 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
654 trace_nvme_handle_event(s
);
655 event_notifier_test_and_clear(n
);
659 static bool nvme_add_io_queue(BlockDriverState
*bs
, Error
**errp
)
661 BDRVNVMeState
*s
= bs
->opaque
;
662 unsigned n
= s
->queue_count
;
665 unsigned queue_size
= NVME_QUEUE_SIZE
;
667 assert(n
<= UINT16_MAX
);
668 q
= nvme_create_queue_pair(s
, bdrv_get_aio_context(bs
),
669 n
, queue_size
, errp
);
674 .opcode
= NVME_ADM_CMD_CREATE_CQ
,
675 .dptr
.prp1
= cpu_to_le64(q
->cq
.iova
),
676 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
677 .cdw11
= cpu_to_le32(NVME_CQ_IEN
| NVME_CQ_PC
),
679 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
680 error_setg(errp
, "Failed to create CQ io queue [%u]", n
);
684 .opcode
= NVME_ADM_CMD_CREATE_SQ
,
685 .dptr
.prp1
= cpu_to_le64(q
->sq
.iova
),
686 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
687 .cdw11
= cpu_to_le32(NVME_SQ_PC
| (n
<< 16)),
689 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
690 error_setg(errp
, "Failed to create SQ io queue [%u]", n
);
693 s
->queues
= g_renew(NVMeQueuePair
*, s
->queues
, n
+ 1);
698 nvme_free_queue_pair(q
);
702 static bool nvme_poll_cb(void *opaque
)
704 EventNotifier
*e
= opaque
;
705 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
706 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
709 for (i
= 0; i
< s
->queue_count
; i
++) {
710 NVMeQueuePair
*q
= s
->queues
[i
];
711 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
712 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
715 * q->lock isn't needed because nvme_process_completion() only runs in
716 * the event loop thread and cannot race with itself.
718 if ((le16_to_cpu(cqe
->status
) & 0x1) != q
->cq_phase
) {
725 static void nvme_poll_ready(EventNotifier
*e
)
727 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
728 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
733 static int nvme_init(BlockDriverState
*bs
, const char *device
, int namespace,
736 BDRVNVMeState
*s
= bs
->opaque
;
738 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
743 uint64_t deadline
, now
;
744 volatile NvmeBar
*regs
= NULL
;
746 qemu_co_mutex_init(&s
->dma_map_lock
);
747 qemu_co_queue_init(&s
->dma_flush_queue
);
748 s
->device
= g_strdup(device
);
750 s
->aio_context
= bdrv_get_aio_context(bs
);
751 ret
= event_notifier_init(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
], 0);
753 error_setg(errp
, "Failed to init event notifier");
757 s
->vfio
= qemu_vfio_open_pci(device
, errp
);
763 regs
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0, sizeof(NvmeBar
),
764 PROT_READ
| PROT_WRITE
, errp
);
769 /* Perform initialize sequence as described in NVMe spec "7.6.1
770 * Initialization". */
772 cap
= le64_to_cpu(regs
->cap
);
773 trace_nvme_controller_capability_raw(cap
);
774 trace_nvme_controller_capability("Maximum Queue Entries Supported",
775 1 + NVME_CAP_MQES(cap
));
776 trace_nvme_controller_capability("Contiguous Queues Required",
778 trace_nvme_controller_capability("Doorbell Stride",
779 1 << (2 + NVME_CAP_DSTRD(cap
)));
780 trace_nvme_controller_capability("Subsystem Reset Supported",
781 NVME_CAP_NSSRS(cap
));
782 trace_nvme_controller_capability("Memory Page Size Minimum",
783 1 << (12 + NVME_CAP_MPSMIN(cap
)));
784 trace_nvme_controller_capability("Memory Page Size Maximum",
785 1 << (12 + NVME_CAP_MPSMAX(cap
)));
786 if (!NVME_CAP_CSS(cap
)) {
787 error_setg(errp
, "Device doesn't support NVMe command set");
792 s
->page_size
= 1u << (12 + NVME_CAP_MPSMIN(cap
));
793 s
->doorbell_scale
= (4 << NVME_CAP_DSTRD(cap
)) / sizeof(uint32_t);
794 bs
->bl
.opt_mem_alignment
= s
->page_size
;
795 bs
->bl
.request_alignment
= s
->page_size
;
796 timeout_ms
= MIN(500 * NVME_CAP_TO(cap
), 30000);
798 ver
= le32_to_cpu(regs
->vs
);
799 trace_nvme_controller_spec_version(extract32(ver
, 16, 16),
800 extract32(ver
, 8, 8),
801 extract32(ver
, 0, 8));
803 /* Reset device to get a clean state. */
804 regs
->cc
= cpu_to_le32(le32_to_cpu(regs
->cc
) & 0xFE);
805 /* Wait for CSTS.RDY = 0. */
806 deadline
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + timeout_ms
* SCALE_MS
;
807 while (NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
808 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
809 error_setg(errp
, "Timeout while waiting for device to reset (%"
817 s
->bar0_wo_map
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0,
818 sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
,
820 s
->doorbells
= (void *)((uintptr_t)s
->bar0_wo_map
+ sizeof(NvmeBar
));
826 /* Set up admin queue. */
827 s
->queues
= g_new(NVMeQueuePair
*, 1);
828 q
= nvme_create_queue_pair(s
, aio_context
, 0, NVME_QUEUE_SIZE
, errp
);
833 s
->queues
[INDEX_ADMIN
] = q
;
835 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE
- 1) & 0xF000);
836 regs
->aqa
= cpu_to_le32(((NVME_QUEUE_SIZE
- 1) << AQA_ACQS_SHIFT
) |
837 ((NVME_QUEUE_SIZE
- 1) << AQA_ASQS_SHIFT
));
838 regs
->asq
= cpu_to_le64(q
->sq
.iova
);
839 regs
->acq
= cpu_to_le64(q
->cq
.iova
);
841 /* After setting up all control registers we can enable device now. */
842 regs
->cc
= cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES
) << CC_IOCQES_SHIFT
) |
843 (ctz32(NVME_SQ_ENTRY_BYTES
) << CC_IOSQES_SHIFT
) |
845 /* Wait for CSTS.RDY = 1. */
846 now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
847 deadline
= now
+ timeout_ms
* SCALE_MS
;
848 while (!NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
849 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
850 error_setg(errp
, "Timeout while waiting for device to start (%"
858 ret
= qemu_vfio_pci_init_irq(s
->vfio
, s
->irq_notifier
,
859 VFIO_PCI_MSIX_IRQ_INDEX
, errp
);
863 aio_set_event_notifier(bdrv_get_aio_context(bs
),
864 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
865 false, nvme_handle_event
, nvme_poll_cb
,
868 if (!nvme_identify(bs
, namespace, errp
)) {
873 /* Set up command queues. */
874 if (!nvme_add_io_queue(bs
, errp
)) {
879 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)regs
, 0, sizeof(NvmeBar
));
882 /* Cleaning up is done in nvme_file_open() upon error. */
886 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
888 * nvme://0000:44:00.0/1
890 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
891 * is the PCI address, and the last part is the namespace number starting from
892 * 1 according to the NVMe spec. */
893 static void nvme_parse_filename(const char *filename
, QDict
*options
,
896 int pref
= strlen("nvme://");
898 if (strlen(filename
) > pref
&& !strncmp(filename
, "nvme://", pref
)) {
899 const char *tmp
= filename
+ pref
;
901 const char *namespace;
903 const char *slash
= strchr(tmp
, '/');
905 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, tmp
);
908 device
= g_strndup(tmp
, slash
- tmp
);
909 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, device
);
911 namespace = slash
+ 1;
912 if (*namespace && qemu_strtoul(namespace, NULL
, 10, &ns
)) {
913 error_setg(errp
, "Invalid namespace '%s', positive number expected",
917 qdict_put_str(options
, NVME_BLOCK_OPT_NAMESPACE
,
918 *namespace ? namespace : "1");
922 static int nvme_enable_disable_write_cache(BlockDriverState
*bs
, bool enable
,
926 BDRVNVMeState
*s
= bs
->opaque
;
928 .opcode
= NVME_ADM_CMD_SET_FEATURES
,
929 .nsid
= cpu_to_le32(s
->nsid
),
930 .cdw10
= cpu_to_le32(0x06),
931 .cdw11
= cpu_to_le32(enable
? 0x01 : 0x00),
934 ret
= nvme_admin_cmd_sync(bs
, &cmd
);
936 error_setg(errp
, "Failed to configure NVMe write cache");
941 static void nvme_close(BlockDriverState
*bs
)
943 BDRVNVMeState
*s
= bs
->opaque
;
945 for (unsigned i
= 0; i
< s
->queue_count
; ++i
) {
946 nvme_free_queue_pair(s
->queues
[i
]);
949 aio_set_event_notifier(bdrv_get_aio_context(bs
),
950 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
951 false, NULL
, NULL
, NULL
);
952 event_notifier_cleanup(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
953 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, s
->bar0_wo_map
,
954 0, sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
);
955 qemu_vfio_close(s
->vfio
);
960 static int nvme_file_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
967 BDRVNVMeState
*s
= bs
->opaque
;
969 bs
->supported_write_flags
= BDRV_REQ_FUA
;
971 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
972 qemu_opts_absorb_qdict(opts
, options
, &error_abort
);
973 device
= qemu_opt_get(opts
, NVME_BLOCK_OPT_DEVICE
);
975 error_setg(errp
, "'" NVME_BLOCK_OPT_DEVICE
"' option is required");
980 namespace = qemu_opt_get_number(opts
, NVME_BLOCK_OPT_NAMESPACE
, 1);
981 ret
= nvme_init(bs
, device
, namespace, errp
);
986 if (flags
& BDRV_O_NOCACHE
) {
987 if (!s
->write_cache_supported
) {
989 "NVMe controller doesn't support write cache configuration");
992 ret
= nvme_enable_disable_write_cache(bs
, !(flags
& BDRV_O_NOCACHE
),
1005 static int64_t coroutine_fn
nvme_co_getlength(BlockDriverState
*bs
)
1007 BDRVNVMeState
*s
= bs
->opaque
;
1008 return s
->nsze
<< s
->blkshift
;
1011 static uint32_t nvme_get_blocksize(BlockDriverState
*bs
)
1013 BDRVNVMeState
*s
= bs
->opaque
;
1014 assert(s
->blkshift
>= BDRV_SECTOR_BITS
&& s
->blkshift
<= 12);
1015 return UINT32_C(1) << s
->blkshift
;
1018 static int nvme_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1020 uint32_t blocksize
= nvme_get_blocksize(bs
);
1021 bsz
->phys
= blocksize
;
1022 bsz
->log
= blocksize
;
1026 /* Called with s->dma_map_lock */
1027 static coroutine_fn
int nvme_cmd_unmap_qiov(BlockDriverState
*bs
,
1031 BDRVNVMeState
*s
= bs
->opaque
;
1033 s
->dma_map_count
-= qiov
->size
;
1034 if (!s
->dma_map_count
&& !qemu_co_queue_empty(&s
->dma_flush_queue
)) {
1035 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1037 qemu_co_queue_restart_all(&s
->dma_flush_queue
);
1043 /* Called with s->dma_map_lock */
1044 static coroutine_fn
int nvme_cmd_map_qiov(BlockDriverState
*bs
, NvmeCmd
*cmd
,
1045 NVMeRequest
*req
, QEMUIOVector
*qiov
)
1047 BDRVNVMeState
*s
= bs
->opaque
;
1048 uint64_t *pagelist
= req
->prp_list_page
;
1051 Error
*local_err
= NULL
, **errp
= NULL
;
1054 assert(QEMU_IS_ALIGNED(qiov
->size
, s
->page_size
));
1055 assert(qiov
->size
/ s
->page_size
<= s
->page_size
/ sizeof(uint64_t));
1056 for (i
= 0; i
< qiov
->niov
; ++i
) {
1059 size_t len
= QEMU_ALIGN_UP(qiov
->iov
[i
].iov_len
,
1060 qemu_real_host_page_size());
1062 r
= qemu_vfio_dma_map(s
->vfio
,
1063 qiov
->iov
[i
].iov_base
,
1064 len
, true, &iova
, errp
);
1067 * In addition to the -ENOMEM error, the VFIO_IOMMU_MAP_DMA
1068 * ioctl returns -ENOSPC to signal the user exhausted the DMA
1069 * mappings available for a container since Linux kernel commit
1070 * 492855939bdb ("vfio/type1: Limit DMA mappings per container",
1071 * April 2019, see CVE-2019-3882).
1073 * This block driver already handles this error path by checking
1074 * for the -ENOMEM error, so we directly replace -ENOSPC by
1075 * -ENOMEM. Beside, -ENOSPC has a specific meaning for blockdev
1076 * coroutines: it triggers BLOCKDEV_ON_ERROR_ENOSPC and
1077 * BLOCK_ERROR_ACTION_STOP which stops the VM, asking the operator
1078 * to add more storage to the blockdev. Not something we can do
1079 * easily with an IOMMU :)
1083 if (r
== -ENOMEM
&& retry
) {
1085 * We exhausted the DMA mappings available for our container:
1086 * recycle the volatile IOVA mappings.
1089 trace_nvme_dma_flush_queue_wait(s
);
1090 if (s
->dma_map_count
) {
1091 trace_nvme_dma_map_flush(s
);
1092 qemu_co_queue_wait(&s
->dma_flush_queue
, &s
->dma_map_lock
);
1094 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1107 for (j
= 0; j
< qiov
->iov
[i
].iov_len
/ s
->page_size
; j
++) {
1108 pagelist
[entries
++] = cpu_to_le64(iova
+ j
* s
->page_size
);
1110 trace_nvme_cmd_map_qiov_iov(s
, i
, qiov
->iov
[i
].iov_base
,
1111 qiov
->iov
[i
].iov_len
/ s
->page_size
);
1114 s
->dma_map_count
+= qiov
->size
;
1116 assert(entries
<= s
->page_size
/ sizeof(uint64_t));
1121 cmd
->dptr
.prp1
= pagelist
[0];
1125 cmd
->dptr
.prp1
= pagelist
[0];
1126 cmd
->dptr
.prp2
= pagelist
[1];
1129 cmd
->dptr
.prp1
= pagelist
[0];
1130 cmd
->dptr
.prp2
= cpu_to_le64(req
->prp_list_iova
+ sizeof(uint64_t));
1133 trace_nvme_cmd_map_qiov(s
, cmd
, req
, qiov
, entries
);
1134 for (i
= 0; i
< entries
; ++i
) {
1135 trace_nvme_cmd_map_qiov_pages(s
, i
, pagelist
[i
]);
1139 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1140 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1141 * because they are already mapped before calling this function; for
1142 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1143 * calling qemu_vfio_dma_reset_temporary when necessary. */
1145 error_reportf_err(local_err
, "Cannot map buffer for DMA: ");
1156 static void nvme_rw_cb_bh(void *opaque
)
1158 NVMeCoData
*data
= opaque
;
1159 qemu_coroutine_enter(data
->co
);
1162 static void nvme_rw_cb(void *opaque
, int ret
)
1164 NVMeCoData
*data
= opaque
;
1167 /* The rw coroutine hasn't yielded, don't try to enter. */
1170 replay_bh_schedule_oneshot_event(data
->ctx
, nvme_rw_cb_bh
, data
);
1173 static coroutine_fn
int nvme_co_prw_aligned(BlockDriverState
*bs
,
1174 uint64_t offset
, uint64_t bytes
,
1180 BDRVNVMeState
*s
= bs
->opaque
;
1181 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1184 uint32_t cdw12
= (((bytes
>> s
->blkshift
) - 1) & 0xFFFF) |
1185 (flags
& BDRV_REQ_FUA
? 1 << 30 : 0);
1187 .opcode
= is_write
? NVME_CMD_WRITE
: NVME_CMD_READ
,
1188 .nsid
= cpu_to_le32(s
->nsid
),
1189 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1190 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1191 .cdw12
= cpu_to_le32(cdw12
),
1194 .ctx
= bdrv_get_aio_context(bs
),
1195 .ret
= -EINPROGRESS
,
1198 trace_nvme_prw_aligned(s
, is_write
, offset
, bytes
, flags
, qiov
->niov
);
1199 assert(s
->queue_count
> 1);
1200 req
= nvme_get_free_req(ioq
);
1203 qemu_co_mutex_lock(&s
->dma_map_lock
);
1204 r
= nvme_cmd_map_qiov(bs
, &cmd
, req
, qiov
);
1205 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1207 nvme_put_free_req_and_wake(ioq
, req
);
1210 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1212 data
.co
= qemu_coroutine_self();
1213 while (data
.ret
== -EINPROGRESS
) {
1214 qemu_coroutine_yield();
1217 qemu_co_mutex_lock(&s
->dma_map_lock
);
1218 r
= nvme_cmd_unmap_qiov(bs
, qiov
);
1219 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1224 trace_nvme_rw_done(s
, is_write
, offset
, bytes
, data
.ret
);
1228 static inline bool nvme_qiov_aligned(BlockDriverState
*bs
,
1229 const QEMUIOVector
*qiov
)
1232 BDRVNVMeState
*s
= bs
->opaque
;
1234 for (i
= 0; i
< qiov
->niov
; ++i
) {
1235 if (!QEMU_PTR_IS_ALIGNED(qiov
->iov
[i
].iov_base
,
1236 qemu_real_host_page_size()) ||
1237 !QEMU_IS_ALIGNED(qiov
->iov
[i
].iov_len
, qemu_real_host_page_size())) {
1238 trace_nvme_qiov_unaligned(qiov
, i
, qiov
->iov
[i
].iov_base
,
1239 qiov
->iov
[i
].iov_len
, s
->page_size
);
1246 static coroutine_fn
int nvme_co_prw(BlockDriverState
*bs
,
1247 uint64_t offset
, uint64_t bytes
,
1248 QEMUIOVector
*qiov
, bool is_write
,
1251 BDRVNVMeState
*s
= bs
->opaque
;
1253 QEMU_AUTO_VFREE
uint8_t *buf
= NULL
;
1254 QEMUIOVector local_qiov
;
1255 size_t len
= QEMU_ALIGN_UP(bytes
, qemu_real_host_page_size());
1256 assert(QEMU_IS_ALIGNED(offset
, s
->page_size
));
1257 assert(QEMU_IS_ALIGNED(bytes
, s
->page_size
));
1258 assert(bytes
<= s
->max_transfer
);
1259 if (nvme_qiov_aligned(bs
, qiov
)) {
1260 s
->stats
.aligned_accesses
++;
1261 return nvme_co_prw_aligned(bs
, offset
, bytes
, qiov
, is_write
, flags
);
1263 s
->stats
.unaligned_accesses
++;
1264 trace_nvme_prw_buffered(s
, offset
, bytes
, qiov
->niov
, is_write
);
1265 buf
= qemu_try_memalign(qemu_real_host_page_size(), len
);
1270 qemu_iovec_init(&local_qiov
, 1);
1272 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
1274 qemu_iovec_add(&local_qiov
, buf
, bytes
);
1275 r
= nvme_co_prw_aligned(bs
, offset
, bytes
, &local_qiov
, is_write
, flags
);
1276 qemu_iovec_destroy(&local_qiov
);
1277 if (!r
&& !is_write
) {
1278 qemu_iovec_from_buf(qiov
, 0, buf
, bytes
);
1283 static coroutine_fn
int nvme_co_preadv(BlockDriverState
*bs
,
1284 int64_t offset
, int64_t bytes
,
1286 BdrvRequestFlags flags
)
1288 return nvme_co_prw(bs
, offset
, bytes
, qiov
, false, flags
);
1291 static coroutine_fn
int nvme_co_pwritev(BlockDriverState
*bs
,
1292 int64_t offset
, int64_t bytes
,
1294 BdrvRequestFlags flags
)
1296 return nvme_co_prw(bs
, offset
, bytes
, qiov
, true, flags
);
1299 static coroutine_fn
int nvme_co_flush(BlockDriverState
*bs
)
1301 BDRVNVMeState
*s
= bs
->opaque
;
1302 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1305 .opcode
= NVME_CMD_FLUSH
,
1306 .nsid
= cpu_to_le32(s
->nsid
),
1309 .ctx
= bdrv_get_aio_context(bs
),
1310 .ret
= -EINPROGRESS
,
1313 assert(s
->queue_count
> 1);
1314 req
= nvme_get_free_req(ioq
);
1316 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1318 data
.co
= qemu_coroutine_self();
1319 if (data
.ret
== -EINPROGRESS
) {
1320 qemu_coroutine_yield();
1327 static coroutine_fn
int nvme_co_pwrite_zeroes(BlockDriverState
*bs
,
1330 BdrvRequestFlags flags
)
1332 BDRVNVMeState
*s
= bs
->opaque
;
1333 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1337 if (!s
->supports_write_zeroes
) {
1345 cdw12
= ((bytes
>> s
->blkshift
) - 1) & 0xFFFF;
1347 * We should not lose information. pwrite_zeroes_alignment and
1348 * max_pwrite_zeroes guarantees it.
1350 assert(((cdw12
+ 1) << s
->blkshift
) == bytes
);
1353 .opcode
= NVME_CMD_WRITE_ZEROES
,
1354 .nsid
= cpu_to_le32(s
->nsid
),
1355 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1356 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1360 .ctx
= bdrv_get_aio_context(bs
),
1361 .ret
= -EINPROGRESS
,
1364 if (flags
& BDRV_REQ_MAY_UNMAP
) {
1368 if (flags
& BDRV_REQ_FUA
) {
1372 cmd
.cdw12
= cpu_to_le32(cdw12
);
1374 trace_nvme_write_zeroes(s
, offset
, bytes
, flags
);
1375 assert(s
->queue_count
> 1);
1376 req
= nvme_get_free_req(ioq
);
1379 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1381 data
.co
= qemu_coroutine_self();
1382 while (data
.ret
== -EINPROGRESS
) {
1383 qemu_coroutine_yield();
1386 trace_nvme_rw_done(s
, true, offset
, bytes
, data
.ret
);
1391 static int coroutine_fn
nvme_co_pdiscard(BlockDriverState
*bs
,
1395 BDRVNVMeState
*s
= bs
->opaque
;
1396 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1398 QEMU_AUTO_VFREE NvmeDsmRange
*buf
= NULL
;
1399 QEMUIOVector local_qiov
;
1403 .opcode
= NVME_CMD_DSM
,
1404 .nsid
= cpu_to_le32(s
->nsid
),
1405 .cdw10
= cpu_to_le32(0), /*number of ranges - 0 based*/
1406 .cdw11
= cpu_to_le32(1 << 2), /*deallocate bit*/
1410 .ctx
= bdrv_get_aio_context(bs
),
1411 .ret
= -EINPROGRESS
,
1414 if (!s
->supports_discard
) {
1418 assert(s
->queue_count
> 1);
1421 * Filling the @buf requires @offset and @bytes to satisfy restrictions
1422 * defined in nvme_refresh_limits().
1424 assert(QEMU_IS_ALIGNED(bytes
, 1UL << s
->blkshift
));
1425 assert(QEMU_IS_ALIGNED(offset
, 1UL << s
->blkshift
));
1426 assert((bytes
>> s
->blkshift
) <= UINT32_MAX
);
1428 buf
= qemu_try_memalign(s
->page_size
, s
->page_size
);
1432 memset(buf
, 0, s
->page_size
);
1433 buf
->nlb
= cpu_to_le32(bytes
>> s
->blkshift
);
1434 buf
->slba
= cpu_to_le64(offset
>> s
->blkshift
);
1437 qemu_iovec_init(&local_qiov
, 1);
1438 qemu_iovec_add(&local_qiov
, buf
, 4096);
1440 req
= nvme_get_free_req(ioq
);
1443 qemu_co_mutex_lock(&s
->dma_map_lock
);
1444 ret
= nvme_cmd_map_qiov(bs
, &cmd
, req
, &local_qiov
);
1445 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1448 nvme_put_free_req_and_wake(ioq
, req
);
1452 trace_nvme_dsm(s
, offset
, bytes
);
1454 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1456 data
.co
= qemu_coroutine_self();
1457 while (data
.ret
== -EINPROGRESS
) {
1458 qemu_coroutine_yield();
1461 qemu_co_mutex_lock(&s
->dma_map_lock
);
1462 ret
= nvme_cmd_unmap_qiov(bs
, &local_qiov
);
1463 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1470 trace_nvme_dsm_done(s
, offset
, bytes
, ret
);
1472 qemu_iovec_destroy(&local_qiov
);
1477 static int coroutine_fn
nvme_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1478 bool exact
, PreallocMode prealloc
,
1479 BdrvRequestFlags flags
, Error
**errp
)
1483 if (prealloc
!= PREALLOC_MODE_OFF
) {
1484 error_setg(errp
, "Unsupported preallocation mode '%s'",
1485 PreallocMode_str(prealloc
));
1489 cur_length
= nvme_co_getlength(bs
);
1490 if (offset
!= cur_length
&& exact
) {
1491 error_setg(errp
, "Cannot resize NVMe devices");
1493 } else if (offset
> cur_length
) {
1494 error_setg(errp
, "Cannot grow NVMe devices");
1501 static int nvme_reopen_prepare(BDRVReopenState
*reopen_state
,
1502 BlockReopenQueue
*queue
, Error
**errp
)
1507 static void nvme_refresh_filename(BlockDriverState
*bs
)
1509 BDRVNVMeState
*s
= bs
->opaque
;
1511 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
), "nvme://%s/%i",
1512 s
->device
, s
->nsid
);
1515 static void nvme_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1517 BDRVNVMeState
*s
= bs
->opaque
;
1519 bs
->bl
.opt_mem_alignment
= s
->page_size
;
1520 bs
->bl
.request_alignment
= s
->page_size
;
1521 bs
->bl
.max_transfer
= s
->max_transfer
;
1524 * Look at nvme_co_pwrite_zeroes: after shift and decrement we should get
1527 bs
->bl
.max_pwrite_zeroes
= 1ULL << (s
->blkshift
+ 16);
1528 bs
->bl
.pwrite_zeroes_alignment
= MAX(bs
->bl
.request_alignment
,
1529 1UL << s
->blkshift
);
1531 bs
->bl
.max_pdiscard
= (uint64_t)UINT32_MAX
<< s
->blkshift
;
1532 bs
->bl
.pdiscard_alignment
= MAX(bs
->bl
.request_alignment
,
1533 1UL << s
->blkshift
);
1536 static void nvme_detach_aio_context(BlockDriverState
*bs
)
1538 BDRVNVMeState
*s
= bs
->opaque
;
1540 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1541 NVMeQueuePair
*q
= s
->queues
[i
];
1543 qemu_bh_delete(q
->completion_bh
);
1544 q
->completion_bh
= NULL
;
1547 aio_set_event_notifier(bdrv_get_aio_context(bs
),
1548 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1549 false, NULL
, NULL
, NULL
);
1552 static void nvme_attach_aio_context(BlockDriverState
*bs
,
1553 AioContext
*new_context
)
1555 BDRVNVMeState
*s
= bs
->opaque
;
1557 s
->aio_context
= new_context
;
1558 aio_set_event_notifier(new_context
, &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1559 false, nvme_handle_event
, nvme_poll_cb
,
1562 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1563 NVMeQueuePair
*q
= s
->queues
[i
];
1566 aio_bh_new(new_context
, nvme_process_completion_bh
, q
);
1570 static void coroutine_fn
nvme_co_io_plug(BlockDriverState
*bs
)
1572 BDRVNVMeState
*s
= bs
->opaque
;
1573 assert(!s
->plugged
);
1577 static void coroutine_fn
nvme_co_io_unplug(BlockDriverState
*bs
)
1579 BDRVNVMeState
*s
= bs
->opaque
;
1582 for (unsigned i
= INDEX_IO(0); i
< s
->queue_count
; i
++) {
1583 NVMeQueuePair
*q
= s
->queues
[i
];
1584 qemu_mutex_lock(&q
->lock
);
1586 nvme_process_completion(q
);
1587 qemu_mutex_unlock(&q
->lock
);
1591 static bool nvme_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
1595 BDRVNVMeState
*s
= bs
->opaque
;
1598 * FIXME: we may run out of IOVA addresses after repeated
1599 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1600 * doesn't reclaim addresses for fixed mappings.
1602 ret
= qemu_vfio_dma_map(s
->vfio
, host
, size
, false, NULL
, errp
);
1606 static void nvme_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
1608 BDRVNVMeState
*s
= bs
->opaque
;
1610 qemu_vfio_dma_unmap(s
->vfio
, host
);
1613 static BlockStatsSpecific
*nvme_get_specific_stats(BlockDriverState
*bs
)
1615 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
1616 BDRVNVMeState
*s
= bs
->opaque
;
1618 stats
->driver
= BLOCKDEV_DRIVER_NVME
;
1619 stats
->u
.nvme
= (BlockStatsSpecificNvme
) {
1620 .completion_errors
= s
->stats
.completion_errors
,
1621 .aligned_accesses
= s
->stats
.aligned_accesses
,
1622 .unaligned_accesses
= s
->stats
.unaligned_accesses
,
1628 static const char *const nvme_strong_runtime_opts
[] = {
1629 NVME_BLOCK_OPT_DEVICE
,
1630 NVME_BLOCK_OPT_NAMESPACE
,
1635 static BlockDriver bdrv_nvme
= {
1636 .format_name
= "nvme",
1637 .protocol_name
= "nvme",
1638 .instance_size
= sizeof(BDRVNVMeState
),
1640 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
1641 .create_opts
= &bdrv_create_opts_simple
,
1643 .bdrv_parse_filename
= nvme_parse_filename
,
1644 .bdrv_file_open
= nvme_file_open
,
1645 .bdrv_close
= nvme_close
,
1646 .bdrv_co_getlength
= nvme_co_getlength
,
1647 .bdrv_probe_blocksizes
= nvme_probe_blocksizes
,
1648 .bdrv_co_truncate
= nvme_co_truncate
,
1650 .bdrv_co_preadv
= nvme_co_preadv
,
1651 .bdrv_co_pwritev
= nvme_co_pwritev
,
1653 .bdrv_co_pwrite_zeroes
= nvme_co_pwrite_zeroes
,
1654 .bdrv_co_pdiscard
= nvme_co_pdiscard
,
1656 .bdrv_co_flush_to_disk
= nvme_co_flush
,
1657 .bdrv_reopen_prepare
= nvme_reopen_prepare
,
1659 .bdrv_refresh_filename
= nvme_refresh_filename
,
1660 .bdrv_refresh_limits
= nvme_refresh_limits
,
1661 .strong_runtime_opts
= nvme_strong_runtime_opts
,
1662 .bdrv_get_specific_stats
= nvme_get_specific_stats
,
1664 .bdrv_detach_aio_context
= nvme_detach_aio_context
,
1665 .bdrv_attach_aio_context
= nvme_attach_aio_context
,
1667 .bdrv_co_io_plug
= nvme_co_io_plug
,
1668 .bdrv_co_io_unplug
= nvme_co_io_unplug
,
1670 .bdrv_register_buf
= nvme_register_buf
,
1671 .bdrv_unregister_buf
= nvme_unregister_buf
,
1674 static void bdrv_nvme_init(void)
1676 bdrv_register(&bdrv_nvme
);
1679 block_init(bdrv_nvme_init
);