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
)
175 bytes
= ROUND_UP(nentries
* entry_bytes
, qemu_real_host_page_size());
176 q
->head
= q
->tail
= 0;
177 q
->queue
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
179 error_setg(errp
, "Cannot allocate queue");
182 memset(q
->queue
, 0, bytes
);
183 r
= qemu_vfio_dma_map(s
->vfio
, q
->queue
, bytes
, false, &q
->iova
, errp
);
185 error_prepend(errp
, "Cannot map queue: ");
190 static void nvme_free_queue(NVMeQueue
*q
)
192 qemu_vfree(q
->queue
);
195 static void nvme_free_queue_pair(NVMeQueuePair
*q
)
197 trace_nvme_free_queue_pair(q
->index
, q
, &q
->cq
, &q
->sq
);
198 if (q
->completion_bh
) {
199 qemu_bh_delete(q
->completion_bh
);
201 nvme_free_queue(&q
->sq
);
202 nvme_free_queue(&q
->cq
);
203 qemu_vfree(q
->prp_list_pages
);
204 qemu_mutex_destroy(&q
->lock
);
208 static void nvme_free_req_queue_cb(void *opaque
)
210 NVMeQueuePair
*q
= opaque
;
212 qemu_mutex_lock(&q
->lock
);
213 while (q
->free_req_head
!= -1 &&
214 qemu_co_enter_next(&q
->free_req_queue
, &q
->lock
)) {
215 /* Retry waiting requests */
217 qemu_mutex_unlock(&q
->lock
);
220 static NVMeQueuePair
*nvme_create_queue_pair(BDRVNVMeState
*s
,
221 AioContext
*aio_context
,
222 unsigned idx
, size_t size
,
228 uint64_t prp_list_iova
;
231 q
= g_try_new0(NVMeQueuePair
, 1);
233 error_setg(errp
, "Cannot allocate queue pair");
236 trace_nvme_create_queue_pair(idx
, q
, size
, aio_context
,
237 event_notifier_get_fd(s
->irq_notifier
));
238 bytes
= QEMU_ALIGN_UP(s
->page_size
* NVME_NUM_REQS
,
239 qemu_real_host_page_size());
240 q
->prp_list_pages
= qemu_try_memalign(qemu_real_host_page_size(), bytes
);
241 if (!q
->prp_list_pages
) {
242 error_setg(errp
, "Cannot allocate PRP page list");
245 memset(q
->prp_list_pages
, 0, bytes
);
246 qemu_mutex_init(&q
->lock
);
249 qemu_co_queue_init(&q
->free_req_queue
);
250 q
->completion_bh
= aio_bh_new(aio_context
, nvme_process_completion_bh
, q
);
251 r
= qemu_vfio_dma_map(s
->vfio
, q
->prp_list_pages
, bytes
,
252 false, &prp_list_iova
, errp
);
254 error_prepend(errp
, "Cannot map buffer for DMA: ");
257 q
->free_req_head
= -1;
258 for (i
= 0; i
< NVME_NUM_REQS
; i
++) {
259 NVMeRequest
*req
= &q
->reqs
[i
];
261 req
->free_req_next
= q
->free_req_head
;
262 q
->free_req_head
= i
;
263 req
->prp_list_page
= q
->prp_list_pages
+ i
* s
->page_size
;
264 req
->prp_list_iova
= prp_list_iova
+ i
* s
->page_size
;
267 if (!nvme_init_queue(s
, &q
->sq
, size
, NVME_SQ_ENTRY_BYTES
, errp
)) {
270 q
->sq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].sq_tail
;
272 if (!nvme_init_queue(s
, &q
->cq
, size
, NVME_CQ_ENTRY_BYTES
, errp
)) {
275 q
->cq
.doorbell
= &s
->doorbells
[idx
* s
->doorbell_scale
].cq_head
;
279 nvme_free_queue_pair(q
);
284 static void nvme_kick(NVMeQueuePair
*q
)
286 BDRVNVMeState
*s
= q
->s
;
291 trace_nvme_kick(s
, q
->index
);
292 assert(!(q
->sq
.tail
& 0xFF00));
293 /* Fence the write to submission queue entry before notifying the device. */
295 *q
->sq
.doorbell
= cpu_to_le32(q
->sq
.tail
);
296 q
->inflight
+= q
->need_kick
;
300 static NVMeRequest
*nvme_get_free_req_nofail_locked(NVMeQueuePair
*q
)
304 req
= &q
->reqs
[q
->free_req_head
];
305 q
->free_req_head
= req
->free_req_next
;
306 req
->free_req_next
= -1;
310 /* Return a free request element if any, otherwise return NULL. */
311 static NVMeRequest
*nvme_get_free_req_nowait(NVMeQueuePair
*q
)
313 QEMU_LOCK_GUARD(&q
->lock
);
314 if (q
->free_req_head
== -1) {
317 return nvme_get_free_req_nofail_locked(q
);
321 * Wait for a free request to become available if necessary, then
324 static coroutine_fn NVMeRequest
*nvme_get_free_req(NVMeQueuePair
*q
)
326 QEMU_LOCK_GUARD(&q
->lock
);
328 while (q
->free_req_head
== -1) {
329 trace_nvme_free_req_queue_wait(q
->s
, q
->index
);
330 qemu_co_queue_wait(&q
->free_req_queue
, &q
->lock
);
333 return nvme_get_free_req_nofail_locked(q
);
337 static void nvme_put_free_req_locked(NVMeQueuePair
*q
, NVMeRequest
*req
)
339 req
->free_req_next
= q
->free_req_head
;
340 q
->free_req_head
= req
- q
->reqs
;
344 static void nvme_wake_free_req_locked(NVMeQueuePair
*q
)
346 if (!qemu_co_queue_empty(&q
->free_req_queue
)) {
347 replay_bh_schedule_oneshot_event(q
->s
->aio_context
,
348 nvme_free_req_queue_cb
, q
);
352 /* Insert a request in the freelist and wake waiters */
353 static void nvme_put_free_req_and_wake(NVMeQueuePair
*q
, NVMeRequest
*req
)
355 qemu_mutex_lock(&q
->lock
);
356 nvme_put_free_req_locked(q
, req
);
357 nvme_wake_free_req_locked(q
);
358 qemu_mutex_unlock(&q
->lock
);
361 static inline int nvme_translate_error(const NvmeCqe
*c
)
363 uint16_t status
= (le16_to_cpu(c
->status
) >> 1) & 0xFF;
365 trace_nvme_error(le32_to_cpu(c
->result
),
366 le16_to_cpu(c
->sq_head
),
367 le16_to_cpu(c
->sq_id
),
369 le16_to_cpu(status
));
384 static bool nvme_process_completion(NVMeQueuePair
*q
)
386 BDRVNVMeState
*s
= q
->s
;
387 bool progress
= false;
392 trace_nvme_process_completion(s
, q
->index
, q
->inflight
);
395 * Support re-entrancy when a request cb() function invokes aio_poll().
396 * Pending completions must be visible to aio_poll() so that a cb()
397 * function can wait for the completion of another request.
399 * The aio_poll() loop will execute our BH and we'll resume completion
402 qemu_bh_schedule(q
->completion_bh
);
404 assert(q
->inflight
>= 0);
405 while (q
->inflight
) {
409 c
= (NvmeCqe
*)&q
->cq
.queue
[q
->cq
.head
* NVME_CQ_ENTRY_BYTES
];
410 if ((le16_to_cpu(c
->status
) & 0x1) == q
->cq_phase
) {
413 ret
= nvme_translate_error(c
);
415 s
->stats
.completion_errors
++;
417 q
->cq
.head
= (q
->cq
.head
+ 1) % NVME_QUEUE_SIZE
;
419 q
->cq_phase
= !q
->cq_phase
;
421 cid
= le16_to_cpu(c
->cid
);
422 if (cid
== 0 || cid
> NVME_NUM_REQS
) {
423 warn_report("NVMe: Unexpected CID in completion queue: %" PRIu32
424 ", should be within: 1..%u inclusively", cid
,
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_deferred_fn(void *opaque
)
485 NVMeQueuePair
*q
= opaque
;
487 QEMU_LOCK_GUARD(&q
->lock
);
489 nvme_process_completion(q
);
492 static void nvme_submit_command(NVMeQueuePair
*q
, NVMeRequest
*req
,
493 NvmeCmd
*cmd
, BlockCompletionFunc cb
,
498 req
->opaque
= opaque
;
499 cmd
->cid
= cpu_to_le16(req
->cid
);
501 trace_nvme_submit_command(q
->s
, q
->index
, req
->cid
);
502 nvme_trace_command(cmd
);
503 qemu_mutex_lock(&q
->lock
);
504 memcpy((uint8_t *)q
->sq
.queue
+
505 q
->sq
.tail
* NVME_SQ_ENTRY_BYTES
, cmd
, sizeof(*cmd
));
506 q
->sq
.tail
= (q
->sq
.tail
+ 1) % NVME_QUEUE_SIZE
;
508 qemu_mutex_unlock(&q
->lock
);
510 defer_call(nvme_deferred_fn
, q
);
513 static void nvme_admin_cmd_sync_cb(void *opaque
, int ret
)
520 static int nvme_admin_cmd_sync(BlockDriverState
*bs
, NvmeCmd
*cmd
)
522 BDRVNVMeState
*s
= bs
->opaque
;
523 NVMeQueuePair
*q
= s
->queues
[INDEX_ADMIN
];
524 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
526 int ret
= -EINPROGRESS
;
527 req
= nvme_get_free_req_nowait(q
);
531 nvme_submit_command(q
, req
, cmd
, nvme_admin_cmd_sync_cb
, &ret
);
533 AIO_WAIT_WHILE(aio_context
, ret
== -EINPROGRESS
);
537 /* Returns true on success, false on failure. */
538 static bool nvme_identify(BlockDriverState
*bs
, int namespace, Error
**errp
)
541 BDRVNVMeState
*s
= bs
->opaque
;
543 QEMU_AUTO_VFREE
union {
552 .opcode
= NVME_ADM_CMD_IDENTIFY
,
553 .cdw10
= cpu_to_le32(0x1),
555 size_t id_size
= QEMU_ALIGN_UP(sizeof(*id
), qemu_real_host_page_size());
557 id
= qemu_try_memalign(qemu_real_host_page_size(), id_size
);
559 error_setg(errp
, "Cannot allocate buffer for identify response");
562 r
= qemu_vfio_dma_map(s
->vfio
, id
, id_size
, true, &iova
, errp
);
564 error_prepend(errp
, "Cannot map buffer for DMA: ");
568 memset(id
, 0, id_size
);
569 cmd
.dptr
.prp1
= cpu_to_le64(iova
);
570 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
571 error_setg(errp
, "Failed to identify controller");
575 if (le32_to_cpu(id
->ctrl
.nn
) < namespace) {
576 error_setg(errp
, "Invalid namespace");
579 s
->write_cache_supported
= le32_to_cpu(id
->ctrl
.vwc
) & 0x1;
580 s
->max_transfer
= (id
->ctrl
.mdts
? 1 << id
->ctrl
.mdts
: 0) * s
->page_size
;
581 /* For now the page list buffer per command is one page, to hold at most
582 * s->page_size / sizeof(uint64_t) entries. */
583 s
->max_transfer
= MIN_NON_ZERO(s
->max_transfer
,
584 s
->page_size
/ sizeof(uint64_t) * s
->page_size
);
586 oncs
= le16_to_cpu(id
->ctrl
.oncs
);
587 s
->supports_write_zeroes
= !!(oncs
& NVME_ONCS_WRITE_ZEROES
);
588 s
->supports_discard
= !!(oncs
& NVME_ONCS_DSM
);
590 memset(id
, 0, id_size
);
592 cmd
.nsid
= cpu_to_le32(namespace);
593 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
594 error_setg(errp
, "Failed to identify namespace");
598 s
->nsze
= le64_to_cpu(id
->ns
.nsze
);
599 lbaf
= &id
->ns
.lbaf
[NVME_ID_NS_FLBAS_INDEX(id
->ns
.flbas
)];
601 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id
->ns
.dlfeat
) &&
602 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id
->ns
.dlfeat
) ==
603 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES
) {
604 bs
->supported_write_flags
|= BDRV_REQ_MAY_UNMAP
;
608 error_setg(errp
, "Namespaces with metadata are not yet supported");
612 if (lbaf
->ds
< BDRV_SECTOR_BITS
|| lbaf
->ds
> 12 ||
613 (1 << lbaf
->ds
) > s
->page_size
)
615 error_setg(errp
, "Namespace has unsupported block size (2^%d)",
621 s
->blkshift
= lbaf
->ds
;
623 qemu_vfio_dma_unmap(s
->vfio
, id
);
628 static void nvme_poll_queue(NVMeQueuePair
*q
)
630 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
631 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
633 trace_nvme_poll_queue(q
->s
, q
->index
);
635 * Do an early check for completions. q->lock isn't needed because
636 * nvme_process_completion() only runs in the event loop thread and
637 * cannot race with itself.
639 if ((le16_to_cpu(cqe
->status
) & 0x1) == q
->cq_phase
) {
643 qemu_mutex_lock(&q
->lock
);
644 while (nvme_process_completion(q
)) {
647 qemu_mutex_unlock(&q
->lock
);
650 static void nvme_poll_queues(BDRVNVMeState
*s
)
654 for (i
= 0; i
< s
->queue_count
; i
++) {
655 nvme_poll_queue(s
->queues
[i
]);
659 static void nvme_handle_event(EventNotifier
*n
)
661 BDRVNVMeState
*s
= container_of(n
, BDRVNVMeState
,
662 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
664 trace_nvme_handle_event(s
);
665 event_notifier_test_and_clear(n
);
669 static bool nvme_add_io_queue(BlockDriverState
*bs
, Error
**errp
)
671 BDRVNVMeState
*s
= bs
->opaque
;
672 unsigned n
= s
->queue_count
;
675 unsigned queue_size
= NVME_QUEUE_SIZE
;
677 assert(n
<= UINT16_MAX
);
678 q
= nvme_create_queue_pair(s
, bdrv_get_aio_context(bs
),
679 n
, queue_size
, errp
);
684 .opcode
= NVME_ADM_CMD_CREATE_CQ
,
685 .dptr
.prp1
= cpu_to_le64(q
->cq
.iova
),
686 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
687 .cdw11
= cpu_to_le32(NVME_CQ_IEN
| NVME_CQ_PC
),
689 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
690 error_setg(errp
, "Failed to create CQ io queue [%u]", n
);
694 .opcode
= NVME_ADM_CMD_CREATE_SQ
,
695 .dptr
.prp1
= cpu_to_le64(q
->sq
.iova
),
696 .cdw10
= cpu_to_le32(((queue_size
- 1) << 16) | n
),
697 .cdw11
= cpu_to_le32(NVME_SQ_PC
| (n
<< 16)),
699 if (nvme_admin_cmd_sync(bs
, &cmd
)) {
700 error_setg(errp
, "Failed to create SQ io queue [%u]", n
);
703 s
->queues
= g_renew(NVMeQueuePair
*, s
->queues
, n
+ 1);
708 nvme_free_queue_pair(q
);
712 static bool nvme_poll_cb(void *opaque
)
714 EventNotifier
*e
= opaque
;
715 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
716 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
719 for (i
= 0; i
< s
->queue_count
; i
++) {
720 NVMeQueuePair
*q
= s
->queues
[i
];
721 const size_t cqe_offset
= q
->cq
.head
* NVME_CQ_ENTRY_BYTES
;
722 NvmeCqe
*cqe
= (NvmeCqe
*)&q
->cq
.queue
[cqe_offset
];
725 * q->lock isn't needed because nvme_process_completion() only runs in
726 * the event loop thread and cannot race with itself.
728 if ((le16_to_cpu(cqe
->status
) & 0x1) != q
->cq_phase
) {
735 static void nvme_poll_ready(EventNotifier
*e
)
737 BDRVNVMeState
*s
= container_of(e
, BDRVNVMeState
,
738 irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
743 static int nvme_init(BlockDriverState
*bs
, const char *device
, int namespace,
746 BDRVNVMeState
*s
= bs
->opaque
;
748 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
753 uint64_t deadline
, now
;
754 volatile NvmeBar
*regs
= NULL
;
756 qemu_co_mutex_init(&s
->dma_map_lock
);
757 qemu_co_queue_init(&s
->dma_flush_queue
);
758 s
->device
= g_strdup(device
);
760 s
->aio_context
= bdrv_get_aio_context(bs
);
761 ret
= event_notifier_init(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
], 0);
763 error_setg(errp
, "Failed to init event notifier");
767 s
->vfio
= qemu_vfio_open_pci(device
, errp
);
773 regs
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0, sizeof(NvmeBar
),
774 PROT_READ
| PROT_WRITE
, errp
);
779 /* Perform initialize sequence as described in NVMe spec "7.6.1
780 * Initialization". */
782 cap
= le64_to_cpu(regs
->cap
);
783 trace_nvme_controller_capability_raw(cap
);
784 trace_nvme_controller_capability("Maximum Queue Entries Supported",
785 1 + NVME_CAP_MQES(cap
));
786 trace_nvme_controller_capability("Contiguous Queues Required",
788 trace_nvme_controller_capability("Doorbell Stride",
789 1 << (2 + NVME_CAP_DSTRD(cap
)));
790 trace_nvme_controller_capability("Subsystem Reset Supported",
791 NVME_CAP_NSSRS(cap
));
792 trace_nvme_controller_capability("Memory Page Size Minimum",
793 1 << (12 + NVME_CAP_MPSMIN(cap
)));
794 trace_nvme_controller_capability("Memory Page Size Maximum",
795 1 << (12 + NVME_CAP_MPSMAX(cap
)));
796 if (!NVME_CAP_CSS(cap
)) {
797 error_setg(errp
, "Device doesn't support NVMe command set");
802 s
->page_size
= 1u << (12 + NVME_CAP_MPSMIN(cap
));
803 s
->doorbell_scale
= (4 << NVME_CAP_DSTRD(cap
)) / sizeof(uint32_t);
804 bs
->bl
.opt_mem_alignment
= s
->page_size
;
805 bs
->bl
.request_alignment
= s
->page_size
;
806 timeout_ms
= MIN(500 * NVME_CAP_TO(cap
), 30000);
808 ver
= le32_to_cpu(regs
->vs
);
809 trace_nvme_controller_spec_version(extract32(ver
, 16, 16),
810 extract32(ver
, 8, 8),
811 extract32(ver
, 0, 8));
813 /* Reset device to get a clean state. */
814 regs
->cc
= cpu_to_le32(le32_to_cpu(regs
->cc
) & 0xFE);
815 /* Wait for CSTS.RDY = 0. */
816 deadline
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) + timeout_ms
* SCALE_MS
;
817 while (NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
818 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
819 error_setg(errp
, "Timeout while waiting for device to reset (%"
827 s
->bar0_wo_map
= qemu_vfio_pci_map_bar(s
->vfio
, 0, 0,
828 sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
,
830 s
->doorbells
= (void *)((uintptr_t)s
->bar0_wo_map
+ sizeof(NvmeBar
));
836 /* Set up admin queue. */
837 s
->queues
= g_new(NVMeQueuePair
*, 1);
838 q
= nvme_create_queue_pair(s
, aio_context
, 0, NVME_QUEUE_SIZE
, errp
);
843 s
->queues
[INDEX_ADMIN
] = q
;
845 QEMU_BUILD_BUG_ON((NVME_QUEUE_SIZE
- 1) & 0xF000);
846 regs
->aqa
= cpu_to_le32(((NVME_QUEUE_SIZE
- 1) << AQA_ACQS_SHIFT
) |
847 ((NVME_QUEUE_SIZE
- 1) << AQA_ASQS_SHIFT
));
848 regs
->asq
= cpu_to_le64(q
->sq
.iova
);
849 regs
->acq
= cpu_to_le64(q
->cq
.iova
);
851 /* After setting up all control registers we can enable device now. */
852 regs
->cc
= cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES
) << CC_IOCQES_SHIFT
) |
853 (ctz32(NVME_SQ_ENTRY_BYTES
) << CC_IOSQES_SHIFT
) |
855 /* Wait for CSTS.RDY = 1. */
856 now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
857 deadline
= now
+ timeout_ms
* SCALE_MS
;
858 while (!NVME_CSTS_RDY(le32_to_cpu(regs
->csts
))) {
859 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) > deadline
) {
860 error_setg(errp
, "Timeout while waiting for device to start (%"
868 ret
= qemu_vfio_pci_init_irq(s
->vfio
, s
->irq_notifier
,
869 VFIO_PCI_MSIX_IRQ_INDEX
, errp
);
873 aio_set_event_notifier(bdrv_get_aio_context(bs
),
874 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
875 nvme_handle_event
, nvme_poll_cb
,
878 if (!nvme_identify(bs
, namespace, errp
)) {
883 /* Set up command queues. */
884 if (!nvme_add_io_queue(bs
, errp
)) {
889 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, (void *)regs
, 0, sizeof(NvmeBar
));
892 /* Cleaning up is done in nvme_open() upon error. */
896 /* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
898 * nvme://0000:44:00.0/1
900 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
901 * is the PCI address, and the last part is the namespace number starting from
902 * 1 according to the NVMe spec. */
903 static void nvme_parse_filename(const char *filename
, QDict
*options
,
906 int pref
= strlen("nvme://");
908 if (strlen(filename
) > pref
&& !strncmp(filename
, "nvme://", pref
)) {
909 const char *tmp
= filename
+ pref
;
911 const char *namespace;
913 const char *slash
= strchr(tmp
, '/');
915 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, tmp
);
918 device
= g_strndup(tmp
, slash
- tmp
);
919 qdict_put_str(options
, NVME_BLOCK_OPT_DEVICE
, device
);
921 namespace = slash
+ 1;
922 if (*namespace && qemu_strtoul(namespace, NULL
, 10, &ns
)) {
923 error_setg(errp
, "Invalid namespace '%s', positive number expected",
927 qdict_put_str(options
, NVME_BLOCK_OPT_NAMESPACE
,
928 *namespace ? namespace : "1");
932 static int nvme_enable_disable_write_cache(BlockDriverState
*bs
, bool enable
,
936 BDRVNVMeState
*s
= bs
->opaque
;
938 .opcode
= NVME_ADM_CMD_SET_FEATURES
,
939 .nsid
= cpu_to_le32(s
->nsid
),
940 .cdw10
= cpu_to_le32(0x06),
941 .cdw11
= cpu_to_le32(enable
? 0x01 : 0x00),
944 ret
= nvme_admin_cmd_sync(bs
, &cmd
);
946 error_setg(errp
, "Failed to configure NVMe write cache");
951 static void nvme_close(BlockDriverState
*bs
)
953 BDRVNVMeState
*s
= bs
->opaque
;
955 for (unsigned i
= 0; i
< s
->queue_count
; ++i
) {
956 nvme_free_queue_pair(s
->queues
[i
]);
959 aio_set_event_notifier(bdrv_get_aio_context(bs
),
960 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
962 event_notifier_cleanup(&s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
]);
963 qemu_vfio_pci_unmap_bar(s
->vfio
, 0, s
->bar0_wo_map
,
964 0, sizeof(NvmeBar
) + NVME_DOORBELL_SIZE
);
965 qemu_vfio_close(s
->vfio
);
970 static int nvme_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
977 BDRVNVMeState
*s
= bs
->opaque
;
979 bs
->supported_write_flags
= BDRV_REQ_FUA
;
981 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
982 qemu_opts_absorb_qdict(opts
, options
, &error_abort
);
983 device
= qemu_opt_get(opts
, NVME_BLOCK_OPT_DEVICE
);
985 error_setg(errp
, "'" NVME_BLOCK_OPT_DEVICE
"' option is required");
990 namespace = qemu_opt_get_number(opts
, NVME_BLOCK_OPT_NAMESPACE
, 1);
991 ret
= nvme_init(bs
, device
, namespace, errp
);
996 if (flags
& BDRV_O_NOCACHE
) {
997 if (!s
->write_cache_supported
) {
999 "NVMe controller doesn't support write cache configuration");
1002 ret
= nvme_enable_disable_write_cache(bs
, !(flags
& BDRV_O_NOCACHE
),
1015 static int64_t coroutine_fn
nvme_co_getlength(BlockDriverState
*bs
)
1017 BDRVNVMeState
*s
= bs
->opaque
;
1018 return s
->nsze
<< s
->blkshift
;
1021 static uint32_t nvme_get_blocksize(BlockDriverState
*bs
)
1023 BDRVNVMeState
*s
= bs
->opaque
;
1024 assert(s
->blkshift
>= BDRV_SECTOR_BITS
&& s
->blkshift
<= 12);
1025 return UINT32_C(1) << s
->blkshift
;
1028 static int nvme_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1030 uint32_t blocksize
= nvme_get_blocksize(bs
);
1031 bsz
->phys
= blocksize
;
1032 bsz
->log
= blocksize
;
1036 /* Called with s->dma_map_lock */
1037 static coroutine_fn
int nvme_cmd_unmap_qiov(BlockDriverState
*bs
,
1041 BDRVNVMeState
*s
= bs
->opaque
;
1043 s
->dma_map_count
-= qiov
->size
;
1044 if (!s
->dma_map_count
&& !qemu_co_queue_empty(&s
->dma_flush_queue
)) {
1045 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1047 qemu_co_queue_restart_all(&s
->dma_flush_queue
);
1053 /* Called with s->dma_map_lock */
1054 static coroutine_fn
int nvme_cmd_map_qiov(BlockDriverState
*bs
, NvmeCmd
*cmd
,
1055 NVMeRequest
*req
, QEMUIOVector
*qiov
)
1057 BDRVNVMeState
*s
= bs
->opaque
;
1058 uint64_t *pagelist
= req
->prp_list_page
;
1061 Error
*local_err
= NULL
, **errp
= NULL
;
1064 assert(QEMU_IS_ALIGNED(qiov
->size
, s
->page_size
));
1065 assert(qiov
->size
/ s
->page_size
<= s
->page_size
/ sizeof(uint64_t));
1066 for (i
= 0; i
< qiov
->niov
; ++i
) {
1069 size_t len
= QEMU_ALIGN_UP(qiov
->iov
[i
].iov_len
,
1070 qemu_real_host_page_size());
1072 r
= qemu_vfio_dma_map(s
->vfio
,
1073 qiov
->iov
[i
].iov_base
,
1074 len
, true, &iova
, errp
);
1077 * In addition to the -ENOMEM error, the VFIO_IOMMU_MAP_DMA
1078 * ioctl returns -ENOSPC to signal the user exhausted the DMA
1079 * mappings available for a container since Linux kernel commit
1080 * 492855939bdb ("vfio/type1: Limit DMA mappings per container",
1081 * April 2019, see CVE-2019-3882).
1083 * This block driver already handles this error path by checking
1084 * for the -ENOMEM error, so we directly replace -ENOSPC by
1085 * -ENOMEM. Beside, -ENOSPC has a specific meaning for blockdev
1086 * coroutines: it triggers BLOCKDEV_ON_ERROR_ENOSPC and
1087 * BLOCK_ERROR_ACTION_STOP which stops the VM, asking the operator
1088 * to add more storage to the blockdev. Not something we can do
1089 * easily with an IOMMU :)
1093 if (r
== -ENOMEM
&& retry
) {
1095 * We exhausted the DMA mappings available for our container:
1096 * recycle the volatile IOVA mappings.
1099 trace_nvme_dma_flush_queue_wait(s
);
1100 if (s
->dma_map_count
) {
1101 trace_nvme_dma_map_flush(s
);
1102 qemu_co_queue_wait(&s
->dma_flush_queue
, &s
->dma_map_lock
);
1104 r
= qemu_vfio_dma_reset_temporary(s
->vfio
);
1117 for (j
= 0; j
< qiov
->iov
[i
].iov_len
/ s
->page_size
; j
++) {
1118 pagelist
[entries
++] = cpu_to_le64(iova
+ j
* s
->page_size
);
1120 trace_nvme_cmd_map_qiov_iov(s
, i
, qiov
->iov
[i
].iov_base
,
1121 qiov
->iov
[i
].iov_len
/ s
->page_size
);
1124 s
->dma_map_count
+= qiov
->size
;
1126 assert(entries
<= s
->page_size
/ sizeof(uint64_t));
1131 cmd
->dptr
.prp1
= pagelist
[0];
1135 cmd
->dptr
.prp1
= pagelist
[0];
1136 cmd
->dptr
.prp2
= pagelist
[1];
1139 cmd
->dptr
.prp1
= pagelist
[0];
1140 cmd
->dptr
.prp2
= cpu_to_le64(req
->prp_list_iova
+ sizeof(uint64_t));
1143 trace_nvme_cmd_map_qiov(s
, cmd
, req
, qiov
, entries
);
1144 for (i
= 0; i
< entries
; ++i
) {
1145 trace_nvme_cmd_map_qiov_pages(s
, i
, pagelist
[i
]);
1149 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1150 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1151 * because they are already mapped before calling this function; for
1152 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1153 * calling qemu_vfio_dma_reset_temporary when necessary. */
1155 error_reportf_err(local_err
, "Cannot map buffer for DMA: ");
1166 static void nvme_rw_cb_bh(void *opaque
)
1168 NVMeCoData
*data
= opaque
;
1169 qemu_coroutine_enter(data
->co
);
1172 static void nvme_rw_cb(void *opaque
, int ret
)
1174 NVMeCoData
*data
= opaque
;
1177 /* The rw coroutine hasn't yielded, don't try to enter. */
1180 replay_bh_schedule_oneshot_event(data
->ctx
, nvme_rw_cb_bh
, data
);
1183 static coroutine_fn
int nvme_co_prw_aligned(BlockDriverState
*bs
,
1184 uint64_t offset
, uint64_t bytes
,
1190 BDRVNVMeState
*s
= bs
->opaque
;
1191 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1194 uint32_t cdw12
= (((bytes
>> s
->blkshift
) - 1) & 0xFFFF) |
1195 (flags
& BDRV_REQ_FUA
? 1 << 30 : 0);
1197 .opcode
= is_write
? NVME_CMD_WRITE
: NVME_CMD_READ
,
1198 .nsid
= cpu_to_le32(s
->nsid
),
1199 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1200 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1201 .cdw12
= cpu_to_le32(cdw12
),
1204 .ctx
= bdrv_get_aio_context(bs
),
1205 .ret
= -EINPROGRESS
,
1208 trace_nvme_prw_aligned(s
, is_write
, offset
, bytes
, flags
, qiov
->niov
);
1209 assert(s
->queue_count
> 1);
1210 req
= nvme_get_free_req(ioq
);
1213 qemu_co_mutex_lock(&s
->dma_map_lock
);
1214 r
= nvme_cmd_map_qiov(bs
, &cmd
, req
, qiov
);
1215 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1217 nvme_put_free_req_and_wake(ioq
, req
);
1220 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1222 data
.co
= qemu_coroutine_self();
1223 while (data
.ret
== -EINPROGRESS
) {
1224 qemu_coroutine_yield();
1227 qemu_co_mutex_lock(&s
->dma_map_lock
);
1228 r
= nvme_cmd_unmap_qiov(bs
, qiov
);
1229 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1234 trace_nvme_rw_done(s
, is_write
, offset
, bytes
, data
.ret
);
1238 static inline bool nvme_qiov_aligned(BlockDriverState
*bs
,
1239 const QEMUIOVector
*qiov
)
1242 BDRVNVMeState
*s
= bs
->opaque
;
1244 for (i
= 0; i
< qiov
->niov
; ++i
) {
1245 if (!QEMU_PTR_IS_ALIGNED(qiov
->iov
[i
].iov_base
,
1246 qemu_real_host_page_size()) ||
1247 !QEMU_IS_ALIGNED(qiov
->iov
[i
].iov_len
, qemu_real_host_page_size())) {
1248 trace_nvme_qiov_unaligned(qiov
, i
, qiov
->iov
[i
].iov_base
,
1249 qiov
->iov
[i
].iov_len
, s
->page_size
);
1256 static coroutine_fn
int nvme_co_prw(BlockDriverState
*bs
,
1257 uint64_t offset
, uint64_t bytes
,
1258 QEMUIOVector
*qiov
, bool is_write
,
1261 BDRVNVMeState
*s
= bs
->opaque
;
1263 QEMU_AUTO_VFREE
uint8_t *buf
= NULL
;
1264 QEMUIOVector local_qiov
;
1265 size_t len
= QEMU_ALIGN_UP(bytes
, qemu_real_host_page_size());
1266 assert(QEMU_IS_ALIGNED(offset
, s
->page_size
));
1267 assert(QEMU_IS_ALIGNED(bytes
, s
->page_size
));
1268 assert(bytes
<= s
->max_transfer
);
1269 if (nvme_qiov_aligned(bs
, qiov
)) {
1270 s
->stats
.aligned_accesses
++;
1271 return nvme_co_prw_aligned(bs
, offset
, bytes
, qiov
, is_write
, flags
);
1273 s
->stats
.unaligned_accesses
++;
1274 trace_nvme_prw_buffered(s
, offset
, bytes
, qiov
->niov
, is_write
);
1275 buf
= qemu_try_memalign(qemu_real_host_page_size(), len
);
1280 qemu_iovec_init(&local_qiov
, 1);
1282 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
1284 qemu_iovec_add(&local_qiov
, buf
, bytes
);
1285 r
= nvme_co_prw_aligned(bs
, offset
, bytes
, &local_qiov
, is_write
, flags
);
1286 qemu_iovec_destroy(&local_qiov
);
1287 if (!r
&& !is_write
) {
1288 qemu_iovec_from_buf(qiov
, 0, buf
, bytes
);
1293 static coroutine_fn
int nvme_co_preadv(BlockDriverState
*bs
,
1294 int64_t offset
, int64_t bytes
,
1296 BdrvRequestFlags flags
)
1298 return nvme_co_prw(bs
, offset
, bytes
, qiov
, false, flags
);
1301 static coroutine_fn
int nvme_co_pwritev(BlockDriverState
*bs
,
1302 int64_t offset
, int64_t bytes
,
1304 BdrvRequestFlags flags
)
1306 return nvme_co_prw(bs
, offset
, bytes
, qiov
, true, flags
);
1309 static coroutine_fn
int nvme_co_flush(BlockDriverState
*bs
)
1311 BDRVNVMeState
*s
= bs
->opaque
;
1312 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1315 .opcode
= NVME_CMD_FLUSH
,
1316 .nsid
= cpu_to_le32(s
->nsid
),
1319 .ctx
= bdrv_get_aio_context(bs
),
1320 .ret
= -EINPROGRESS
,
1323 assert(s
->queue_count
> 1);
1324 req
= nvme_get_free_req(ioq
);
1326 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1328 data
.co
= qemu_coroutine_self();
1329 if (data
.ret
== -EINPROGRESS
) {
1330 qemu_coroutine_yield();
1337 static coroutine_fn
int nvme_co_pwrite_zeroes(BlockDriverState
*bs
,
1340 BdrvRequestFlags flags
)
1342 BDRVNVMeState
*s
= bs
->opaque
;
1343 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1347 if (!s
->supports_write_zeroes
) {
1355 cdw12
= ((bytes
>> s
->blkshift
) - 1) & 0xFFFF;
1357 * We should not lose information. pwrite_zeroes_alignment and
1358 * max_pwrite_zeroes guarantees it.
1360 assert(((cdw12
+ 1) << s
->blkshift
) == bytes
);
1363 .opcode
= NVME_CMD_WRITE_ZEROES
,
1364 .nsid
= cpu_to_le32(s
->nsid
),
1365 .cdw10
= cpu_to_le32((offset
>> s
->blkshift
) & 0xFFFFFFFF),
1366 .cdw11
= cpu_to_le32(((offset
>> s
->blkshift
) >> 32) & 0xFFFFFFFF),
1370 .ctx
= bdrv_get_aio_context(bs
),
1371 .ret
= -EINPROGRESS
,
1374 if (flags
& BDRV_REQ_MAY_UNMAP
) {
1378 if (flags
& BDRV_REQ_FUA
) {
1382 cmd
.cdw12
= cpu_to_le32(cdw12
);
1384 trace_nvme_write_zeroes(s
, offset
, bytes
, flags
);
1385 assert(s
->queue_count
> 1);
1386 req
= nvme_get_free_req(ioq
);
1389 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1391 data
.co
= qemu_coroutine_self();
1392 while (data
.ret
== -EINPROGRESS
) {
1393 qemu_coroutine_yield();
1396 trace_nvme_rw_done(s
, true, offset
, bytes
, data
.ret
);
1401 static int coroutine_fn
nvme_co_pdiscard(BlockDriverState
*bs
,
1405 BDRVNVMeState
*s
= bs
->opaque
;
1406 NVMeQueuePair
*ioq
= s
->queues
[INDEX_IO(0)];
1408 QEMU_AUTO_VFREE NvmeDsmRange
*buf
= NULL
;
1409 QEMUIOVector local_qiov
;
1413 .opcode
= NVME_CMD_DSM
,
1414 .nsid
= cpu_to_le32(s
->nsid
),
1415 .cdw10
= cpu_to_le32(0), /*number of ranges - 0 based*/
1416 .cdw11
= cpu_to_le32(1 << 2), /*deallocate bit*/
1420 .ctx
= bdrv_get_aio_context(bs
),
1421 .ret
= -EINPROGRESS
,
1424 if (!s
->supports_discard
) {
1428 assert(s
->queue_count
> 1);
1431 * Filling the @buf requires @offset and @bytes to satisfy restrictions
1432 * defined in nvme_refresh_limits().
1434 assert(QEMU_IS_ALIGNED(bytes
, 1UL << s
->blkshift
));
1435 assert(QEMU_IS_ALIGNED(offset
, 1UL << s
->blkshift
));
1436 assert((bytes
>> s
->blkshift
) <= UINT32_MAX
);
1438 buf
= qemu_try_memalign(s
->page_size
, s
->page_size
);
1442 memset(buf
, 0, s
->page_size
);
1443 buf
->nlb
= cpu_to_le32(bytes
>> s
->blkshift
);
1444 buf
->slba
= cpu_to_le64(offset
>> s
->blkshift
);
1447 qemu_iovec_init(&local_qiov
, 1);
1448 qemu_iovec_add(&local_qiov
, buf
, 4096);
1450 req
= nvme_get_free_req(ioq
);
1453 qemu_co_mutex_lock(&s
->dma_map_lock
);
1454 ret
= nvme_cmd_map_qiov(bs
, &cmd
, req
, &local_qiov
);
1455 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1458 nvme_put_free_req_and_wake(ioq
, req
);
1462 trace_nvme_dsm(s
, offset
, bytes
);
1464 nvme_submit_command(ioq
, req
, &cmd
, nvme_rw_cb
, &data
);
1466 data
.co
= qemu_coroutine_self();
1467 while (data
.ret
== -EINPROGRESS
) {
1468 qemu_coroutine_yield();
1471 qemu_co_mutex_lock(&s
->dma_map_lock
);
1472 ret
= nvme_cmd_unmap_qiov(bs
, &local_qiov
);
1473 qemu_co_mutex_unlock(&s
->dma_map_lock
);
1480 trace_nvme_dsm_done(s
, offset
, bytes
, ret
);
1482 qemu_iovec_destroy(&local_qiov
);
1487 static int coroutine_fn
nvme_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1488 bool exact
, PreallocMode prealloc
,
1489 BdrvRequestFlags flags
, Error
**errp
)
1493 if (prealloc
!= PREALLOC_MODE_OFF
) {
1494 error_setg(errp
, "Unsupported preallocation mode '%s'",
1495 PreallocMode_str(prealloc
));
1499 cur_length
= nvme_co_getlength(bs
);
1500 if (offset
!= cur_length
&& exact
) {
1501 error_setg(errp
, "Cannot resize NVMe devices");
1503 } else if (offset
> cur_length
) {
1504 error_setg(errp
, "Cannot grow NVMe devices");
1511 static int nvme_reopen_prepare(BDRVReopenState
*reopen_state
,
1512 BlockReopenQueue
*queue
, Error
**errp
)
1517 static void nvme_refresh_filename(BlockDriverState
*bs
)
1519 BDRVNVMeState
*s
= bs
->opaque
;
1521 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
), "nvme://%s/%i",
1522 s
->device
, s
->nsid
);
1525 static void nvme_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1527 BDRVNVMeState
*s
= bs
->opaque
;
1529 bs
->bl
.opt_mem_alignment
= s
->page_size
;
1530 bs
->bl
.request_alignment
= s
->page_size
;
1531 bs
->bl
.max_transfer
= s
->max_transfer
;
1534 * Look at nvme_co_pwrite_zeroes: after shift and decrement we should get
1537 bs
->bl
.max_pwrite_zeroes
= 1ULL << (s
->blkshift
+ 16);
1538 bs
->bl
.pwrite_zeroes_alignment
= MAX(bs
->bl
.request_alignment
,
1539 1UL << s
->blkshift
);
1541 bs
->bl
.max_pdiscard
= (uint64_t)UINT32_MAX
<< s
->blkshift
;
1542 bs
->bl
.pdiscard_alignment
= MAX(bs
->bl
.request_alignment
,
1543 1UL << s
->blkshift
);
1546 static void nvme_detach_aio_context(BlockDriverState
*bs
)
1548 BDRVNVMeState
*s
= bs
->opaque
;
1550 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1551 NVMeQueuePair
*q
= s
->queues
[i
];
1553 qemu_bh_delete(q
->completion_bh
);
1554 q
->completion_bh
= NULL
;
1557 aio_set_event_notifier(bdrv_get_aio_context(bs
),
1558 &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1562 static void nvme_attach_aio_context(BlockDriverState
*bs
,
1563 AioContext
*new_context
)
1565 BDRVNVMeState
*s
= bs
->opaque
;
1567 s
->aio_context
= new_context
;
1568 aio_set_event_notifier(new_context
, &s
->irq_notifier
[MSIX_SHARED_IRQ_IDX
],
1569 nvme_handle_event
, nvme_poll_cb
,
1572 for (unsigned i
= 0; i
< s
->queue_count
; i
++) {
1573 NVMeQueuePair
*q
= s
->queues
[i
];
1576 aio_bh_new(new_context
, nvme_process_completion_bh
, q
);
1580 static bool nvme_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
1584 BDRVNVMeState
*s
= bs
->opaque
;
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.
1591 ret
= qemu_vfio_dma_map(s
->vfio
, host
, size
, false, NULL
, errp
);
1595 static void nvme_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
1597 BDRVNVMeState
*s
= bs
->opaque
;
1599 qemu_vfio_dma_unmap(s
->vfio
, host
);
1602 static BlockStatsSpecific
*nvme_get_specific_stats(BlockDriverState
*bs
)
1604 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
1605 BDRVNVMeState
*s
= bs
->opaque
;
1607 stats
->driver
= BLOCKDEV_DRIVER_NVME
;
1608 stats
->u
.nvme
= (BlockStatsSpecificNvme
) {
1609 .completion_errors
= s
->stats
.completion_errors
,
1610 .aligned_accesses
= s
->stats
.aligned_accesses
,
1611 .unaligned_accesses
= s
->stats
.unaligned_accesses
,
1617 static const char *const nvme_strong_runtime_opts
[] = {
1618 NVME_BLOCK_OPT_DEVICE
,
1619 NVME_BLOCK_OPT_NAMESPACE
,
1624 static BlockDriver bdrv_nvme
= {
1625 .format_name
= "nvme",
1626 .protocol_name
= "nvme",
1627 .instance_size
= sizeof(BDRVNVMeState
),
1629 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
1630 .create_opts
= &bdrv_create_opts_simple
,
1632 .bdrv_parse_filename
= nvme_parse_filename
,
1633 .bdrv_open
= nvme_open
,
1634 .bdrv_close
= nvme_close
,
1635 .bdrv_co_getlength
= nvme_co_getlength
,
1636 .bdrv_probe_blocksizes
= nvme_probe_blocksizes
,
1637 .bdrv_co_truncate
= nvme_co_truncate
,
1639 .bdrv_co_preadv
= nvme_co_preadv
,
1640 .bdrv_co_pwritev
= nvme_co_pwritev
,
1642 .bdrv_co_pwrite_zeroes
= nvme_co_pwrite_zeroes
,
1643 .bdrv_co_pdiscard
= nvme_co_pdiscard
,
1645 .bdrv_co_flush_to_disk
= nvme_co_flush
,
1646 .bdrv_reopen_prepare
= nvme_reopen_prepare
,
1648 .bdrv_refresh_filename
= nvme_refresh_filename
,
1649 .bdrv_refresh_limits
= nvme_refresh_limits
,
1650 .strong_runtime_opts
= nvme_strong_runtime_opts
,
1651 .bdrv_get_specific_stats
= nvme_get_specific_stats
,
1653 .bdrv_detach_aio_context
= nvme_detach_aio_context
,
1654 .bdrv_attach_aio_context
= nvme_attach_aio_context
,
1656 .bdrv_register_buf
= nvme_register_buf
,
1657 .bdrv_unregister_buf
= nvme_unregister_buf
,
1660 static void bdrv_nvme_init(void)
1662 bdrv_register(&bdrv_nvme
);
1665 block_init(bdrv_nvme_init
);