]> git.proxmox.com Git - mirror_qemu.git/blame - block/nvme.c
Revert "audio: fix pc speaker init"
[mirror_qemu.git] / block / nvme.c
CommitLineData
bdd6a90a
FZ
1/*
2 * NVMe block driver based on vfio
3 *
4 * Copyright 2016 - 2018 Red Hat, Inc.
5 *
6 * Authors:
7 * Fam Zheng <famz@redhat.com>
8 * Paolo Bonzini <pbonzini@redhat.com>
9 *
10 * This work is licensed under the terms of the GNU GPL, version 2 or later.
11 * See the COPYING file in the top-level directory.
12 */
13
14#include "qemu/osdep.h"
15#include <linux/vfio.h>
16#include "qapi/error.h"
17#include "qapi/qmp/qdict.h"
18#include "qapi/qmp/qstring.h"
19#include "qemu/error-report.h"
20#include "qemu/cutils.h"
922a01a0 21#include "qemu/option.h"
bdd6a90a
FZ
22#include "qemu/vfio-helpers.h"
23#include "block/block_int.h"
24#include "trace.h"
25
a3d9a352 26#include "block/nvme.h"
bdd6a90a
FZ
27
28#define NVME_SQ_ENTRY_BYTES 64
29#define NVME_CQ_ENTRY_BYTES 16
30#define NVME_QUEUE_SIZE 128
31#define NVME_BAR_SIZE 8192
32
33typedef struct {
34 int32_t head, tail;
35 uint8_t *queue;
36 uint64_t iova;
37 /* Hardware MMIO register */
38 volatile uint32_t *doorbell;
39} NVMeQueue;
40
41typedef struct {
42 BlockCompletionFunc *cb;
43 void *opaque;
44 int cid;
45 void *prp_list_page;
46 uint64_t prp_list_iova;
47 bool busy;
48} NVMeRequest;
49
50typedef struct {
51 CoQueue free_req_queue;
52 QemuMutex lock;
53
54 /* Fields protected by BQL */
55 int index;
56 uint8_t *prp_list_pages;
57
58 /* Fields protected by @lock */
59 NVMeQueue sq, cq;
60 int cq_phase;
61 NVMeRequest reqs[NVME_QUEUE_SIZE];
62 bool busy;
63 int need_kick;
64 int inflight;
65} NVMeQueuePair;
66
67/* Memory mapped registers */
68typedef volatile struct {
69 uint64_t cap;
70 uint32_t vs;
71 uint32_t intms;
72 uint32_t intmc;
73 uint32_t cc;
74 uint32_t reserved0;
75 uint32_t csts;
76 uint32_t nssr;
77 uint32_t aqa;
78 uint64_t asq;
79 uint64_t acq;
80 uint32_t cmbloc;
81 uint32_t cmbsz;
82 uint8_t reserved1[0xec0];
83 uint8_t cmd_set_specfic[0x100];
84 uint32_t doorbells[];
83c68e14 85} NVMeRegs;
bdd6a90a
FZ
86
87QEMU_BUILD_BUG_ON(offsetof(NVMeRegs, doorbells) != 0x1000);
88
89typedef struct {
90 AioContext *aio_context;
91 QEMUVFIOState *vfio;
92 NVMeRegs *regs;
93 /* The submission/completion queue pairs.
94 * [0]: admin queue.
95 * [1..]: io queues.
96 */
97 NVMeQueuePair **queues;
98 int nr_queues;
99 size_t page_size;
100 /* How many uint32_t elements does each doorbell entry take. */
101 size_t doorbell_scale;
102 bool write_cache_supported;
103 EventNotifier irq_notifier;
104 uint64_t nsze; /* Namespace size reported by identify command */
105 int nsid; /* The namespace id to read/write data. */
106 uint64_t max_transfer;
2f0d8947 107 bool plugged;
bdd6a90a
FZ
108
109 CoMutex dma_map_lock;
110 CoQueue dma_flush_queue;
111
112 /* Total size of mapped qiov, accessed under dma_map_lock */
113 int dma_map_count;
cc61b074
HR
114
115 /* PCI address (required for nvme_refresh_filename()) */
116 char *device;
bdd6a90a
FZ
117} BDRVNVMeState;
118
119#define NVME_BLOCK_OPT_DEVICE "device"
120#define NVME_BLOCK_OPT_NAMESPACE "namespace"
121
122static QemuOptsList runtime_opts = {
123 .name = "nvme",
124 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
125 .desc = {
126 {
127 .name = NVME_BLOCK_OPT_DEVICE,
128 .type = QEMU_OPT_STRING,
129 .help = "NVMe PCI device address",
130 },
131 {
132 .name = NVME_BLOCK_OPT_NAMESPACE,
133 .type = QEMU_OPT_NUMBER,
134 .help = "NVMe namespace",
135 },
136 { /* end of list */ }
137 },
138};
139
140static void nvme_init_queue(BlockDriverState *bs, NVMeQueue *q,
141 int nentries, int entry_bytes, Error **errp)
142{
143 BDRVNVMeState *s = bs->opaque;
144 size_t bytes;
145 int r;
146
147 bytes = ROUND_UP(nentries * entry_bytes, s->page_size);
148 q->head = q->tail = 0;
149 q->queue = qemu_try_blockalign0(bs, bytes);
150
151 if (!q->queue) {
152 error_setg(errp, "Cannot allocate queue");
153 return;
154 }
155 r = qemu_vfio_dma_map(s->vfio, q->queue, bytes, false, &q->iova);
156 if (r) {
157 error_setg(errp, "Cannot map queue");
158 }
159}
160
161static void nvme_free_queue_pair(BlockDriverState *bs, NVMeQueuePair *q)
162{
163 qemu_vfree(q->prp_list_pages);
164 qemu_vfree(q->sq.queue);
165 qemu_vfree(q->cq.queue);
166 qemu_mutex_destroy(&q->lock);
167 g_free(q);
168}
169
170static void nvme_free_req_queue_cb(void *opaque)
171{
172 NVMeQueuePair *q = opaque;
173
174 qemu_mutex_lock(&q->lock);
175 while (qemu_co_enter_next(&q->free_req_queue, &q->lock)) {
176 /* Retry all pending requests */
177 }
178 qemu_mutex_unlock(&q->lock);
179}
180
181static NVMeQueuePair *nvme_create_queue_pair(BlockDriverState *bs,
182 int idx, int size,
183 Error **errp)
184{
185 int i, r;
186 BDRVNVMeState *s = bs->opaque;
187 Error *local_err = NULL;
188 NVMeQueuePair *q = g_new0(NVMeQueuePair, 1);
189 uint64_t prp_list_iova;
190
191 qemu_mutex_init(&q->lock);
192 q->index = idx;
193 qemu_co_queue_init(&q->free_req_queue);
194 q->prp_list_pages = qemu_blockalign0(bs, s->page_size * NVME_QUEUE_SIZE);
195 r = qemu_vfio_dma_map(s->vfio, q->prp_list_pages,
196 s->page_size * NVME_QUEUE_SIZE,
197 false, &prp_list_iova);
198 if (r) {
199 goto fail;
200 }
201 for (i = 0; i < NVME_QUEUE_SIZE; i++) {
202 NVMeRequest *req = &q->reqs[i];
203 req->cid = i + 1;
204 req->prp_list_page = q->prp_list_pages + i * s->page_size;
205 req->prp_list_iova = prp_list_iova + i * s->page_size;
206 }
207 nvme_init_queue(bs, &q->sq, size, NVME_SQ_ENTRY_BYTES, &local_err);
208 if (local_err) {
209 error_propagate(errp, local_err);
210 goto fail;
211 }
212 q->sq.doorbell = &s->regs->doorbells[idx * 2 * s->doorbell_scale];
213
214 nvme_init_queue(bs, &q->cq, size, NVME_CQ_ENTRY_BYTES, &local_err);
215 if (local_err) {
216 error_propagate(errp, local_err);
217 goto fail;
218 }
219 q->cq.doorbell = &s->regs->doorbells[idx * 2 * s->doorbell_scale + 1];
220
221 return q;
222fail:
223 nvme_free_queue_pair(bs, q);
224 return NULL;
225}
226
227/* With q->lock */
228static void nvme_kick(BDRVNVMeState *s, NVMeQueuePair *q)
229{
230 if (s->plugged || !q->need_kick) {
231 return;
232 }
233 trace_nvme_kick(s, q->index);
234 assert(!(q->sq.tail & 0xFF00));
235 /* Fence the write to submission queue entry before notifying the device. */
236 smp_wmb();
237 *q->sq.doorbell = cpu_to_le32(q->sq.tail);
238 q->inflight += q->need_kick;
239 q->need_kick = 0;
240}
241
242/* Find a free request element if any, otherwise:
243 * a) if in coroutine context, try to wait for one to become available;
244 * b) if not in coroutine, return NULL;
245 */
246static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
247{
248 int i;
249 NVMeRequest *req = NULL;
250
251 qemu_mutex_lock(&q->lock);
252 while (q->inflight + q->need_kick > NVME_QUEUE_SIZE - 2) {
253 /* We have to leave one slot empty as that is the full queue case (head
254 * == tail + 1). */
255 if (qemu_in_coroutine()) {
256 trace_nvme_free_req_queue_wait(q);
257 qemu_co_queue_wait(&q->free_req_queue, &q->lock);
258 } else {
259 qemu_mutex_unlock(&q->lock);
260 return NULL;
261 }
262 }
263 for (i = 0; i < NVME_QUEUE_SIZE; i++) {
264 if (!q->reqs[i].busy) {
265 q->reqs[i].busy = true;
266 req = &q->reqs[i];
267 break;
268 }
269 }
270 /* We have checked inflight and need_kick while holding q->lock, so one
271 * free req must be available. */
272 assert(req);
273 qemu_mutex_unlock(&q->lock);
274 return req;
275}
276
277static inline int nvme_translate_error(const NvmeCqe *c)
278{
279 uint16_t status = (le16_to_cpu(c->status) >> 1) & 0xFF;
280 if (status) {
281 trace_nvme_error(le32_to_cpu(c->result),
282 le16_to_cpu(c->sq_head),
283 le16_to_cpu(c->sq_id),
284 le16_to_cpu(c->cid),
285 le16_to_cpu(status));
286 }
287 switch (status) {
288 case 0:
289 return 0;
290 case 1:
291 return -ENOSYS;
292 case 2:
293 return -EINVAL;
294 default:
295 return -EIO;
296 }
297}
298
299/* With q->lock */
300static bool nvme_process_completion(BDRVNVMeState *s, NVMeQueuePair *q)
301{
302 bool progress = false;
303 NVMeRequest *preq;
304 NVMeRequest req;
305 NvmeCqe *c;
306
307 trace_nvme_process_completion(s, q->index, q->inflight);
308 if (q->busy || s->plugged) {
309 trace_nvme_process_completion_queue_busy(s, q->index);
310 return false;
311 }
312 q->busy = true;
313 assert(q->inflight >= 0);
314 while (q->inflight) {
315 int16_t cid;
316 c = (NvmeCqe *)&q->cq.queue[q->cq.head * NVME_CQ_ENTRY_BYTES];
317 if (!c->cid || (le16_to_cpu(c->status) & 0x1) == q->cq_phase) {
318 break;
319 }
320 q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
321 if (!q->cq.head) {
322 q->cq_phase = !q->cq_phase;
323 }
324 cid = le16_to_cpu(c->cid);
325 if (cid == 0 || cid > NVME_QUEUE_SIZE) {
326 fprintf(stderr, "Unexpected CID in completion queue: %" PRIu32 "\n",
327 cid);
328 continue;
329 }
330 assert(cid <= NVME_QUEUE_SIZE);
331 trace_nvme_complete_command(s, q->index, cid);
332 preq = &q->reqs[cid - 1];
333 req = *preq;
334 assert(req.cid == cid);
335 assert(req.cb);
336 preq->busy = false;
337 preq->cb = preq->opaque = NULL;
338 qemu_mutex_unlock(&q->lock);
339 req.cb(req.opaque, nvme_translate_error(c));
340 qemu_mutex_lock(&q->lock);
341 c->cid = cpu_to_le16(0);
342 q->inflight--;
343 /* Flip Phase Tag bit. */
344 c->status = cpu_to_le16(le16_to_cpu(c->status) ^ 0x1);
345 progress = true;
346 }
347 if (progress) {
348 /* Notify the device so it can post more completions. */
349 smp_mb_release();
350 *q->cq.doorbell = cpu_to_le32(q->cq.head);
351 if (!qemu_co_queue_empty(&q->free_req_queue)) {
352 aio_bh_schedule_oneshot(s->aio_context, nvme_free_req_queue_cb, q);
353 }
354 }
355 q->busy = false;
356 return progress;
357}
358
359static void nvme_trace_command(const NvmeCmd *cmd)
360{
361 int i;
362
363 for (i = 0; i < 8; ++i) {
364 uint8_t *cmdp = (uint8_t *)cmd + i * 8;
365 trace_nvme_submit_command_raw(cmdp[0], cmdp[1], cmdp[2], cmdp[3],
366 cmdp[4], cmdp[5], cmdp[6], cmdp[7]);
367 }
368}
369
370static void nvme_submit_command(BDRVNVMeState *s, NVMeQueuePair *q,
371 NVMeRequest *req,
372 NvmeCmd *cmd, BlockCompletionFunc cb,
373 void *opaque)
374{
375 assert(!req->cb);
376 req->cb = cb;
377 req->opaque = opaque;
378 cmd->cid = cpu_to_le32(req->cid);
379
380 trace_nvme_submit_command(s, q->index, req->cid);
381 nvme_trace_command(cmd);
382 qemu_mutex_lock(&q->lock);
383 memcpy((uint8_t *)q->sq.queue +
384 q->sq.tail * NVME_SQ_ENTRY_BYTES, cmd, sizeof(*cmd));
385 q->sq.tail = (q->sq.tail + 1) % NVME_QUEUE_SIZE;
386 q->need_kick++;
387 nvme_kick(s, q);
388 nvme_process_completion(s, q);
389 qemu_mutex_unlock(&q->lock);
390}
391
392static void nvme_cmd_sync_cb(void *opaque, int ret)
393{
394 int *pret = opaque;
395 *pret = ret;
4720cbee 396 aio_wait_kick();
bdd6a90a
FZ
397}
398
399static int nvme_cmd_sync(BlockDriverState *bs, NVMeQueuePair *q,
400 NvmeCmd *cmd)
401{
402 NVMeRequest *req;
403 BDRVNVMeState *s = bs->opaque;
404 int ret = -EINPROGRESS;
405 req = nvme_get_free_req(q);
406 if (!req) {
407 return -EBUSY;
408 }
409 nvme_submit_command(s, q, req, cmd, nvme_cmd_sync_cb, &ret);
410
411 BDRV_POLL_WHILE(bs, ret == -EINPROGRESS);
412 return ret;
413}
414
415static void nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
416{
417 BDRVNVMeState *s = bs->opaque;
418 NvmeIdCtrl *idctrl;
419 NvmeIdNs *idns;
420 uint8_t *resp;
421 int r;
422 uint64_t iova;
423 NvmeCmd cmd = {
424 .opcode = NVME_ADM_CMD_IDENTIFY,
425 .cdw10 = cpu_to_le32(0x1),
426 };
427
428 resp = qemu_try_blockalign0(bs, sizeof(NvmeIdCtrl));
429 if (!resp) {
430 error_setg(errp, "Cannot allocate buffer for identify response");
431 goto out;
432 }
433 idctrl = (NvmeIdCtrl *)resp;
434 idns = (NvmeIdNs *)resp;
435 r = qemu_vfio_dma_map(s->vfio, resp, sizeof(NvmeIdCtrl), true, &iova);
436 if (r) {
437 error_setg(errp, "Cannot map buffer for DMA");
438 goto out;
439 }
440 cmd.prp1 = cpu_to_le64(iova);
441
442 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
443 error_setg(errp, "Failed to identify controller");
444 goto out;
445 }
446
447 if (le32_to_cpu(idctrl->nn) < namespace) {
448 error_setg(errp, "Invalid namespace");
449 goto out;
450 }
451 s->write_cache_supported = le32_to_cpu(idctrl->vwc) & 0x1;
452 s->max_transfer = (idctrl->mdts ? 1 << idctrl->mdts : 0) * s->page_size;
453 /* For now the page list buffer per command is one page, to hold at most
454 * s->page_size / sizeof(uint64_t) entries. */
455 s->max_transfer = MIN_NON_ZERO(s->max_transfer,
456 s->page_size / sizeof(uint64_t) * s->page_size);
457
458 memset(resp, 0, 4096);
459
460 cmd.cdw10 = 0;
461 cmd.nsid = cpu_to_le32(namespace);
462 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
463 error_setg(errp, "Failed to identify namespace");
464 goto out;
465 }
466
467 s->nsze = le64_to_cpu(idns->nsze);
468
469out:
470 qemu_vfio_dma_unmap(s->vfio, resp);
471 qemu_vfree(resp);
472}
473
474static bool nvme_poll_queues(BDRVNVMeState *s)
475{
476 bool progress = false;
477 int i;
478
479 for (i = 0; i < s->nr_queues; i++) {
480 NVMeQueuePair *q = s->queues[i];
481 qemu_mutex_lock(&q->lock);
482 while (nvme_process_completion(s, q)) {
483 /* Keep polling */
484 progress = true;
485 }
486 qemu_mutex_unlock(&q->lock);
487 }
488 return progress;
489}
490
491static void nvme_handle_event(EventNotifier *n)
492{
493 BDRVNVMeState *s = container_of(n, BDRVNVMeState, irq_notifier);
494
495 trace_nvme_handle_event(s);
bdd6a90a
FZ
496 event_notifier_test_and_clear(n);
497 nvme_poll_queues(s);
bdd6a90a
FZ
498}
499
500static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
501{
502 BDRVNVMeState *s = bs->opaque;
503 int n = s->nr_queues;
504 NVMeQueuePair *q;
505 NvmeCmd cmd;
506 int queue_size = NVME_QUEUE_SIZE;
507
508 q = nvme_create_queue_pair(bs, n, queue_size, errp);
509 if (!q) {
510 return false;
511 }
512 cmd = (NvmeCmd) {
513 .opcode = NVME_ADM_CMD_CREATE_CQ,
514 .prp1 = cpu_to_le64(q->cq.iova),
515 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | (n & 0xFFFF)),
516 .cdw11 = cpu_to_le32(0x3),
517 };
518 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
519 error_setg(errp, "Failed to create io queue [%d]", n);
520 nvme_free_queue_pair(bs, q);
521 return false;
522 }
523 cmd = (NvmeCmd) {
524 .opcode = NVME_ADM_CMD_CREATE_SQ,
525 .prp1 = cpu_to_le64(q->sq.iova),
526 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | (n & 0xFFFF)),
527 .cdw11 = cpu_to_le32(0x1 | (n << 16)),
528 };
529 if (nvme_cmd_sync(bs, s->queues[0], &cmd)) {
530 error_setg(errp, "Failed to create io queue [%d]", n);
531 nvme_free_queue_pair(bs, q);
532 return false;
533 }
534 s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
535 s->queues[n] = q;
536 s->nr_queues++;
537 return true;
538}
539
540static bool nvme_poll_cb(void *opaque)
541{
542 EventNotifier *e = opaque;
543 BDRVNVMeState *s = container_of(e, BDRVNVMeState, irq_notifier);
544 bool progress = false;
545
546 trace_nvme_poll_cb(s);
547 progress = nvme_poll_queues(s);
548 return progress;
549}
550
551static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
552 Error **errp)
553{
554 BDRVNVMeState *s = bs->opaque;
555 int ret;
556 uint64_t cap;
557 uint64_t timeout_ms;
558 uint64_t deadline, now;
559 Error *local_err = NULL;
560
561 qemu_co_mutex_init(&s->dma_map_lock);
562 qemu_co_queue_init(&s->dma_flush_queue);
cc61b074 563 s->device = g_strdup(device);
bdd6a90a
FZ
564 s->nsid = namespace;
565 s->aio_context = bdrv_get_aio_context(bs);
566 ret = event_notifier_init(&s->irq_notifier, 0);
567 if (ret) {
568 error_setg(errp, "Failed to init event notifier");
569 return ret;
570 }
571
572 s->vfio = qemu_vfio_open_pci(device, errp);
573 if (!s->vfio) {
574 ret = -EINVAL;
9582f357 575 goto out;
bdd6a90a
FZ
576 }
577
578 s->regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, NVME_BAR_SIZE, errp);
579 if (!s->regs) {
580 ret = -EINVAL;
9582f357 581 goto out;
bdd6a90a
FZ
582 }
583
584 /* Perform initialize sequence as described in NVMe spec "7.6.1
585 * Initialization". */
586
587 cap = le64_to_cpu(s->regs->cap);
588 if (!(cap & (1ULL << 37))) {
589 error_setg(errp, "Device doesn't support NVMe command set");
590 ret = -EINVAL;
9582f357 591 goto out;
bdd6a90a
FZ
592 }
593
594 s->page_size = MAX(4096, 1 << (12 + ((cap >> 48) & 0xF)));
595 s->doorbell_scale = (4 << (((cap >> 32) & 0xF))) / sizeof(uint32_t);
596 bs->bl.opt_mem_alignment = s->page_size;
597 timeout_ms = MIN(500 * ((cap >> 24) & 0xFF), 30000);
598
599 /* Reset device to get a clean state. */
600 s->regs->cc = cpu_to_le32(le32_to_cpu(s->regs->cc) & 0xFE);
601 /* Wait for CSTS.RDY = 0. */
602 deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * 1000000ULL;
603 while (le32_to_cpu(s->regs->csts) & 0x1) {
604 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
605 error_setg(errp, "Timeout while waiting for device to reset (%"
606 PRId64 " ms)",
607 timeout_ms);
608 ret = -ETIMEDOUT;
9582f357 609 goto out;
bdd6a90a
FZ
610 }
611 }
612
613 /* Set up admin queue. */
614 s->queues = g_new(NVMeQueuePair *, 1);
615 s->nr_queues = 1;
616 s->queues[0] = nvme_create_queue_pair(bs, 0, NVME_QUEUE_SIZE, errp);
617 if (!s->queues[0]) {
618 ret = -EINVAL;
9582f357 619 goto out;
bdd6a90a
FZ
620 }
621 QEMU_BUILD_BUG_ON(NVME_QUEUE_SIZE & 0xF000);
622 s->regs->aqa = cpu_to_le32((NVME_QUEUE_SIZE << 16) | NVME_QUEUE_SIZE);
623 s->regs->asq = cpu_to_le64(s->queues[0]->sq.iova);
624 s->regs->acq = cpu_to_le64(s->queues[0]->cq.iova);
625
626 /* After setting up all control registers we can enable device now. */
627 s->regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << 20) |
628 (ctz32(NVME_SQ_ENTRY_BYTES) << 16) |
629 0x1);
630 /* Wait for CSTS.RDY = 1. */
631 now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
632 deadline = now + timeout_ms * 1000000;
633 while (!(le32_to_cpu(s->regs->csts) & 0x1)) {
634 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
635 error_setg(errp, "Timeout while waiting for device to start (%"
636 PRId64 " ms)",
637 timeout_ms);
638 ret = -ETIMEDOUT;
9582f357 639 goto out;
bdd6a90a
FZ
640 }
641 }
642
643 ret = qemu_vfio_pci_init_irq(s->vfio, &s->irq_notifier,
644 VFIO_PCI_MSIX_IRQ_INDEX, errp);
645 if (ret) {
9582f357 646 goto out;
bdd6a90a
FZ
647 }
648 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
649 false, nvme_handle_event, nvme_poll_cb);
650
78d8c99e 651 nvme_identify(bs, namespace, &local_err);
bdd6a90a
FZ
652 if (local_err) {
653 error_propagate(errp, local_err);
654 ret = -EIO;
9582f357 655 goto out;
bdd6a90a
FZ
656 }
657
658 /* Set up command queues. */
659 if (!nvme_add_io_queue(bs, errp)) {
660 ret = -EIO;
bdd6a90a 661 }
9582f357
FZ
662out:
663 /* Cleaning up is done in nvme_file_open() upon error. */
bdd6a90a
FZ
664 return ret;
665}
666
667/* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
668 *
669 * nvme://0000:44:00.0/1
670 *
671 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
672 * is the PCI address, and the last part is the namespace number starting from
673 * 1 according to the NVMe spec. */
674static void nvme_parse_filename(const char *filename, QDict *options,
675 Error **errp)
676{
677 int pref = strlen("nvme://");
678
679 if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
680 const char *tmp = filename + pref;
681 char *device;
682 const char *namespace;
683 unsigned long ns;
684 const char *slash = strchr(tmp, '/');
685 if (!slash) {
625eaca9 686 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
bdd6a90a
FZ
687 return;
688 }
689 device = g_strndup(tmp, slash - tmp);
625eaca9 690 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
bdd6a90a
FZ
691 g_free(device);
692 namespace = slash + 1;
693 if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
694 error_setg(errp, "Invalid namespace '%s', positive number expected",
695 namespace);
696 return;
697 }
625eaca9
LV
698 qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
699 *namespace ? namespace : "1");
bdd6a90a
FZ
700 }
701}
702
703static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
704 Error **errp)
705{
706 int ret;
707 BDRVNVMeState *s = bs->opaque;
708 NvmeCmd cmd = {
709 .opcode = NVME_ADM_CMD_SET_FEATURES,
710 .nsid = cpu_to_le32(s->nsid),
711 .cdw10 = cpu_to_le32(0x06),
712 .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
713 };
714
715 ret = nvme_cmd_sync(bs, s->queues[0], &cmd);
716 if (ret) {
717 error_setg(errp, "Failed to configure NVMe write cache");
718 }
719 return ret;
720}
721
722static void nvme_close(BlockDriverState *bs)
723{
724 int i;
725 BDRVNVMeState *s = bs->opaque;
726
727 for (i = 0; i < s->nr_queues; ++i) {
728 nvme_free_queue_pair(bs, s->queues[i]);
729 }
9582f357 730 g_free(s->queues);
bdd6a90a
FZ
731 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
732 false, NULL, NULL);
9582f357 733 event_notifier_cleanup(&s->irq_notifier);
bdd6a90a
FZ
734 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)s->regs, 0, NVME_BAR_SIZE);
735 qemu_vfio_close(s->vfio);
cc61b074
HR
736
737 g_free(s->device);
bdd6a90a
FZ
738}
739
740static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
741 Error **errp)
742{
743 const char *device;
744 QemuOpts *opts;
745 int namespace;
746 int ret;
747 BDRVNVMeState *s = bs->opaque;
748
749 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
750 qemu_opts_absorb_qdict(opts, options, &error_abort);
751 device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
752 if (!device) {
753 error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
754 qemu_opts_del(opts);
755 return -EINVAL;
756 }
757
758 namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
759 ret = nvme_init(bs, device, namespace, errp);
760 qemu_opts_del(opts);
761 if (ret) {
762 goto fail;
763 }
764 if (flags & BDRV_O_NOCACHE) {
765 if (!s->write_cache_supported) {
766 error_setg(errp,
767 "NVMe controller doesn't support write cache configuration");
768 ret = -EINVAL;
769 } else {
770 ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
771 errp);
772 }
773 if (ret) {
774 goto fail;
775 }
776 }
777 bs->supported_write_flags = BDRV_REQ_FUA;
778 return 0;
779fail:
780 nvme_close(bs);
781 return ret;
782}
783
784static int64_t nvme_getlength(BlockDriverState *bs)
785{
786 BDRVNVMeState *s = bs->opaque;
787
788 return s->nsze << BDRV_SECTOR_BITS;
789}
790
791/* Called with s->dma_map_lock */
792static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
793 QEMUIOVector *qiov)
794{
795 int r = 0;
796 BDRVNVMeState *s = bs->opaque;
797
798 s->dma_map_count -= qiov->size;
799 if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
800 r = qemu_vfio_dma_reset_temporary(s->vfio);
801 if (!r) {
802 qemu_co_queue_restart_all(&s->dma_flush_queue);
803 }
804 }
805 return r;
806}
807
808/* Called with s->dma_map_lock */
809static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
810 NVMeRequest *req, QEMUIOVector *qiov)
811{
812 BDRVNVMeState *s = bs->opaque;
813 uint64_t *pagelist = req->prp_list_page;
814 int i, j, r;
815 int entries = 0;
816
817 assert(qiov->size);
818 assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
819 assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
820 for (i = 0; i < qiov->niov; ++i) {
821 bool retry = true;
822 uint64_t iova;
823try_map:
824 r = qemu_vfio_dma_map(s->vfio,
825 qiov->iov[i].iov_base,
826 qiov->iov[i].iov_len,
827 true, &iova);
828 if (r == -ENOMEM && retry) {
829 retry = false;
830 trace_nvme_dma_flush_queue_wait(s);
831 if (s->dma_map_count) {
832 trace_nvme_dma_map_flush(s);
833 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
834 } else {
835 r = qemu_vfio_dma_reset_temporary(s->vfio);
836 if (r) {
837 goto fail;
838 }
839 }
840 goto try_map;
841 }
842 if (r) {
843 goto fail;
844 }
845
846 for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
2916405a 847 pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
bdd6a90a
FZ
848 }
849 trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
850 qiov->iov[i].iov_len / s->page_size);
851 }
852
853 s->dma_map_count += qiov->size;
854
855 assert(entries <= s->page_size / sizeof(uint64_t));
856 switch (entries) {
857 case 0:
858 abort();
859 case 1:
2916405a 860 cmd->prp1 = pagelist[0];
bdd6a90a
FZ
861 cmd->prp2 = 0;
862 break;
863 case 2:
2916405a
LF
864 cmd->prp1 = pagelist[0];
865 cmd->prp2 = pagelist[1];
bdd6a90a
FZ
866 break;
867 default:
2916405a
LF
868 cmd->prp1 = pagelist[0];
869 cmd->prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
bdd6a90a
FZ
870 break;
871 }
872 trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
873 for (i = 0; i < entries; ++i) {
874 trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
875 }
876 return 0;
877fail:
878 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
879 * increment s->dma_map_count. This is okay for fixed mapping memory areas
880 * because they are already mapped before calling this function; for
881 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
882 * calling qemu_vfio_dma_reset_temporary when necessary. */
883 return r;
884}
885
886typedef struct {
887 Coroutine *co;
888 int ret;
889 AioContext *ctx;
890} NVMeCoData;
891
892static void nvme_rw_cb_bh(void *opaque)
893{
894 NVMeCoData *data = opaque;
895 qemu_coroutine_enter(data->co);
896}
897
898static void nvme_rw_cb(void *opaque, int ret)
899{
900 NVMeCoData *data = opaque;
901 data->ret = ret;
902 if (!data->co) {
903 /* The rw coroutine hasn't yielded, don't try to enter. */
904 return;
905 }
906 aio_bh_schedule_oneshot(data->ctx, nvme_rw_cb_bh, data);
907}
908
909static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
910 uint64_t offset, uint64_t bytes,
911 QEMUIOVector *qiov,
912 bool is_write,
913 int flags)
914{
915 int r;
916 BDRVNVMeState *s = bs->opaque;
917 NVMeQueuePair *ioq = s->queues[1];
918 NVMeRequest *req;
919 uint32_t cdw12 = (((bytes >> BDRV_SECTOR_BITS) - 1) & 0xFFFF) |
920 (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
921 NvmeCmd cmd = {
922 .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
923 .nsid = cpu_to_le32(s->nsid),
924 .cdw10 = cpu_to_le32((offset >> BDRV_SECTOR_BITS) & 0xFFFFFFFF),
925 .cdw11 = cpu_to_le32(((offset >> BDRV_SECTOR_BITS) >> 32) & 0xFFFFFFFF),
926 .cdw12 = cpu_to_le32(cdw12),
927 };
928 NVMeCoData data = {
929 .ctx = bdrv_get_aio_context(bs),
930 .ret = -EINPROGRESS,
931 };
932
933 trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
934 assert(s->nr_queues > 1);
935 req = nvme_get_free_req(ioq);
936 assert(req);
937
938 qemu_co_mutex_lock(&s->dma_map_lock);
939 r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
940 qemu_co_mutex_unlock(&s->dma_map_lock);
941 if (r) {
942 req->busy = false;
943 return r;
944 }
945 nvme_submit_command(s, ioq, req, &cmd, nvme_rw_cb, &data);
946
947 data.co = qemu_coroutine_self();
948 while (data.ret == -EINPROGRESS) {
949 qemu_coroutine_yield();
950 }
951
952 qemu_co_mutex_lock(&s->dma_map_lock);
953 r = nvme_cmd_unmap_qiov(bs, qiov);
954 qemu_co_mutex_unlock(&s->dma_map_lock);
955 if (r) {
956 return r;
957 }
958
959 trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
960 return data.ret;
961}
962
963static inline bool nvme_qiov_aligned(BlockDriverState *bs,
964 const QEMUIOVector *qiov)
965{
966 int i;
967 BDRVNVMeState *s = bs->opaque;
968
969 for (i = 0; i < qiov->niov; ++i) {
970 if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base, s->page_size) ||
971 !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, s->page_size)) {
972 trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
973 qiov->iov[i].iov_len, s->page_size);
974 return false;
975 }
976 }
977 return true;
978}
979
980static int nvme_co_prw(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
981 QEMUIOVector *qiov, bool is_write, int flags)
982{
983 BDRVNVMeState *s = bs->opaque;
984 int r;
985 uint8_t *buf = NULL;
986 QEMUIOVector local_qiov;
987
988 assert(QEMU_IS_ALIGNED(offset, s->page_size));
989 assert(QEMU_IS_ALIGNED(bytes, s->page_size));
990 assert(bytes <= s->max_transfer);
991 if (nvme_qiov_aligned(bs, qiov)) {
992 return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
993 }
994 trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
995 buf = qemu_try_blockalign(bs, bytes);
996
997 if (!buf) {
998 return -ENOMEM;
999 }
1000 qemu_iovec_init(&local_qiov, 1);
1001 if (is_write) {
1002 qemu_iovec_to_buf(qiov, 0, buf, bytes);
1003 }
1004 qemu_iovec_add(&local_qiov, buf, bytes);
1005 r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
1006 qemu_iovec_destroy(&local_qiov);
1007 if (!r && !is_write) {
1008 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1009 }
1010 qemu_vfree(buf);
1011 return r;
1012}
1013
1014static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1015 uint64_t offset, uint64_t bytes,
1016 QEMUIOVector *qiov, int flags)
1017{
1018 return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1019}
1020
1021static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1022 uint64_t offset, uint64_t bytes,
1023 QEMUIOVector *qiov, int flags)
1024{
1025 return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1026}
1027
1028static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1029{
1030 BDRVNVMeState *s = bs->opaque;
1031 NVMeQueuePair *ioq = s->queues[1];
1032 NVMeRequest *req;
1033 NvmeCmd cmd = {
1034 .opcode = NVME_CMD_FLUSH,
1035 .nsid = cpu_to_le32(s->nsid),
1036 };
1037 NVMeCoData data = {
1038 .ctx = bdrv_get_aio_context(bs),
1039 .ret = -EINPROGRESS,
1040 };
1041
1042 assert(s->nr_queues > 1);
1043 req = nvme_get_free_req(ioq);
1044 assert(req);
1045 nvme_submit_command(s, ioq, req, &cmd, nvme_rw_cb, &data);
1046
1047 data.co = qemu_coroutine_self();
1048 if (data.ret == -EINPROGRESS) {
1049 qemu_coroutine_yield();
1050 }
1051
1052 return data.ret;
1053}
1054
1055
1056static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1057 BlockReopenQueue *queue, Error **errp)
1058{
1059 return 0;
1060}
1061
998b3a1e 1062static void nvme_refresh_filename(BlockDriverState *bs)
bdd6a90a 1063{
cc61b074 1064 BDRVNVMeState *s = bs->opaque;
bdd6a90a 1065
cc61b074
HR
1066 snprintf(bs->exact_filename, sizeof(bs->exact_filename), "nvme://%s/%i",
1067 s->device, s->nsid);
bdd6a90a
FZ
1068}
1069
1070static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1071{
1072 BDRVNVMeState *s = bs->opaque;
1073
1074 bs->bl.opt_mem_alignment = s->page_size;
1075 bs->bl.request_alignment = s->page_size;
1076 bs->bl.max_transfer = s->max_transfer;
1077}
1078
1079static void nvme_detach_aio_context(BlockDriverState *bs)
1080{
1081 BDRVNVMeState *s = bs->opaque;
1082
1083 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
1084 false, NULL, NULL);
1085}
1086
1087static void nvme_attach_aio_context(BlockDriverState *bs,
1088 AioContext *new_context)
1089{
1090 BDRVNVMeState *s = bs->opaque;
1091
1092 s->aio_context = new_context;
1093 aio_set_event_notifier(new_context, &s->irq_notifier,
1094 false, nvme_handle_event, nvme_poll_cb);
1095}
1096
1097static void nvme_aio_plug(BlockDriverState *bs)
1098{
1099 BDRVNVMeState *s = bs->opaque;
2f0d8947
PB
1100 assert(!s->plugged);
1101 s->plugged = true;
bdd6a90a
FZ
1102}
1103
1104static void nvme_aio_unplug(BlockDriverState *bs)
1105{
1106 int i;
1107 BDRVNVMeState *s = bs->opaque;
1108 assert(s->plugged);
2f0d8947
PB
1109 s->plugged = false;
1110 for (i = 1; i < s->nr_queues; i++) {
1111 NVMeQueuePair *q = s->queues[i];
1112 qemu_mutex_lock(&q->lock);
1113 nvme_kick(s, q);
1114 nvme_process_completion(s, q);
1115 qemu_mutex_unlock(&q->lock);
bdd6a90a
FZ
1116 }
1117}
1118
9ed61612
FZ
1119static void nvme_register_buf(BlockDriverState *bs, void *host, size_t size)
1120{
1121 int ret;
1122 BDRVNVMeState *s = bs->opaque;
1123
1124 ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL);
1125 if (ret) {
1126 /* FIXME: we may run out of IOVA addresses after repeated
1127 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1128 * doesn't reclaim addresses for fixed mappings. */
1129 error_report("nvme_register_buf failed: %s", strerror(-ret));
1130 }
1131}
1132
1133static void nvme_unregister_buf(BlockDriverState *bs, void *host)
1134{
1135 BDRVNVMeState *s = bs->opaque;
1136
1137 qemu_vfio_dma_unmap(s->vfio, host);
1138}
1139
2654267c
HR
1140static const char *const nvme_strong_runtime_opts[] = {
1141 NVME_BLOCK_OPT_DEVICE,
1142 NVME_BLOCK_OPT_NAMESPACE,
1143
1144 NULL
1145};
1146
bdd6a90a
FZ
1147static BlockDriver bdrv_nvme = {
1148 .format_name = "nvme",
1149 .protocol_name = "nvme",
1150 .instance_size = sizeof(BDRVNVMeState),
1151
1152 .bdrv_parse_filename = nvme_parse_filename,
1153 .bdrv_file_open = nvme_file_open,
1154 .bdrv_close = nvme_close,
1155 .bdrv_getlength = nvme_getlength,
1156
1157 .bdrv_co_preadv = nvme_co_preadv,
1158 .bdrv_co_pwritev = nvme_co_pwritev,
1159 .bdrv_co_flush_to_disk = nvme_co_flush,
1160 .bdrv_reopen_prepare = nvme_reopen_prepare,
1161
bdd6a90a
FZ
1162 .bdrv_refresh_filename = nvme_refresh_filename,
1163 .bdrv_refresh_limits = nvme_refresh_limits,
2654267c 1164 .strong_runtime_opts = nvme_strong_runtime_opts,
bdd6a90a
FZ
1165
1166 .bdrv_detach_aio_context = nvme_detach_aio_context,
1167 .bdrv_attach_aio_context = nvme_attach_aio_context,
1168
1169 .bdrv_io_plug = nvme_aio_plug,
1170 .bdrv_io_unplug = nvme_aio_unplug,
9ed61612
FZ
1171
1172 .bdrv_register_buf = nvme_register_buf,
1173 .bdrv_unregister_buf = nvme_unregister_buf,
bdd6a90a
FZ
1174};
1175
1176static void bdrv_nvme_init(void)
1177{
1178 bdrv_register(&bdrv_nvme);
1179}
1180
1181block_init(bdrv_nvme_init);