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/defer-call.h"
20 #include "qemu/error-report.h"
21 #include "qemu/main-loop.h"
22 #include "qemu/module.h"
23 #include "qemu/cutils.h"
24 #include "qemu/option.h"
25 #include "qemu/memalign.h"
26 #include "qemu/vfio-helpers.h"
27 #include "block/block-io.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "sysemu/replay.h"
33 #include "block/nvme.h"
35 #define NVME_SQ_ENTRY_BYTES 64
36 #define NVME_CQ_ENTRY_BYTES 16
37 #define NVME_QUEUE_SIZE 128
38 #define NVME_DOORBELL_SIZE 4096
41 * We have to leave one slot empty as that is the full queue case where
44 #define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
46 typedef struct BDRVNVMeState BDRVNVMeState
;
48 /* Same index is used for queues and IRQs */
50 #define INDEX_IO(n) (1 + n)
52 /* This driver shares a single MSIX IRQ for the admin and I/O queues */
54 MSIX_SHARED_IRQ_IDX
= 0,
62 /* Hardware MMIO register */
63 volatile uint32_t *doorbell
;
67 BlockCompletionFunc
*cb
;
71 uint64_t prp_list_iova
;
72 int free_req_next
; /* q->reqs[] index of next free req */
78 /* Read from I/O code path, initialized under BQL */
82 /* Fields protected by BQL */
83 uint8_t *prp_list_pages
;
85 /* Fields protected by @lock */
86 CoQueue free_req_queue
;
90 NVMeRequest reqs
[NVME_NUM_REQS
];
94 /* Thread-safe, no lock necessary */
95 QEMUBH
*completion_bh
;
98 struct BDRVNVMeState
{
99 AioContext
*aio_context
;
102 /* Memory mapped registers */
107 /* The submission/completion queue pairs.
111 NVMeQueuePair
**queues
;
112 unsigned queue_count
;
114 /* How many uint32_t elements does each doorbell entry take. */
115 size_t doorbell_scale
;
116 bool write_cache_supported
;
117 EventNotifier irq_notifier
[MSIX_IRQ_COUNT
];
119 uint64_t nsze
; /* Namespace size reported by identify command */
120 int nsid
; /* The namespace id to read/write data. */
123 uint64_t max_transfer
;
125 bool supports_write_zeroes
;
126 bool supports_discard
;
128 CoMutex dma_map_lock
;
129 CoQueue dma_flush_queue
;
131 /* Total size of mapped qiov, accessed under dma_map_lock */
134 /* PCI address (required for nvme_refresh_filename()) */
138 uint64_t completion_errors
;
139 uint64_t aligned_accesses
;
140 uint64_t unaligned_accesses
;
144 #define NVME_BLOCK_OPT_DEVICE "device"
145 #define NVME_BLOCK_OPT_NAMESPACE "namespace"
147 static void nvme_process_completion_bh(void *opaque
);
149 static QemuOptsList runtime_opts
= {
151 .head
= QTAILQ_HEAD_INITIALIZER(runtime_opts
.head
),
154 .name
= NVME_BLOCK_OPT_DEVICE
,
155 .type
= QEMU_OPT_STRING
,
156 .help
= "NVMe PCI device address",
159 .name
= NVME_BLOCK_OPT_NAMESPACE
,
160 .type
= QEMU_OPT_NUMBER
,
161 .help
= "NVMe namespace",
163 { /* end of list */ }
167 /* Returns true on success, false on failure. */
168 static bool nvme_init_queue(BDRVNVMeState
*s
, NVMeQueue
*q
,
169 unsigned nentries
, size_t entry_bytes
, Error
**errp
)
174 bytes
= ROUND_UP(nentries
* entry_bytes
, qemu_real_host_page_size());
175 q
->head
= q
->tail
= 0;
176 q
->queue
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
178 error_setg(errp
, "Cannot allocate queue");
181 memset(q
->queue
, 0, bytes
);
182 r
= qemu_vfio_dma_map(s
->vfio
, q
->queue
, bytes
, false, &q
->iova
, errp
);
184 error_prepend(errp
, "Cannot map queue: ");
189 static void nvme_free_queue(NVMeQueue
*q
)
191 qemu_vfree(q
->queue
);
194 static void nvme_free_queue_pair(NVMeQueuePair
*q
)
196 trace_nvme_free_queue_pair(q
->index
, q
, &q
->cq
, &q
->sq
);
197 if (q
->completion_bh
) {
198 qemu_bh_delete(q
->completion_bh
);
200 nvme_free_queue(&q
->sq
);
201 nvme_free_queue(&q
->cq
);
202 qemu_vfree(q
->prp_list_pages
);
203 qemu_mutex_destroy(&q
->lock
);
207 static void nvme_free_req_queue_cb(void *opaque
)
209 NVMeQueuePair
*q
= opaque
;
211 qemu_mutex_lock(&q
->lock
);
212 while (q
->free_req_head
!= -1 &&
213 qemu_co_enter_next(&q
->free_req_queue
, &q
->lock
)) {
214 /* Retry waiting requests */
216 qemu_mutex_unlock(&q
->lock
);
219 static NVMeQueuePair
*nvme_create_queue_pair(BDRVNVMeState
*s
,
220 AioContext
*aio_context
,
221 unsigned idx
, size_t size
,
226 uint64_t prp_list_iova
;
229 q
= g_try_new0(NVMeQueuePair
, 1);
231 error_setg(errp
, "Cannot allocate queue pair");
234 trace_nvme_create_queue_pair(idx
, q
, size
, aio_context
,
235 event_notifier_get_fd(s
->irq_notifier
));
236 bytes
= QEMU_ALIGN_UP(s
->page_size
* NVME_NUM_REQS
,
237 qemu_real_host_page_size());
238 q
->prp_list_pages
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
239 if (!q
->prp_list_pages
) {
240 error_setg(errp
, "Cannot allocate PRP page list");
243 memset(q
->prp_list_pages
, 0, bytes
);
244 qemu_mutex_init(&q
->lock
);
247 qemu_co_queue_init(&q
->free_req_queue
);
248 q
->completion_bh
= aio_bh_new(aio_context
, nvme_process_completion_bh
, q
);
249 r
= qemu_vfio_dma_map(s
->vfio
, q
->prp_list_pages
, bytes
,
250 false, &prp_list_iova
, errp
);
252 error_prepend(errp
, "Cannot map buffer for DMA: ");
255 q
->free_req_head
= -1;
256 for (i
= 0; i
< NVME_NUM_REQS
; i
++) {
257 NVMeRequest
*req
= &q
->reqs
[i
];
259 req
->free_req_next
= q
->free_req_head
;
260 q
->free_req_head
= i
;
261 req
->prp_list_page
= q
->prp_list_pages
+ i
* s
->page_size
;
262 req
->prp_list_iova
= prp_list_iova
+ i
* s
->page_size
;
265 if (!nvme_init_queue(s
, &q
->sq
, size
, NVME_SQ_ENTRY_BYTES
, errp
)) {
268 q
->sq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].sq_tail
;
270 if (!nvme_init_queue(s
, &q
->cq
, size
, NVME_CQ_ENTRY_BYTES
, errp
)) {
273 q
->cq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].cq_head
;
277 nvme_free_queue_pair(q
);
282 static void nvme_kick(NVMeQueuePair
*q
)
284 BDRVNVMeState
*s
= q
->s
;
289 trace_nvme_kick(s
, q
->index
);
290 assert(!(q
->sq
.tail
& 0xFF00));
291 /* Fence the write to submission queue entry before notifying the device. */
293 *q
->sq
.doorbell
= cpu_to_le32(q
->sq
.tail
);
294 q
->inflight
+= q
->need_kick
;
298 static NVMeRequest
*nvme_get_free_req_nofail_locked(NVMeQueuePair
*q
)
302 req
= &q
->reqs
[q
->free_req_head
];
303 q
->free_req_head
= req
->free_req_next
;
304 req
->free_req_next
= -1;
308 /* Return a free request element if any, otherwise return NULL. */
309 static NVMeRequest
*nvme_get_free_req_nowait(NVMeQueuePair
*q
)
311 QEMU_LOCK_GUARD(&q
->lock
);
312 if (q
->free_req_head
== -1) {
315 return nvme_get_free_req_nofail_locked(q
);
319 * Wait for a free request to become available if necessary, then
322 static coroutine_fn NVMeRequest
*nvme_get_free_req(NVMeQueuePair
*q
)
324 QEMU_LOCK_GUARD(&q
->lock
);
326 while (q
->free_req_head
== -1) {
327 trace_nvme_free_req_queue_wait(q
->s
, q
->index
);
328 qemu_co_queue_wait(&q
->free_req_queue
, &q
->lock
);
331 return nvme_get_free_req_nofail_locked(q
);
335 static void nvme_put_free_req_locked(NVMeQueuePair
*q
, NVMeRequest
*req
)
337 req
->free_req_next
= q
->free_req_head
;
338 q
->free_req_head
= req
- q
->reqs
;
342 static void nvme_wake_free_req_locked(NVMeQueuePair
*q
)
344 if (!qemu_co_queue_empty(&q
->free_req_queue
)) {
345 replay_bh_schedule_oneshot_event(q
->s
->aio_context
,
346 nvme_free_req_queue_cb
, q
);
350 /* Insert a request in the freelist and wake waiters */
351 static void nvme_put_free_req_and_wake(NVMeQueuePair
*q
, NVMeRequest
*req
)
353 qemu_mutex_lock(&q
->lock
);
354 nvme_put_free_req_locked(q
, req
);
355 nvme_wake_free_req_locked(q
);
356 qemu_mutex_unlock(&q
->lock
);
359 static inline int nvme_translate_error(const NvmeCqe
*c
)
361 uint16_t status
= (le16_to_cpu(c
->status
) >> 1) & 0xFF;
363 trace_nvme_error(le32_to_cpu(c
->result
),
364 le16_to_cpu(c
->sq_head
),
365 le16_to_cpu(c
->sq_id
),
367 le16_to_cpu(status
));
382 static bool nvme_process_completion(NVMeQueuePair
*q
)
384 BDRVNVMeState
*s
= q
->s
;
385 bool progress
= false;
390 trace_nvme_process_completion(s
, q
->index
, q
->inflight
);
393 * Support re-entrancy when a request cb() function invokes aio_poll().
394 * Pending completions must be visible to aio_poll() so that a cb()
395 * function can wait for the completion of another request.
397 * The aio_poll() loop will execute our BH and we'll resume completion
400 qemu_bh_schedule(q
->completion_bh
);
402 assert(q
->inflight
>= 0);
403 while (q
->inflight
) {
407 c
= (NvmeCqe
*)&q
->cq
.queue
[q
->cq
.head
* NVME_CQ_ENTRY_BYTES
];
408 if ((le16_to_cpu(c
->status
) & 0x1) == q
->cq_phase
) {
411 ret
= nvme_translate_error(c
);
413 s
->stats
.completion_errors
++;
415 q
->cq
.head
= (q
->cq
.head
+ 1) % NVME_QUEUE_SIZE
;
417 q
->cq_phase
= !q
->cq_phase
;
419 cid
= le16_to_cpu(c
->cid
);
420 if (cid
== 0 || cid
> NVME_QUEUE_SIZE
) {
421 warn_report("NVMe: Unexpected CID in completion queue: %"PRIu32
", "
422 "queue size: %u", cid
, NVME_QUEUE_SIZE
);
425 trace_nvme_complete_command(s
, q
->index
, cid
);
426 preq
= &q
->reqs
[cid
- 1];
428 assert(req
.cid
== cid
);
430 nvme_put_free_req_locked(q
, preq
);
431 preq
->cb
= preq
->opaque
= NULL
;
433 qemu_mutex_unlock(&q
->lock
);
434 req
.cb(req
.opaque
, ret
);
435 qemu_mutex_lock(&q
->lock
);
439 /* Notify the device so it can post more completions. */
441 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
442 nvme_wake_free_req_locked(q
);
445 qemu_bh_cancel(q
->completion_bh
);
450 static void nvme_process_completion_bh(void *opaque
)
452 NVMeQueuePair
*q
= opaque
;
455 * We're being invoked because a nvme_process_completion() cb() function
456 * called aio_poll(). The callback may be waiting for further completions
457 * so notify the device that it has space to fill in more completions now.
460 *q
->cq
.doorbell
= cpu_to_le32(q
->cq
.head
);
461 nvme_wake_free_req_locked(q
);
463 nvme_process_completion(q
);
466 static void nvme_trace_command(const NvmeCmd
*cmd
)
470 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW
)) {
473 for (i
= 0; i
< 8; ++i
) {
474 uint8_t *cmdp
= (uint8_t *)cmd
+ i
* 8;
475 trace_nvme_submit_command_raw(cmdp
[0], cmdp
[1], cmdp
[2], cmdp
[3],
476 cmdp
[4], cmdp
[5], cmdp
[6], cmdp
[7]);
480 static void nvme_deferred_fn(void *opaque
)
482 NVMeQueuePair
*q
= opaque
;
484 QEMU_LOCK_GUARD(&q
->lock
);
486 nvme_process_completion(q
);
489 static void nvme_submit_command(NVMeQueuePair
*q
, NVMeRequest
*req
,
490 NvmeCmd
*cmd
, BlockCompletionFunc cb
,
495 req
->opaque
= opaque
;
496 cmd
->cid
= cpu_to_le16(req
->cid
);
498 trace_nvme_submit_command(q
->s
, q
->index
, req
->cid
);
499 nvme_trace_command(cmd
);
500 qemu_mutex_lock(&q
->lock
);
501 memcpy((uint8_t *)q
->sq
.queue
+
502 q
->sq
.tail
* NVME_SQ_ENTRY_BYTES
, cmd
, sizeof(*cmd
));
503 q
->sq
.tail
= (q
->sq
.tail
+ 1) % NVME_QUEUE_SIZE
;
505 qemu_mutex_unlock(&q
->lock
);
507 defer_call(nvme_deferred_fn
, q
);
510 static void nvme_admin_cmd_sync_cb(void *opaque
, int ret
)
517 static int nvme_admin_cmd_sync(BlockDriverState
*bs
, NvmeCmd
*cmd
)
519 BDRVNVMeState
*s
= bs
->opaque
;
520 NVMeQueuePair
*q
= s
->queues
[INDEX_ADMIN
];
521 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
523 int ret
= -EINPROGRESS
;
524 req
= nvme_get_free_req_nowait(q
);
528 nvme_submit_command(q
, req
, cmd
, nvme_admin_cmd_sync_cb
, &ret
);
530 AIO_WAIT_WHILE(aio_context
, ret
== -EINPROGRESS
);
534 /* Returns true on success, false on failure. */
535 static bool nvme_identify(BlockDriverState
*bs
, int namespace, Error
**errp
)
537 BDRVNVMeState
*s
= bs
->opaque
;
539 QEMU_AUTO_VFREE
union {
548 .opcode
= NVME_ADM_CMD_IDENTIFY
,
549 .cdw10
= cpu_to_le32(0x1),
551 size_t id_size
= QEMU_ALIGN_UP(sizeof(*id
), qemu_real_host_page_size());
553 id
= qemu_try_memalign(qemu_real_host_page_size(), id_size
);
555 error_setg(errp
, "Cannot allocate buffer for identify response");
558 r
= qemu_vfio_dma_map(s
->vfio
, id
, id_size
, true, &iova
, errp
);
560 error_prepend(errp
, "Cannot map buffer for DMA: ");
564 memset(id
, 0, id_size
);
565 cmd
.dptr
.prp1
= cpu_to_le64(iova
);
566 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
567 error_setg(errp
, "Failed to identify controller");
571 if (le32_to_cpu(id
->ctrl
.nn
) < namespace) {
572 error_setg(errp
, "Invalid namespace");
575 s
->write_cache_supported
= le32_to_cpu(id
->ctrl
.vwc
) & 0x1;
576 s
->max_transfer
= (id
->ctrl
.mdts
? 1 << id
->ctrl
.mdts
: 0) * s
->page_size
;
577 /* For now the page list buffer per command is one page, to hold at most
578 * s->page_size / sizeof(uint64_t) entries. */
579 s
->max_transfer
= MIN_NON_ZERO(s
->max_transfer
,
580 s
->page_size
/ sizeof(uint64_t) * s
->page_size
);
582 oncs
= le16_to_cpu(id
->ctrl
.oncs
);
583 s
->supports_write_zeroes
= !!(oncs
& NVME_ONCS_WRITE_ZEROES
);
584 s
->supports_discard
= !!(oncs
& NVME_ONCS_DSM
);
586 memset(id
, 0, id_size
);
588 cmd
.nsid
= cpu_to_le32(namespace);
589 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
590 error_setg(errp
, "Failed to identify namespace");
594 s
->nsze
= le64_to_cpu(id
->ns
.nsze
);
595 lbaf
= &id
->ns
.lbaf
[NVME_ID_NS_FLBAS_INDEX(id
->ns
.flbas
)];
597 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id
->ns
.dlfeat
) &&
598 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id
->ns
.dlfeat
) ==
599 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES
) {
600 bs
->supported_write_flags
|= BDRV_REQ_MAY_UNMAP
;
604 error_setg(errp
, "Namespaces with metadata are not yet supported");
608 if (lbaf
->ds
< BDRV_SECTOR_BITS
|| lbaf
->ds
> 12 ||
609 (1 << lbaf
->ds
) > s
->page_size
)
611 error_setg(errp
, "Namespace has unsupported block size (2^%d)",
617 s
->blkshift
= lbaf
->ds
;
619 qemu_vfio_dma_unmap(s
->vfio
, id
);
624 static void nvme_poll_queue(NVMeQueuePair
*q
)
626 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
627 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
629 trace_nvme_poll_queue(q
->s
, q
->index
);
631 * Do an early check for completions. q->lock isn't needed because
632 * nvme_process_completion() only runs in the event loop thread and
633 * cannot race with itself.
635 if ((le16_to_cpu(cqe
->status
) & 0x1) == q
->cq_phase
) {
639 qemu_mutex_lock(&q
->lock
);
640 while (nvme_process_completion(q
)) {
643 qemu_mutex_unlock(&q
->lock
);
646 static void nvme_poll_queues(BDRVNVMeState
*s
)
650 for (i
= 0; i
< s
->queue_count
; i
++) {
651 nvme_poll_queue(s
->queues
[i
]);
655 static void nvme_handle_event(EventNotifier
*n
)
657 BDRVNVMeState
*s
= container_of(n
, BDRVNVMeState
,
658 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
660 trace_nvme_handle_event(s
);
661 event_notifier_test_and_clear(n
);
665 static bool nvme_add_io_queue(BlockDriverState
*bs
, Error
**errp
)
667 BDRVNVMeState
*s
= bs
->opaque
;
668 unsigned n
= s
->queue_count
;
671 unsigned queue_size
= NVME_QUEUE_SIZE
;
673 assert(n
<= UINT16_MAX
);
674 q
= nvme_create_queue_pair(s
, bdrv_get_aio_context(bs
),
675 n
, queue_size
, errp
);
680 .opcode
= NVME_ADM_CMD_CREATE_CQ
,
681 .dptr
.prp1
= cpu_to_le64(q
->cq
.iova
),
682 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
683 .cdw11
= cpu_to_le32(NVME_CQ_IEN
| NVME_CQ_PC
),
685 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
686 error_setg(errp
, "Failed to create CQ io queue [%u]", n
);
690 .opcode
= NVME_ADM_CMD_CREATE_SQ
,
691 .dptr
.prp1
= cpu_to_le64(q
->sq
.iova
),
692 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
693 .cdw11
= cpu_to_le32(NVME_SQ_PC
| (n
<< 16)),
695 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
696 error_setg(errp
, "Failed to create SQ io queue [%u]", n
);
699 s
->queues
= g_renew(NVMeQueuePair
*, s
->queues
, n
+ 1);
704 nvme_free_queue_pair(q
);
708 static bool nvme_poll_cb(void *opaque
)
710 EventNotifier
*e
= opaque
;
711 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
712 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
715 for (i
= 0; i
< s
->queue_count
; i
++) {
716 NVMeQueuePair
*q
= s
->queues
[i
];
717 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
718 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
721 * q->lock isn't needed because nvme_process_completion() only runs in
722 * the event loop thread and cannot race with itself.
724 if ((le16_to_cpu(cqe
->status
) & 0x1) != q
->cq_phase
) {
731 static void nvme_poll_ready(EventNotifier
*e
)
733 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
734 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
739 static int nvme_init(BlockDriverState
*bs
, const char *device
, int namespace,
742 BDRVNVMeState
*s
= bs
->opaque
;
744 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
749 uint64_t deadline
, now
;
750 volatile NvmeBar
*regs
= NULL
;
752 qemu_co_mutex_init(&s
->dma_map_lock
);
753 qemu_co_queue_init(&s
->dma_flush_queue
);
754 s
->device
= g_strdup(device
);
756 s
->aio_context
= bdrv_get_aio_context(bs
);
757 ret
= event_notifier_init(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
], 0);
759 error_setg(errp
, "Failed to init event notifier");
763 s
->vfio
= qemu_vfio_open_pci(device
, errp
);
769 regs
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0, sizeof(NvmeBar
),
770 PROT_READ
| PROT_WRITE
, errp
);
775 /* Perform initialize sequence as described in NVMe spec "7.6.1
776 * Initialization". */
778 cap
= le64_to_cpu(regs
->cap
);
779 trace_nvme_controller_capability_raw(cap
);
780 trace_nvme_controller_capability("Maximum Queue Entries Supported",
781 1 + NVME_CAP_MQES(cap
));
782 trace_nvme_controller_capability("Contiguous Queues Required",
784 trace_nvme_controller_capability("Doorbell Stride",
785 1 << (2 + NVME_CAP_DSTRD(cap
)));
786 trace_nvme_controller_capability("Subsystem Reset Supported",
787 NVME_CAP_NSSRS(cap
));
788 trace_nvme_controller_capability("Memory Page Size Minimum",
789 1 << (12 + NVME_CAP_MPSMIN(cap
)));
790 trace_nvme_controller_capability("Memory Page Size Maximum",
791 1 << (12 + NVME_CAP_MPSMAX(cap
)));
792 if (!NVME_CAP_CSS(cap
)) {
793 error_setg(errp
, "Device doesn't support NVMe command set");
798 s
->page_size
= 1u << (12 + NVME_CAP_MPSMIN(cap
));
799 s
->doorbell_scale
= (4 << NVME_CAP_DSTRD(cap
)) / sizeof(uint32_t);
800 bs
->bl
.opt_mem_alignment
= s
->page_size
;
801 bs
->bl
.request_alignment
= s
->page_size
;
802 timeout_ms
= MIN(500 * NVME_CAP_TO(cap
), 30000);
804 ver
= le32_to_cpu(regs
->vs
);
805 trace_nvme_controller_spec_version(extract32(ver
, 16, 16),
806 extract32(ver
, 8, 8),
807 extract32(ver
, 0, 8));
809 /* Reset device to get a clean state. */
810 regs
->cc
= cpu_to_le32(le32_to_cpu(regs
->cc
) & 0xFE);
811 /* Wait for CSTS.RDY = 0. */
812 deadline
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + timeout_ms
* SCALE_MS
;
813 while (NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
814 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
815 error_setg(errp
, "Timeout while waiting for device to reset (%"
823 s
->bar0_wo_map
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0,
824 sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
,
826 s
->doorbells
= (void *)((uintptr_t)s
->bar0_wo_map
+ sizeof(NvmeBar
));
832 /* Set up admin queue. */
833 s
->queues
= g_new(NVMeQueuePair
*, 1);
834 q
= nvme_create_queue_pair(s
, aio_context
, 0, NVME_QUEUE_SIZE
, errp
);
839 s
->queues
[INDEX_ADMIN
] = q
;
841 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE
- 1) & 0xF000);
842 regs
->aqa
= cpu_to_le32(((NVME_QUEUE_SIZE
- 1) << AQA_ACQS_SHIFT
) |
843 ((NVME_QUEUE_SIZE
- 1) << AQA_ASQS_SHIFT
));
844 regs
->asq
= cpu_to_le64(q
->sq
.iova
);
845 regs
->acq
= cpu_to_le64(q
->cq
.iova
);
847 /* After setting up all control registers we can enable device now. */
848 regs
->cc
= cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES
) << CC_IOCQES_SHIFT
) |
849 (ctz32(NVME_SQ_ENTRY_BYTES
) << CC_IOSQES_SHIFT
) |
851 /* Wait for CSTS.RDY = 1. */
852 now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
853 deadline
= now
+ timeout_ms
* SCALE_MS
;
854 while (!NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
855 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
856 error_setg(errp
, "Timeout while waiting for device to start (%"
864 ret
= qemu_vfio_pci_init_irq(s
->vfio
, s
->irq_notifier
,
865 VFIO_PCI_MSIX_IRQ_INDEX
, errp
);
869 aio_set_event_notifier(bdrv_get_aio_context(bs
),
870 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
871 nvme_handle_event
, nvme_poll_cb
,
874 if (!nvme_identify(bs
, namespace, errp
)) {
879 /* Set up command queues. */
880 if (!nvme_add_io_queue(bs
, errp
)) {
885 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)regs
, 0, sizeof(NvmeBar
));
888 /* Cleaning up is done in nvme_file_open() upon error. */
892 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
894 * nvme://0000:44:00.0/1
896 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
897 * is the PCI address, and the last part is the namespace number starting from
898 * 1 according to the NVMe spec. */
899 static void nvme_parse_filename(const char *filename
, QDict
*options
,
902 int pref
= strlen("nvme://");
904 if (strlen(filename
) > pref
&& !strncmp(filename
, "nvme://", pref
)) {
905 const char *tmp
= filename
+ pref
;
907 const char *namespace;
909 const char *slash
= strchr(tmp
, '/');
911 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, tmp
);
914 device
= g_strndup(tmp
, slash
- tmp
);
915 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, device
);
917 namespace = slash
+ 1;
918 if (*namespace && qemu_strtoul(namespace, NULL
, 10, &ns
)) {
919 error_setg(errp
, "Invalid namespace '%s', positive number expected",
923 qdict_put_str(options
, NVME_BLOCK_OPT_NAMESPACE
,
924 *namespace ? namespace : "1");
928 static int nvme_enable_disable_write_cache(BlockDriverState
*bs
, bool enable
,
932 BDRVNVMeState
*s
= bs
->opaque
;
934 .opcode
= NVME_ADM_CMD_SET_FEATURES
,
935 .nsid
= cpu_to_le32(s
->nsid
),
936 .cdw10
= cpu_to_le32(0x06),
937 .cdw11
= cpu_to_le32(enable
? 0x01 : 0x00),
940 ret
= nvme_admin_cmd_sync(bs
, &cmd
);
942 error_setg(errp
, "Failed to configure NVMe write cache");
947 static void nvme_close(BlockDriverState
*bs
)
949 BDRVNVMeState
*s
= bs
->opaque
;
951 for (unsigned i
= 0; i
< s
->queue_count
; ++i
) {
952 nvme_free_queue_pair(s
->queues
[i
]);
955 aio_set_event_notifier(bdrv_get_aio_context(bs
),
956 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
958 event_notifier_cleanup(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
959 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, s
->bar0_wo_map
,
960 0, sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
);
961 qemu_vfio_close(s
->vfio
);
966 static int nvme_file_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
973 BDRVNVMeState
*s
= bs
->opaque
;
975 bs
->supported_write_flags
= BDRV_REQ_FUA
;
977 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
978 qemu_opts_absorb_qdict(opts
, options
, &error_abort
);
979 device
= qemu_opt_get(opts
, NVME_BLOCK_OPT_DEVICE
);
981 error_setg(errp
, "'" NVME_BLOCK_OPT_DEVICE
"' option is required");
986 namespace = qemu_opt_get_number(opts
, NVME_BLOCK_OPT_NAMESPACE
, 1);
987 ret
= nvme_init(bs
, device
, namespace, errp
);
992 if (flags
& BDRV_O_NOCACHE
) {
993 if (!s
->write_cache_supported
) {
995 "NVMe controller doesn't support write cache configuration");
998 ret
= nvme_enable_disable_write_cache(bs
, !(flags
& BDRV_O_NOCACHE
),
1011 static int64_t coroutine_fn
nvme_co_getlength(BlockDriverState
*bs
)
1013 BDRVNVMeState
*s
= bs
->opaque
;
1014 return s
->nsze
<< s
->blkshift
;
1017 static uint32_t nvme_get_blocksize(BlockDriverState
*bs
)
1019 BDRVNVMeState
*s
= bs
->opaque
;
1020 assert(s
->blkshift
>= BDRV_SECTOR_BITS
&& s
->blkshift
<= 12);
1021 return UINT32_C(1) << s
->blkshift
;
1024 static int nvme_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1026 uint32_t blocksize
= nvme_get_blocksize(bs
);
1027 bsz
->phys
= blocksize
;
1028 bsz
->log
= blocksize
;
1032 /* Called with s->dma_map_lock */
1033 static coroutine_fn
int nvme_cmd_unmap_qiov(BlockDriverState
*bs
,
1037 BDRVNVMeState
*s
= bs
->opaque
;
1039 s
->dma_map_count
-= qiov
->size
;
1040 if (!s
->dma_map_count
&& !qemu_co_queue_empty(&s
->dma_flush_queue
)) {
1041 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1043 qemu_co_queue_restart_all(&s
->dma_flush_queue
);
1049 /* Called with s->dma_map_lock */
1050 static coroutine_fn
int nvme_cmd_map_qiov(BlockDriverState
*bs
, NvmeCmd
*cmd
,
1051 NVMeRequest
*req
, QEMUIOVector
*qiov
)
1053 BDRVNVMeState
*s
= bs
->opaque
;
1054 uint64_t *pagelist
= req
->prp_list_page
;
1057 Error
*local_err
= NULL
, **errp
= NULL
;
1060 assert(QEMU_IS_ALIGNED(qiov
->size
, s
->page_size
));
1061 assert(qiov
->size
/ s
->page_size
<= s
->page_size
/ sizeof(uint64_t));
1062 for (i
= 0; i
< qiov
->niov
; ++i
) {
1065 size_t len
= QEMU_ALIGN_UP(qiov
->iov
[i
].iov_len
,
1066 qemu_real_host_page_size());
1068 r
= qemu_vfio_dma_map(s
->vfio
,
1069 qiov
->iov
[i
].iov_base
,
1070 len
, true, &iova
, errp
);
1073 * In addition to the -ENOMEM error, the VFIO_IOMMU_MAP_DMA
1074 * ioctl returns -ENOSPC to signal the user exhausted the DMA
1075 * mappings available for a container since Linux kernel commit
1076 * 492855939bdb ("vfio/type1: Limit DMA mappings per container",
1077 * April 2019, see CVE-2019-3882).
1079 * This block driver already handles this error path by checking
1080 * for the -ENOMEM error, so we directly replace -ENOSPC by
1081 * -ENOMEM. Beside, -ENOSPC has a specific meaning for blockdev
1082 * coroutines: it triggers BLOCKDEV_ON_ERROR_ENOSPC and
1083 * BLOCK_ERROR_ACTION_STOP which stops the VM, asking the operator
1084 * to add more storage to the blockdev. Not something we can do
1085 * easily with an IOMMU :)
1089 if (r
== -ENOMEM
&& retry
) {
1091 * We exhausted the DMA mappings available for our container:
1092 * recycle the volatile IOVA mappings.
1095 trace_nvme_dma_flush_queue_wait(s
);
1096 if (s
->dma_map_count
) {
1097 trace_nvme_dma_map_flush(s
);
1098 qemu_co_queue_wait(&s
->dma_flush_queue
, &s
->dma_map_lock
);
1100 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1113 for (j
= 0; j
< qiov
->iov
[i
].iov_len
/ s
->page_size
; j
++) {
1114 pagelist
[entries
++] = cpu_to_le64(iova
+ j
* s
->page_size
);
1116 trace_nvme_cmd_map_qiov_iov(s
, i
, qiov
->iov
[i
].iov_base
,
1117 qiov
->iov
[i
].iov_len
/ s
->page_size
);
1120 s
->dma_map_count
+= qiov
->size
;
1122 assert(entries
<= s
->page_size
/ sizeof(uint64_t));
1127 cmd
->dptr
.prp1
= pagelist
[0];
1131 cmd
->dptr
.prp1
= pagelist
[0];
1132 cmd
->dptr
.prp2
= pagelist
[1];
1135 cmd
->dptr
.prp1
= pagelist
[0];
1136 cmd
->dptr
.prp2
= cpu_to_le64(req
->prp_list_iova
+ sizeof(uint64_t));
1139 trace_nvme_cmd_map_qiov(s
, cmd
, req
, qiov
, entries
);
1140 for (i
= 0; i
< entries
; ++i
) {
1141 trace_nvme_cmd_map_qiov_pages(s
, i
, pagelist
[i
]);
1145 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1146 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1147 * because they are already mapped before calling this function; for
1148 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1149 * calling qemu_vfio_dma_reset_temporary when necessary. */
1151 error_reportf_err(local_err
, "Cannot map buffer for DMA: ");
1162 static void nvme_rw_cb_bh(void *opaque
)
1164 NVMeCoData
*data
= opaque
;
1165 qemu_coroutine_enter(data
->co
);
1168 static void nvme_rw_cb(void *opaque
, int ret
)
1170 NVMeCoData
*data
= opaque
;
1173 /* The rw coroutine hasn't yielded, don't try to enter. */
1176 replay_bh_schedule_oneshot_event(data
->ctx
, nvme_rw_cb_bh
, data
);
1179 static coroutine_fn
int nvme_co_prw_aligned(BlockDriverState
*bs
,
1180 uint64_t offset
, uint64_t bytes
,
1186 BDRVNVMeState
*s
= bs
->opaque
;
1187 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1190 uint32_t cdw12
= (((bytes
>> s
->blkshift
) - 1) & 0xFFFF) |
1191 (flags
& BDRV_REQ_FUA
? 1 << 30 : 0);
1193 .opcode
= is_write
? NVME_CMD_WRITE
: NVME_CMD_READ
,
1194 .nsid
= cpu_to_le32(s
->nsid
),
1195 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1196 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1197 .cdw12
= cpu_to_le32(cdw12
),
1200 .ctx
= bdrv_get_aio_context(bs
),
1201 .ret
= -EINPROGRESS
,
1204 trace_nvme_prw_aligned(s
, is_write
, offset
, bytes
, flags
, qiov
->niov
);
1205 assert(s
->queue_count
> 1);
1206 req
= nvme_get_free_req(ioq
);
1209 qemu_co_mutex_lock(&s
->dma_map_lock
);
1210 r
= nvme_cmd_map_qiov(bs
, &cmd
, req
, qiov
);
1211 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1213 nvme_put_free_req_and_wake(ioq
, req
);
1216 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1218 data
.co
= qemu_coroutine_self();
1219 while (data
.ret
== -EINPROGRESS
) {
1220 qemu_coroutine_yield();
1223 qemu_co_mutex_lock(&s
->dma_map_lock
);
1224 r
= nvme_cmd_unmap_qiov(bs
, qiov
);
1225 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1230 trace_nvme_rw_done(s
, is_write
, offset
, bytes
, data
.ret
);
1234 static inline bool nvme_qiov_aligned(BlockDriverState
*bs
,
1235 const QEMUIOVector
*qiov
)
1238 BDRVNVMeState
*s
= bs
->opaque
;
1240 for (i
= 0; i
< qiov
->niov
; ++i
) {
1241 if (!QEMU_PTR_IS_ALIGNED(qiov
->iov
[i
].iov_base
,
1242 qemu_real_host_page_size()) ||
1243 !QEMU_IS_ALIGNED(qiov
->iov
[i
].iov_len
, qemu_real_host_page_size())) {
1244 trace_nvme_qiov_unaligned(qiov
, i
, qiov
->iov
[i
].iov_base
,
1245 qiov
->iov
[i
].iov_len
, s
->page_size
);
1252 static coroutine_fn
int nvme_co_prw(BlockDriverState
*bs
,
1253 uint64_t offset
, uint64_t bytes
,
1254 QEMUIOVector
*qiov
, bool is_write
,
1257 BDRVNVMeState
*s
= bs
->opaque
;
1259 QEMU_AUTO_VFREE
uint8_t *buf
= NULL
;
1260 QEMUIOVector local_qiov
;
1261 size_t len
= QEMU_ALIGN_UP(bytes
, qemu_real_host_page_size());
1262 assert(QEMU_IS_ALIGNED(offset
, s
->page_size
));
1263 assert(QEMU_IS_ALIGNED(bytes
, s
->page_size
));
1264 assert(bytes
<= s
->max_transfer
);
1265 if (nvme_qiov_aligned(bs
, qiov
)) {
1266 s
->stats
.aligned_accesses
++;
1267 return nvme_co_prw_aligned(bs
, offset
, bytes
, qiov
, is_write
, flags
);
1269 s
->stats
.unaligned_accesses
++;
1270 trace_nvme_prw_buffered(s
, offset
, bytes
, qiov
->niov
, is_write
);
1271 buf
= qemu_try_memalign(qemu_real_host_page_size(), len
);
1276 qemu_iovec_init(&local_qiov
, 1);
1278 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
1280 qemu_iovec_add(&local_qiov
, buf
, bytes
);
1281 r
= nvme_co_prw_aligned(bs
, offset
, bytes
, &local_qiov
, is_write
, flags
);
1282 qemu_iovec_destroy(&local_qiov
);
1283 if (!r
&& !is_write
) {
1284 qemu_iovec_from_buf(qiov
, 0, buf
, bytes
);
1289 static coroutine_fn
int nvme_co_preadv(BlockDriverState
*bs
,
1290 int64_t offset
, int64_t bytes
,
1292 BdrvRequestFlags flags
)
1294 return nvme_co_prw(bs
, offset
, bytes
, qiov
, false, flags
);
1297 static coroutine_fn
int nvme_co_pwritev(BlockDriverState
*bs
,
1298 int64_t offset
, int64_t bytes
,
1300 BdrvRequestFlags flags
)
1302 return nvme_co_prw(bs
, offset
, bytes
, qiov
, true, flags
);
1305 static coroutine_fn
int nvme_co_flush(BlockDriverState
*bs
)
1307 BDRVNVMeState
*s
= bs
->opaque
;
1308 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1311 .opcode
= NVME_CMD_FLUSH
,
1312 .nsid
= cpu_to_le32(s
->nsid
),
1315 .ctx
= bdrv_get_aio_context(bs
),
1316 .ret
= -EINPROGRESS
,
1319 assert(s
->queue_count
> 1);
1320 req
= nvme_get_free_req(ioq
);
1322 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1324 data
.co
= qemu_coroutine_self();
1325 if (data
.ret
== -EINPROGRESS
) {
1326 qemu_coroutine_yield();
1333 static coroutine_fn
int nvme_co_pwrite_zeroes(BlockDriverState
*bs
,
1336 BdrvRequestFlags flags
)
1338 BDRVNVMeState
*s
= bs
->opaque
;
1339 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1343 if (!s
->supports_write_zeroes
) {
1351 cdw12
= ((bytes
>> s
->blkshift
) - 1) & 0xFFFF;
1353 * We should not lose information. pwrite_zeroes_alignment and
1354 * max_pwrite_zeroes guarantees it.
1356 assert(((cdw12
+ 1) << s
->blkshift
) == bytes
);
1359 .opcode
= NVME_CMD_WRITE_ZEROES
,
1360 .nsid
= cpu_to_le32(s
->nsid
),
1361 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1362 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1366 .ctx
= bdrv_get_aio_context(bs
),
1367 .ret
= -EINPROGRESS
,
1370 if (flags
& BDRV_REQ_MAY_UNMAP
) {
1374 if (flags
& BDRV_REQ_FUA
) {
1378 cmd
.cdw12
= cpu_to_le32(cdw12
);
1380 trace_nvme_write_zeroes(s
, offset
, bytes
, flags
);
1381 assert(s
->queue_count
> 1);
1382 req
= nvme_get_free_req(ioq
);
1385 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1387 data
.co
= qemu_coroutine_self();
1388 while (data
.ret
== -EINPROGRESS
) {
1389 qemu_coroutine_yield();
1392 trace_nvme_rw_done(s
, true, offset
, bytes
, data
.ret
);
1397 static int coroutine_fn
nvme_co_pdiscard(BlockDriverState
*bs
,
1401 BDRVNVMeState
*s
= bs
->opaque
;
1402 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1404 QEMU_AUTO_VFREE NvmeDsmRange
*buf
= NULL
;
1405 QEMUIOVector local_qiov
;
1409 .opcode
= NVME_CMD_DSM
,
1410 .nsid
= cpu_to_le32(s
->nsid
),
1411 .cdw10
= cpu_to_le32(0), /*number of ranges - 0 based*/
1412 .cdw11
= cpu_to_le32(1 << 2), /*deallocate bit*/
1416 .ctx
= bdrv_get_aio_context(bs
),
1417 .ret
= -EINPROGRESS
,
1420 if (!s
->supports_discard
) {
1424 assert(s
->queue_count
> 1);
1427 * Filling the @buf requires @offset and @bytes to satisfy restrictions
1428 * defined in nvme_refresh_limits().
1430 assert(QEMU_IS_ALIGNED(bytes
, 1UL << s
->blkshift
));
1431 assert(QEMU_IS_ALIGNED(offset
, 1UL << s
->blkshift
));
1432 assert((bytes
>> s
->blkshift
) <= UINT32_MAX
);
1434 buf
= qemu_try_memalign(s
->page_size
, s
->page_size
);
1438 memset(buf
, 0, s
->page_size
);
1439 buf
->nlb
= cpu_to_le32(bytes
>> s
->blkshift
);
1440 buf
->slba
= cpu_to_le64(offset
>> s
->blkshift
);
1443 qemu_iovec_init(&local_qiov
, 1);
1444 qemu_iovec_add(&local_qiov
, buf
, 4096);
1446 req
= nvme_get_free_req(ioq
);
1449 qemu_co_mutex_lock(&s
->dma_map_lock
);
1450 ret
= nvme_cmd_map_qiov(bs
, &cmd
, req
, &local_qiov
);
1451 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1454 nvme_put_free_req_and_wake(ioq
, req
);
1458 trace_nvme_dsm(s
, offset
, bytes
);
1460 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1462 data
.co
= qemu_coroutine_self();
1463 while (data
.ret
== -EINPROGRESS
) {
1464 qemu_coroutine_yield();
1467 qemu_co_mutex_lock(&s
->dma_map_lock
);
1468 ret
= nvme_cmd_unmap_qiov(bs
, &local_qiov
);
1469 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1476 trace_nvme_dsm_done(s
, offset
, bytes
, ret
);
1478 qemu_iovec_destroy(&local_qiov
);
1483 static int coroutine_fn
nvme_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1484 bool exact
, PreallocMode prealloc
,
1485 BdrvRequestFlags flags
, Error
**errp
)
1489 if (prealloc
!= PREALLOC_MODE_OFF
) {
1490 error_setg(errp
, "Unsupported preallocation mode '%s'",
1491 PreallocMode_str(prealloc
));
1495 cur_length
= nvme_co_getlength(bs
);
1496 if (offset
!= cur_length
&& exact
) {
1497 error_setg(errp
, "Cannot resize NVMe devices");
1499 } else if (offset
> cur_length
) {
1500 error_setg(errp
, "Cannot grow NVMe devices");
1507 static int nvme_reopen_prepare(BDRVReopenState
*reopen_state
,
1508 BlockReopenQueue
*queue
, Error
**errp
)
1513 static void nvme_refresh_filename(BlockDriverState
*bs
)
1515 BDRVNVMeState
*s
= bs
->opaque
;
1517 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
), "nvme://%s/%i",
1518 s
->device
, s
->nsid
);
1521 static void nvme_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1523 BDRVNVMeState
*s
= bs
->opaque
;
1525 bs
->bl
.opt_mem_alignment
= s
->page_size
;
1526 bs
->bl
.request_alignment
= s
->page_size
;
1527 bs
->bl
.max_transfer
= s
->max_transfer
;
1530 * Look at nvme_co_pwrite_zeroes: after shift and decrement we should get
1533 bs
->bl
.max_pwrite_zeroes
= 1ULL << (s
->blkshift
+ 16);
1534 bs
->bl
.pwrite_zeroes_alignment
= MAX(bs
->bl
.request_alignment
,
1535 1UL << s
->blkshift
);
1537 bs
->bl
.max_pdiscard
= (uint64_t)UINT32_MAX
<< s
->blkshift
;
1538 bs
->bl
.pdiscard_alignment
= MAX(bs
->bl
.request_alignment
,
1539 1UL << s
->blkshift
);
1542 static void nvme_detach_aio_context(BlockDriverState
*bs
)
1544 BDRVNVMeState
*s
= bs
->opaque
;
1546 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1547 NVMeQueuePair
*q
= s
->queues
[i
];
1549 qemu_bh_delete(q
->completion_bh
);
1550 q
->completion_bh
= NULL
;
1553 aio_set_event_notifier(bdrv_get_aio_context(bs
),
1554 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1558 static void nvme_attach_aio_context(BlockDriverState
*bs
,
1559 AioContext
*new_context
)
1561 BDRVNVMeState
*s
= bs
->opaque
;
1563 s
->aio_context
= new_context
;
1564 aio_set_event_notifier(new_context
, &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1565 nvme_handle_event
, nvme_poll_cb
,
1568 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1569 NVMeQueuePair
*q
= s
->queues
[i
];
1572 aio_bh_new(new_context
, nvme_process_completion_bh
, q
);
1576 static bool nvme_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
1580 BDRVNVMeState
*s
= bs
->opaque
;
1583 * FIXME: we may run out of IOVA addresses after repeated
1584 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1585 * doesn't reclaim addresses for fixed mappings.
1587 ret
= qemu_vfio_dma_map(s
->vfio
, host
, size
, false, NULL
, errp
);
1591 static void nvme_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
1593 BDRVNVMeState
*s
= bs
->opaque
;
1595 qemu_vfio_dma_unmap(s
->vfio
, host
);
1598 static BlockStatsSpecific
*nvme_get_specific_stats(BlockDriverState
*bs
)
1600 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
1601 BDRVNVMeState
*s
= bs
->opaque
;
1603 stats
->driver
= BLOCKDEV_DRIVER_NVME
;
1604 stats
->u
.nvme
= (BlockStatsSpecificNvme
) {
1605 .completion_errors
= s
->stats
.completion_errors
,
1606 .aligned_accesses
= s
->stats
.aligned_accesses
,
1607 .unaligned_accesses
= s
->stats
.unaligned_accesses
,
1613 static const char *const nvme_strong_runtime_opts
[] = {
1614 NVME_BLOCK_OPT_DEVICE
,
1615 NVME_BLOCK_OPT_NAMESPACE
,
1620 static BlockDriver bdrv_nvme
= {
1621 .format_name
= "nvme",
1622 .protocol_name
= "nvme",
1623 .instance_size
= sizeof(BDRVNVMeState
),
1625 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
1626 .create_opts
= &bdrv_create_opts_simple
,
1628 .bdrv_parse_filename
= nvme_parse_filename
,
1629 .bdrv_file_open
= nvme_file_open
,
1630 .bdrv_close
= nvme_close
,
1631 .bdrv_co_getlength
= nvme_co_getlength
,
1632 .bdrv_probe_blocksizes
= nvme_probe_blocksizes
,
1633 .bdrv_co_truncate
= nvme_co_truncate
,
1635 .bdrv_co_preadv
= nvme_co_preadv
,
1636 .bdrv_co_pwritev
= nvme_co_pwritev
,
1638 .bdrv_co_pwrite_zeroes
= nvme_co_pwrite_zeroes
,
1639 .bdrv_co_pdiscard
= nvme_co_pdiscard
,
1641 .bdrv_co_flush_to_disk
= nvme_co_flush
,
1642 .bdrv_reopen_prepare
= nvme_reopen_prepare
,
1644 .bdrv_refresh_filename
= nvme_refresh_filename
,
1645 .bdrv_refresh_limits
= nvme_refresh_limits
,
1646 .strong_runtime_opts
= nvme_strong_runtime_opts
,
1647 .bdrv_get_specific_stats
= nvme_get_specific_stats
,
1649 .bdrv_detach_aio_context
= nvme_detach_aio_context
,
1650 .bdrv_attach_aio_context
= nvme_attach_aio_context
,
1652 .bdrv_register_buf
= nvme_register_buf
,
1653 .bdrv_unregister_buf
= nvme_unregister_buf
,
1656 static void bdrv_nvme_init(void)
1658 bdrv_register(&bdrv_nvme
);
1661 block_init(bdrv_nvme_init
);