]> git.proxmox.com Git - mirror_qemu.git/blame - block/nvme.c
block/nvme: Simplify nvme_create_queue_pair() arguments
[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"
db725815 20#include "qemu/main-loop.h"
0b8fa32f 21#include "qemu/module.h"
bdd6a90a 22#include "qemu/cutils.h"
922a01a0 23#include "qemu/option.h"
bdd6a90a
FZ
24#include "qemu/vfio-helpers.h"
25#include "block/block_int.h"
e4ec5ad4 26#include "sysemu/replay.h"
bdd6a90a
FZ
27#include "trace.h"
28
a3d9a352 29#include "block/nvme.h"
bdd6a90a
FZ
30
31#define NVME_SQ_ENTRY_BYTES 64
32#define NVME_CQ_ENTRY_BYTES 16
33#define NVME_QUEUE_SIZE 128
34#define NVME_BAR_SIZE 8192
35
1086e95d
SH
36/*
37 * We have to leave one slot empty as that is the full queue case where
38 * head == tail + 1.
39 */
40#define NVME_NUM_REQS (NVME_QUEUE_SIZE - 1)
41
b75fd5f5
SH
42typedef struct BDRVNVMeState BDRVNVMeState;
43
bdd6a90a
FZ
44typedef struct {
45 int32_t head, tail;
46 uint8_t *queue;
47 uint64_t iova;
48 /* Hardware MMIO register */
49 volatile uint32_t *doorbell;
50} NVMeQueue;
51
52typedef struct {
53 BlockCompletionFunc *cb;
54 void *opaque;
55 int cid;
56 void *prp_list_page;
57 uint64_t prp_list_iova;
1086e95d 58 int free_req_next; /* q->reqs[] index of next free req */
bdd6a90a
FZ
59} NVMeRequest;
60
61typedef struct {
bdd6a90a
FZ
62 QemuMutex lock;
63
b75fd5f5
SH
64 /* Read from I/O code path, initialized under BQL */
65 BDRVNVMeState *s;
66 int index;
67
bdd6a90a 68 /* Fields protected by BQL */
bdd6a90a
FZ
69 uint8_t *prp_list_pages;
70
71 /* Fields protected by @lock */
a5db74f3 72 CoQueue free_req_queue;
bdd6a90a
FZ
73 NVMeQueue sq, cq;
74 int cq_phase;
1086e95d
SH
75 int free_req_head;
76 NVMeRequest reqs[NVME_NUM_REQS];
bdd6a90a
FZ
77 int need_kick;
78 int inflight;
7838c67f
SH
79
80 /* Thread-safe, no lock necessary */
81 QEMUBH *completion_bh;
bdd6a90a
FZ
82} NVMeQueuePair;
83
84/* Memory mapped registers */
85typedef volatile struct {
86 uint64_t cap;
87 uint32_t vs;
88 uint32_t intms;
89 uint32_t intmc;
90 uint32_t cc;
91 uint32_t reserved0;
92 uint32_t csts;
93 uint32_t nssr;
94 uint32_t aqa;
95 uint64_t asq;
96 uint64_t acq;
97 uint32_t cmbloc;
98 uint32_t cmbsz;
99 uint8_t reserved1[0xec0];
100 uint8_t cmd_set_specfic[0x100];
101 uint32_t doorbells[];
83c68e14 102} NVMeRegs;
bdd6a90a
FZ
103
104QEMU_BUILD_BUG_ON(offsetof(NVMeRegs, doorbells) != 0x1000);
105
73159e52
PMD
106#define INDEX_ADMIN 0
107#define INDEX_IO(n) (1 + n)
108
b75fd5f5 109struct BDRVNVMeState {
bdd6a90a
FZ
110 AioContext *aio_context;
111 QEMUVFIOState *vfio;
112 NVMeRegs *regs;
113 /* The submission/completion queue pairs.
114 * [0]: admin queue.
115 * [1..]: io queues.
116 */
117 NVMeQueuePair **queues;
118 int nr_queues;
119 size_t page_size;
120 /* How many uint32_t elements does each doorbell entry take. */
121 size_t doorbell_scale;
122 bool write_cache_supported;
123 EventNotifier irq_notifier;
118d1b6a 124
bdd6a90a
FZ
125 uint64_t nsze; /* Namespace size reported by identify command */
126 int nsid; /* The namespace id to read/write data. */
1120407b 127 int blkshift;
118d1b6a 128
bdd6a90a 129 uint64_t max_transfer;
2f0d8947 130 bool plugged;
bdd6a90a 131
e0dd95e3 132 bool supports_write_zeroes;
e87a09d6 133 bool supports_discard;
e0dd95e3 134
bdd6a90a
FZ
135 CoMutex dma_map_lock;
136 CoQueue dma_flush_queue;
137
138 /* Total size of mapped qiov, accessed under dma_map_lock */
139 int dma_map_count;
cc61b074
HR
140
141 /* PCI address (required for nvme_refresh_filename()) */
142 char *device;
b75fd5f5 143};
bdd6a90a
FZ
144
145#define NVME_BLOCK_OPT_DEVICE "device"
146#define NVME_BLOCK_OPT_NAMESPACE "namespace"
147
7838c67f
SH
148static void nvme_process_completion_bh(void *opaque);
149
bdd6a90a
FZ
150static QemuOptsList runtime_opts = {
151 .name = "nvme",
152 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
153 .desc = {
154 {
155 .name = NVME_BLOCK_OPT_DEVICE,
156 .type = QEMU_OPT_STRING,
157 .help = "NVMe PCI device address",
158 },
159 {
160 .name = NVME_BLOCK_OPT_NAMESPACE,
161 .type = QEMU_OPT_NUMBER,
162 .help = "NVMe namespace",
163 },
164 { /* end of list */ }
165 },
166};
167
3a6d34d0 168static void nvme_init_queue(BDRVNVMeState *s, NVMeQueue *q,
bdd6a90a
FZ
169 int nentries, int entry_bytes, Error **errp)
170{
bdd6a90a
FZ
171 size_t bytes;
172 int r;
173
174 bytes = ROUND_UP(nentries * entry_bytes, s->page_size);
175 q->head = q->tail = 0;
38e1f818 176 q->queue = qemu_try_memalign(s->page_size, bytes);
bdd6a90a
FZ
177 if (!q->queue) {
178 error_setg(errp, "Cannot allocate queue");
179 return;
180 }
2ed84693 181 memset(q->queue, 0, bytes);
bdd6a90a
FZ
182 r = qemu_vfio_dma_map(s->vfio, q->queue, bytes, false, &q->iova);
183 if (r) {
184 error_setg(errp, "Cannot map queue");
185 }
186}
187
b75fd5f5 188static void nvme_free_queue_pair(NVMeQueuePair *q)
bdd6a90a 189{
7838c67f
SH
190 if (q->completion_bh) {
191 qemu_bh_delete(q->completion_bh);
192 }
bdd6a90a
FZ
193 qemu_vfree(q->prp_list_pages);
194 qemu_vfree(q->sq.queue);
195 qemu_vfree(q->cq.queue);
196 qemu_mutex_destroy(&q->lock);
197 g_free(q);
198}
199
200static void nvme_free_req_queue_cb(void *opaque)
201{
202 NVMeQueuePair *q = opaque;
203
204 qemu_mutex_lock(&q->lock);
205 while (qemu_co_enter_next(&q->free_req_queue, &q->lock)) {
206 /* Retry all pending requests */
207 }
208 qemu_mutex_unlock(&q->lock);
209}
210
0a28b02e
PMD
211static NVMeQueuePair *nvme_create_queue_pair(BDRVNVMeState *s,
212 AioContext *aio_context,
bdd6a90a
FZ
213 int idx, int size,
214 Error **errp)
215{
216 int i, r;
bdd6a90a 217 Error *local_err = NULL;
0ea45f76 218 NVMeQueuePair *q;
bdd6a90a
FZ
219 uint64_t prp_list_iova;
220
0ea45f76
PMD
221 q = g_try_new0(NVMeQueuePair, 1);
222 if (!q) {
223 return NULL;
224 }
38e1f818 225 q->prp_list_pages = qemu_try_memalign(s->page_size,
0ea45f76
PMD
226 s->page_size * NVME_NUM_REQS);
227 if (!q->prp_list_pages) {
228 goto fail;
229 }
2ed84693 230 memset(q->prp_list_pages, 0, s->page_size * NVME_NUM_REQS);
bdd6a90a 231 qemu_mutex_init(&q->lock);
b75fd5f5 232 q->s = s;
bdd6a90a
FZ
233 q->index = idx;
234 qemu_co_queue_init(&q->free_req_queue);
0a28b02e 235 q->completion_bh = aio_bh_new(aio_context, nvme_process_completion_bh, q);
bdd6a90a 236 r = qemu_vfio_dma_map(s->vfio, q->prp_list_pages,
1086e95d 237 s->page_size * NVME_NUM_REQS,
bdd6a90a
FZ
238 false, &prp_list_iova);
239 if (r) {
240 goto fail;
241 }
1086e95d
SH
242 q->free_req_head = -1;
243 for (i = 0; i < NVME_NUM_REQS; i++) {
bdd6a90a
FZ
244 NVMeRequest *req = &q->reqs[i];
245 req->cid = i + 1;
1086e95d
SH
246 req->free_req_next = q->free_req_head;
247 q->free_req_head = i;
bdd6a90a
FZ
248 req->prp_list_page = q->prp_list_pages + i * s->page_size;
249 req->prp_list_iova = prp_list_iova + i * s->page_size;
250 }
1086e95d 251
3a6d34d0 252 nvme_init_queue(s, &q->sq, size, NVME_SQ_ENTRY_BYTES, &local_err);
bdd6a90a
FZ
253 if (local_err) {
254 error_propagate(errp, local_err);
255 goto fail;
256 }
257 q->sq.doorbell = &s->regs->doorbells[idx * 2 * s->doorbell_scale];
258
3a6d34d0 259 nvme_init_queue(s, &q->cq, size, NVME_CQ_ENTRY_BYTES, &local_err);
bdd6a90a
FZ
260 if (local_err) {
261 error_propagate(errp, local_err);
262 goto fail;
263 }
461bba04 264 q->cq.doorbell = &s->regs->doorbells[(idx * 2 + 1) * s->doorbell_scale];
bdd6a90a
FZ
265
266 return q;
267fail:
b75fd5f5 268 nvme_free_queue_pair(q);
bdd6a90a
FZ
269 return NULL;
270}
271
272/* With q->lock */
b75fd5f5 273static void nvme_kick(NVMeQueuePair *q)
bdd6a90a 274{
b75fd5f5
SH
275 BDRVNVMeState *s = q->s;
276
bdd6a90a
FZ
277 if (s->plugged || !q->need_kick) {
278 return;
279 }
280 trace_nvme_kick(s, q->index);
281 assert(!(q->sq.tail & 0xFF00));
282 /* Fence the write to submission queue entry before notifying the device. */
283 smp_wmb();
284 *q->sq.doorbell = cpu_to_le32(q->sq.tail);
285 q->inflight += q->need_kick;
286 q->need_kick = 0;
287}
288
289/* Find a free request element if any, otherwise:
290 * a) if in coroutine context, try to wait for one to become available;
291 * b) if not in coroutine, return NULL;
292 */
293static NVMeRequest *nvme_get_free_req(NVMeQueuePair *q)
294{
1086e95d 295 NVMeRequest *req;
bdd6a90a
FZ
296
297 qemu_mutex_lock(&q->lock);
1086e95d
SH
298
299 while (q->free_req_head == -1) {
bdd6a90a
FZ
300 if (qemu_in_coroutine()) {
301 trace_nvme_free_req_queue_wait(q);
302 qemu_co_queue_wait(&q->free_req_queue, &q->lock);
303 } else {
304 qemu_mutex_unlock(&q->lock);
305 return NULL;
306 }
307 }
1086e95d
SH
308
309 req = &q->reqs[q->free_req_head];
310 q->free_req_head = req->free_req_next;
311 req->free_req_next = -1;
312
bdd6a90a
FZ
313 qemu_mutex_unlock(&q->lock);
314 return req;
315}
316
1086e95d
SH
317/* With q->lock */
318static void nvme_put_free_req_locked(NVMeQueuePair *q, NVMeRequest *req)
319{
320 req->free_req_next = q->free_req_head;
321 q->free_req_head = req - q->reqs;
322}
323
324/* With q->lock */
b75fd5f5 325static void nvme_wake_free_req_locked(NVMeQueuePair *q)
1086e95d
SH
326{
327 if (!qemu_co_queue_empty(&q->free_req_queue)) {
b75fd5f5 328 replay_bh_schedule_oneshot_event(q->s->aio_context,
1086e95d
SH
329 nvme_free_req_queue_cb, q);
330 }
331}
332
333/* Insert a request in the freelist and wake waiters */
b75fd5f5 334static void nvme_put_free_req_and_wake(NVMeQueuePair *q, NVMeRequest *req)
1086e95d
SH
335{
336 qemu_mutex_lock(&q->lock);
337 nvme_put_free_req_locked(q, req);
b75fd5f5 338 nvme_wake_free_req_locked(q);
1086e95d
SH
339 qemu_mutex_unlock(&q->lock);
340}
341
bdd6a90a
FZ
342static inline int nvme_translate_error(const NvmeCqe *c)
343{
344 uint16_t status = (le16_to_cpu(c->status) >> 1) & 0xFF;
345 if (status) {
346 trace_nvme_error(le32_to_cpu(c->result),
347 le16_to_cpu(c->sq_head),
348 le16_to_cpu(c->sq_id),
349 le16_to_cpu(c->cid),
350 le16_to_cpu(status));
351 }
352 switch (status) {
353 case 0:
354 return 0;
355 case 1:
356 return -ENOSYS;
357 case 2:
358 return -EINVAL;
359 default:
360 return -EIO;
361 }
362}
363
364/* With q->lock */
b75fd5f5 365static bool nvme_process_completion(NVMeQueuePair *q)
bdd6a90a 366{
b75fd5f5 367 BDRVNVMeState *s = q->s;
bdd6a90a
FZ
368 bool progress = false;
369 NVMeRequest *preq;
370 NVMeRequest req;
371 NvmeCqe *c;
372
373 trace_nvme_process_completion(s, q->index, q->inflight);
7838c67f
SH
374 if (s->plugged) {
375 trace_nvme_process_completion_queue_plugged(s, q->index);
bdd6a90a
FZ
376 return false;
377 }
7838c67f
SH
378
379 /*
380 * Support re-entrancy when a request cb() function invokes aio_poll().
381 * Pending completions must be visible to aio_poll() so that a cb()
382 * function can wait for the completion of another request.
383 *
384 * The aio_poll() loop will execute our BH and we'll resume completion
385 * processing there.
386 */
387 qemu_bh_schedule(q->completion_bh);
388
bdd6a90a
FZ
389 assert(q->inflight >= 0);
390 while (q->inflight) {
04b3fb39 391 int ret;
bdd6a90a 392 int16_t cid;
04b3fb39 393
bdd6a90a 394 c = (NvmeCqe *)&q->cq.queue[q->cq.head * NVME_CQ_ENTRY_BYTES];
258867d1 395 if ((le16_to_cpu(c->status) & 0x1) == q->cq_phase) {
bdd6a90a
FZ
396 break;
397 }
04b3fb39 398 ret = nvme_translate_error(c);
bdd6a90a
FZ
399 q->cq.head = (q->cq.head + 1) % NVME_QUEUE_SIZE;
400 if (!q->cq.head) {
401 q->cq_phase = !q->cq_phase;
402 }
403 cid = le16_to_cpu(c->cid);
404 if (cid == 0 || cid > NVME_QUEUE_SIZE) {
405 fprintf(stderr, "Unexpected CID in completion queue: %" PRIu32 "\n",
406 cid);
407 continue;
408 }
bdd6a90a
FZ
409 trace_nvme_complete_command(s, q->index, cid);
410 preq = &q->reqs[cid - 1];
411 req = *preq;
412 assert(req.cid == cid);
413 assert(req.cb);
1086e95d 414 nvme_put_free_req_locked(q, preq);
bdd6a90a 415 preq->cb = preq->opaque = NULL;
7838c67f 416 q->inflight--;
bdd6a90a 417 qemu_mutex_unlock(&q->lock);
04b3fb39 418 req.cb(req.opaque, ret);
bdd6a90a 419 qemu_mutex_lock(&q->lock);
bdd6a90a
FZ
420 progress = true;
421 }
422 if (progress) {
423 /* Notify the device so it can post more completions. */
424 smp_mb_release();
425 *q->cq.doorbell = cpu_to_le32(q->cq.head);
b75fd5f5 426 nvme_wake_free_req_locked(q);
bdd6a90a 427 }
7838c67f
SH
428
429 qemu_bh_cancel(q->completion_bh);
430
bdd6a90a
FZ
431 return progress;
432}
433
7838c67f
SH
434static void nvme_process_completion_bh(void *opaque)
435{
436 NVMeQueuePair *q = opaque;
437
438 /*
439 * We're being invoked because a nvme_process_completion() cb() function
440 * called aio_poll(). The callback may be waiting for further completions
441 * so notify the device that it has space to fill in more completions now.
442 */
443 smp_mb_release();
444 *q->cq.doorbell = cpu_to_le32(q->cq.head);
445 nvme_wake_free_req_locked(q);
446
447 nvme_process_completion(q);
448}
449
bdd6a90a
FZ
450static void nvme_trace_command(const NvmeCmd *cmd)
451{
452 int i;
453
e266f52c
PMD
454 if (!trace_event_get_state_backends(TRACE_NVME_SUBMIT_COMMAND_RAW)) {
455 return;
456 }
bdd6a90a
FZ
457 for (i = 0; i < 8; ++i) {
458 uint8_t *cmdp = (uint8_t *)cmd + i * 8;
459 trace_nvme_submit_command_raw(cmdp[0], cmdp[1], cmdp[2], cmdp[3],
460 cmdp[4], cmdp[5], cmdp[6], cmdp[7]);
461 }
462}
463
b75fd5f5 464static void nvme_submit_command(NVMeQueuePair *q, NVMeRequest *req,
bdd6a90a
FZ
465 NvmeCmd *cmd, BlockCompletionFunc cb,
466 void *opaque)
467{
468 assert(!req->cb);
469 req->cb = cb;
470 req->opaque = opaque;
471 cmd->cid = cpu_to_le32(req->cid);
472
b75fd5f5 473 trace_nvme_submit_command(q->s, q->index, req->cid);
bdd6a90a
FZ
474 nvme_trace_command(cmd);
475 qemu_mutex_lock(&q->lock);
476 memcpy((uint8_t *)q->sq.queue +
477 q->sq.tail * NVME_SQ_ENTRY_BYTES, cmd, sizeof(*cmd));
478 q->sq.tail = (q->sq.tail + 1) % NVME_QUEUE_SIZE;
479 q->need_kick++;
b75fd5f5
SH
480 nvme_kick(q);
481 nvme_process_completion(q);
bdd6a90a
FZ
482 qemu_mutex_unlock(&q->lock);
483}
484
485static void nvme_cmd_sync_cb(void *opaque, int ret)
486{
487 int *pret = opaque;
488 *pret = ret;
4720cbee 489 aio_wait_kick();
bdd6a90a
FZ
490}
491
492static int nvme_cmd_sync(BlockDriverState *bs, NVMeQueuePair *q,
493 NvmeCmd *cmd)
494{
073a0697 495 AioContext *aio_context = bdrv_get_aio_context(bs);
bdd6a90a 496 NVMeRequest *req;
bdd6a90a
FZ
497 int ret = -EINPROGRESS;
498 req = nvme_get_free_req(q);
499 if (!req) {
500 return -EBUSY;
501 }
b75fd5f5 502 nvme_submit_command(q, req, cmd, nvme_cmd_sync_cb, &ret);
bdd6a90a 503
073a0697 504 AIO_WAIT_WHILE(aio_context, ret == -EINPROGRESS);
bdd6a90a
FZ
505 return ret;
506}
507
508static void nvme_identify(BlockDriverState *bs, int namespace, Error **errp)
509{
510 BDRVNVMeState *s = bs->opaque;
7d3b214a
PMD
511 union {
512 NvmeIdCtrl ctrl;
513 NvmeIdNs ns;
514 } *id;
118d1b6a 515 NvmeLBAF *lbaf;
e0dd95e3 516 uint16_t oncs;
1120407b 517 int r;
bdd6a90a
FZ
518 uint64_t iova;
519 NvmeCmd cmd = {
520 .opcode = NVME_ADM_CMD_IDENTIFY,
521 .cdw10 = cpu_to_le32(0x1),
522 };
523
38e1f818 524 id = qemu_try_memalign(s->page_size, sizeof(*id));
4d980939 525 if (!id) {
bdd6a90a
FZ
526 error_setg(errp, "Cannot allocate buffer for identify response");
527 goto out;
528 }
7d3b214a 529 r = qemu_vfio_dma_map(s->vfio, id, sizeof(*id), true, &iova);
bdd6a90a
FZ
530 if (r) {
531 error_setg(errp, "Cannot map buffer for DMA");
532 goto out;
533 }
bdd6a90a 534
2ed84693
PMD
535 memset(id, 0, sizeof(*id));
536 cmd.dptr.prp1 = cpu_to_le64(iova);
73159e52 537 if (nvme_cmd_sync(bs, s->queues[INDEX_ADMIN], &cmd)) {
bdd6a90a
FZ
538 error_setg(errp, "Failed to identify controller");
539 goto out;
540 }
541
7d3b214a 542 if (le32_to_cpu(id->ctrl.nn) < namespace) {
bdd6a90a
FZ
543 error_setg(errp, "Invalid namespace");
544 goto out;
545 }
7d3b214a
PMD
546 s->write_cache_supported = le32_to_cpu(id->ctrl.vwc) & 0x1;
547 s->max_transfer = (id->ctrl.mdts ? 1 << id->ctrl.mdts : 0) * s->page_size;
bdd6a90a
FZ
548 /* For now the page list buffer per command is one page, to hold at most
549 * s->page_size / sizeof(uint64_t) entries. */
550 s->max_transfer = MIN_NON_ZERO(s->max_transfer,
551 s->page_size / sizeof(uint64_t) * s->page_size);
552
7d3b214a 553 oncs = le16_to_cpu(id->ctrl.oncs);
69265150 554 s->supports_write_zeroes = !!(oncs & NVME_ONCS_WRITE_ZEROES);
e87a09d6 555 s->supports_discard = !!(oncs & NVME_ONCS_DSM);
e0dd95e3 556
7d3b214a 557 memset(id, 0, sizeof(*id));
bdd6a90a
FZ
558 cmd.cdw10 = 0;
559 cmd.nsid = cpu_to_le32(namespace);
73159e52 560 if (nvme_cmd_sync(bs, s->queues[INDEX_ADMIN], &cmd)) {
bdd6a90a
FZ
561 error_setg(errp, "Failed to identify namespace");
562 goto out;
563 }
564
7d3b214a
PMD
565 s->nsze = le64_to_cpu(id->ns.nsze);
566 lbaf = &id->ns.lbaf[NVME_ID_NS_FLBAS_INDEX(id->ns.flbas)];
118d1b6a 567
7d3b214a
PMD
568 if (NVME_ID_NS_DLFEAT_WRITE_ZEROES(id->ns.dlfeat) &&
569 NVME_ID_NS_DLFEAT_READ_BEHAVIOR(id->ns.dlfeat) ==
e0dd95e3
ML
570 NVME_ID_NS_DLFEAT_READ_BEHAVIOR_ZEROES) {
571 bs->supported_write_flags |= BDRV_REQ_MAY_UNMAP;
572 }
573
118d1b6a
ML
574 if (lbaf->ms) {
575 error_setg(errp, "Namespaces with metadata are not yet supported");
576 goto out;
577 }
578
1120407b
HR
579 if (lbaf->ds < BDRV_SECTOR_BITS || lbaf->ds > 12 ||
580 (1 << lbaf->ds) > s->page_size)
581 {
582 error_setg(errp, "Namespace has unsupported block size (2^%d)",
583 lbaf->ds);
118d1b6a
ML
584 goto out;
585 }
bdd6a90a 586
118d1b6a 587 s->blkshift = lbaf->ds;
bdd6a90a 588out:
4d980939
PMD
589 qemu_vfio_dma_unmap(s->vfio, id);
590 qemu_vfree(id);
bdd6a90a
FZ
591}
592
593static bool nvme_poll_queues(BDRVNVMeState *s)
594{
595 bool progress = false;
596 int i;
597
598 for (i = 0; i < s->nr_queues; i++) {
599 NVMeQueuePair *q = s->queues[i];
2446e0e2
SH
600 const size_t cqe_offset = q->cq.head * NVME_CQ_ENTRY_BYTES;
601 NvmeCqe *cqe = (NvmeCqe *)&q->cq.queue[cqe_offset];
602
603 /*
604 * Do an early check for completions. q->lock isn't needed because
605 * nvme_process_completion() only runs in the event loop thread and
606 * cannot race with itself.
607 */
608 if ((le16_to_cpu(cqe->status) & 0x1) == q->cq_phase) {
609 continue;
610 }
611
bdd6a90a 612 qemu_mutex_lock(&q->lock);
b75fd5f5 613 while (nvme_process_completion(q)) {
bdd6a90a
FZ
614 /* Keep polling */
615 progress = true;
616 }
617 qemu_mutex_unlock(&q->lock);
618 }
619 return progress;
620}
621
622static void nvme_handle_event(EventNotifier *n)
623{
624 BDRVNVMeState *s = container_of(n, BDRVNVMeState, irq_notifier);
625
626 trace_nvme_handle_event(s);
bdd6a90a
FZ
627 event_notifier_test_and_clear(n);
628 nvme_poll_queues(s);
bdd6a90a
FZ
629}
630
631static bool nvme_add_io_queue(BlockDriverState *bs, Error **errp)
632{
633 BDRVNVMeState *s = bs->opaque;
634 int n = s->nr_queues;
635 NVMeQueuePair *q;
636 NvmeCmd cmd;
637 int queue_size = NVME_QUEUE_SIZE;
638
0a28b02e
PMD
639 q = nvme_create_queue_pair(s, bdrv_get_aio_context(bs),
640 n, queue_size, errp);
bdd6a90a
FZ
641 if (!q) {
642 return false;
643 }
644 cmd = (NvmeCmd) {
645 .opcode = NVME_ADM_CMD_CREATE_CQ,
c26f2173 646 .dptr.prp1 = cpu_to_le64(q->cq.iova),
bdd6a90a
FZ
647 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | (n & 0xFFFF)),
648 .cdw11 = cpu_to_le32(0x3),
649 };
73159e52 650 if (nvme_cmd_sync(bs, s->queues[INDEX_ADMIN], &cmd)) {
bf6ce5ec 651 error_setg(errp, "Failed to create CQ io queue [%d]", n);
c8edbfb2 652 goto out_error;
bdd6a90a
FZ
653 }
654 cmd = (NvmeCmd) {
655 .opcode = NVME_ADM_CMD_CREATE_SQ,
c26f2173 656 .dptr.prp1 = cpu_to_le64(q->sq.iova),
bdd6a90a
FZ
657 .cdw10 = cpu_to_le32(((queue_size - 1) << 16) | (n & 0xFFFF)),
658 .cdw11 = cpu_to_le32(0x1 | (n << 16)),
659 };
73159e52 660 if (nvme_cmd_sync(bs, s->queues[INDEX_ADMIN], &cmd)) {
bf6ce5ec 661 error_setg(errp, "Failed to create SQ io queue [%d]", n);
c8edbfb2 662 goto out_error;
bdd6a90a
FZ
663 }
664 s->queues = g_renew(NVMeQueuePair *, s->queues, n + 1);
665 s->queues[n] = q;
666 s->nr_queues++;
667 return true;
c8edbfb2
PMD
668out_error:
669 nvme_free_queue_pair(q);
670 return false;
bdd6a90a
FZ
671}
672
673static bool nvme_poll_cb(void *opaque)
674{
675 EventNotifier *e = opaque;
676 BDRVNVMeState *s = container_of(e, BDRVNVMeState, irq_notifier);
bdd6a90a
FZ
677
678 trace_nvme_poll_cb(s);
b3ac2b94 679 return nvme_poll_queues(s);
bdd6a90a
FZ
680}
681
682static int nvme_init(BlockDriverState *bs, const char *device, int namespace,
683 Error **errp)
684{
685 BDRVNVMeState *s = bs->opaque;
0a28b02e 686 AioContext *aio_context = bdrv_get_aio_context(bs);
bdd6a90a
FZ
687 int ret;
688 uint64_t cap;
689 uint64_t timeout_ms;
690 uint64_t deadline, now;
691 Error *local_err = NULL;
692
693 qemu_co_mutex_init(&s->dma_map_lock);
694 qemu_co_queue_init(&s->dma_flush_queue);
cc61b074 695 s->device = g_strdup(device);
bdd6a90a
FZ
696 s->nsid = namespace;
697 s->aio_context = bdrv_get_aio_context(bs);
698 ret = event_notifier_init(&s->irq_notifier, 0);
699 if (ret) {
700 error_setg(errp, "Failed to init event notifier");
701 return ret;
702 }
703
704 s->vfio = qemu_vfio_open_pci(device, errp);
705 if (!s->vfio) {
706 ret = -EINVAL;
9582f357 707 goto out;
bdd6a90a
FZ
708 }
709
710 s->regs = qemu_vfio_pci_map_bar(s->vfio, 0, 0, NVME_BAR_SIZE, errp);
711 if (!s->regs) {
712 ret = -EINVAL;
9582f357 713 goto out;
bdd6a90a
FZ
714 }
715
716 /* Perform initialize sequence as described in NVMe spec "7.6.1
717 * Initialization". */
718
719 cap = le64_to_cpu(s->regs->cap);
720 if (!(cap & (1ULL << 37))) {
721 error_setg(errp, "Device doesn't support NVMe command set");
722 ret = -EINVAL;
9582f357 723 goto out;
bdd6a90a
FZ
724 }
725
726 s->page_size = MAX(4096, 1 << (12 + ((cap >> 48) & 0xF)));
727 s->doorbell_scale = (4 << (((cap >> 32) & 0xF))) / sizeof(uint32_t);
728 bs->bl.opt_mem_alignment = s->page_size;
729 timeout_ms = MIN(500 * ((cap >> 24) & 0xFF), 30000);
730
731 /* Reset device to get a clean state. */
732 s->regs->cc = cpu_to_le32(le32_to_cpu(s->regs->cc) & 0xFE);
733 /* Wait for CSTS.RDY = 0. */
e4f310fe 734 deadline = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + timeout_ms * SCALE_MS;
bdd6a90a
FZ
735 while (le32_to_cpu(s->regs->csts) & 0x1) {
736 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
737 error_setg(errp, "Timeout while waiting for device to reset (%"
738 PRId64 " ms)",
739 timeout_ms);
740 ret = -ETIMEDOUT;
9582f357 741 goto out;
bdd6a90a
FZ
742 }
743 }
744
745 /* Set up admin queue. */
746 s->queues = g_new(NVMeQueuePair *, 1);
0a28b02e 747 s->queues[INDEX_ADMIN] = nvme_create_queue_pair(s, aio_context, 0,
73159e52
PMD
748 NVME_QUEUE_SIZE,
749 errp);
750 if (!s->queues[INDEX_ADMIN]) {
bdd6a90a 751 ret = -EINVAL;
9582f357 752 goto out;
bdd6a90a 753 }
95667c3b 754 s->nr_queues = 1;
bdd6a90a
FZ
755 QEMU_BUILD_BUG_ON(NVME_QUEUE_SIZE & 0xF000);
756 s->regs->aqa = cpu_to_le32((NVME_QUEUE_SIZE << 16) | NVME_QUEUE_SIZE);
73159e52
PMD
757 s->regs->asq = cpu_to_le64(s->queues[INDEX_ADMIN]->sq.iova);
758 s->regs->acq = cpu_to_le64(s->queues[INDEX_ADMIN]->cq.iova);
bdd6a90a
FZ
759
760 /* After setting up all control registers we can enable device now. */
761 s->regs->cc = cpu_to_le32((ctz32(NVME_CQ_ENTRY_BYTES) << 20) |
762 (ctz32(NVME_SQ_ENTRY_BYTES) << 16) |
763 0x1);
764 /* Wait for CSTS.RDY = 1. */
765 now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
766 deadline = now + timeout_ms * 1000000;
767 while (!(le32_to_cpu(s->regs->csts) & 0x1)) {
768 if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) > deadline) {
769 error_setg(errp, "Timeout while waiting for device to start (%"
770 PRId64 " ms)",
771 timeout_ms);
772 ret = -ETIMEDOUT;
9582f357 773 goto out;
bdd6a90a
FZ
774 }
775 }
776
777 ret = qemu_vfio_pci_init_irq(s->vfio, &s->irq_notifier,
778 VFIO_PCI_MSIX_IRQ_INDEX, errp);
779 if (ret) {
9582f357 780 goto out;
bdd6a90a
FZ
781 }
782 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
783 false, nvme_handle_event, nvme_poll_cb);
784
78d8c99e 785 nvme_identify(bs, namespace, &local_err);
bdd6a90a
FZ
786 if (local_err) {
787 error_propagate(errp, local_err);
788 ret = -EIO;
9582f357 789 goto out;
bdd6a90a
FZ
790 }
791
792 /* Set up command queues. */
793 if (!nvme_add_io_queue(bs, errp)) {
794 ret = -EIO;
bdd6a90a 795 }
9582f357
FZ
796out:
797 /* Cleaning up is done in nvme_file_open() upon error. */
bdd6a90a
FZ
798 return ret;
799}
800
801/* Parse a filename in the format of nvme://XXXX:XX:XX.X/X. Example:
802 *
803 * nvme://0000:44:00.0/1
804 *
805 * where the "nvme://" is a fixed form of the protocol prefix, the middle part
806 * is the PCI address, and the last part is the namespace number starting from
807 * 1 according to the NVMe spec. */
808static void nvme_parse_filename(const char *filename, QDict *options,
809 Error **errp)
810{
811 int pref = strlen("nvme://");
812
813 if (strlen(filename) > pref && !strncmp(filename, "nvme://", pref)) {
814 const char *tmp = filename + pref;
815 char *device;
816 const char *namespace;
817 unsigned long ns;
818 const char *slash = strchr(tmp, '/');
819 if (!slash) {
625eaca9 820 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, tmp);
bdd6a90a
FZ
821 return;
822 }
823 device = g_strndup(tmp, slash - tmp);
625eaca9 824 qdict_put_str(options, NVME_BLOCK_OPT_DEVICE, device);
bdd6a90a
FZ
825 g_free(device);
826 namespace = slash + 1;
827 if (*namespace && qemu_strtoul(namespace, NULL, 10, &ns)) {
828 error_setg(errp, "Invalid namespace '%s', positive number expected",
829 namespace);
830 return;
831 }
625eaca9
LV
832 qdict_put_str(options, NVME_BLOCK_OPT_NAMESPACE,
833 *namespace ? namespace : "1");
bdd6a90a
FZ
834 }
835}
836
837static int nvme_enable_disable_write_cache(BlockDriverState *bs, bool enable,
838 Error **errp)
839{
840 int ret;
841 BDRVNVMeState *s = bs->opaque;
842 NvmeCmd cmd = {
843 .opcode = NVME_ADM_CMD_SET_FEATURES,
844 .nsid = cpu_to_le32(s->nsid),
845 .cdw10 = cpu_to_le32(0x06),
846 .cdw11 = cpu_to_le32(enable ? 0x01 : 0x00),
847 };
848
73159e52 849 ret = nvme_cmd_sync(bs, s->queues[INDEX_ADMIN], &cmd);
bdd6a90a
FZ
850 if (ret) {
851 error_setg(errp, "Failed to configure NVMe write cache");
852 }
853 return ret;
854}
855
856static void nvme_close(BlockDriverState *bs)
857{
858 int i;
859 BDRVNVMeState *s = bs->opaque;
860
861 for (i = 0; i < s->nr_queues; ++i) {
b75fd5f5 862 nvme_free_queue_pair(s->queues[i]);
bdd6a90a 863 }
9582f357 864 g_free(s->queues);
bdd6a90a
FZ
865 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
866 false, NULL, NULL);
9582f357 867 event_notifier_cleanup(&s->irq_notifier);
bdd6a90a
FZ
868 qemu_vfio_pci_unmap_bar(s->vfio, 0, (void *)s->regs, 0, NVME_BAR_SIZE);
869 qemu_vfio_close(s->vfio);
cc61b074
HR
870
871 g_free(s->device);
bdd6a90a
FZ
872}
873
874static int nvme_file_open(BlockDriverState *bs, QDict *options, int flags,
875 Error **errp)
876{
877 const char *device;
878 QemuOpts *opts;
879 int namespace;
880 int ret;
881 BDRVNVMeState *s = bs->opaque;
882
e0dd95e3
ML
883 bs->supported_write_flags = BDRV_REQ_FUA;
884
bdd6a90a
FZ
885 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
886 qemu_opts_absorb_qdict(opts, options, &error_abort);
887 device = qemu_opt_get(opts, NVME_BLOCK_OPT_DEVICE);
888 if (!device) {
889 error_setg(errp, "'" NVME_BLOCK_OPT_DEVICE "' option is required");
890 qemu_opts_del(opts);
891 return -EINVAL;
892 }
893
894 namespace = qemu_opt_get_number(opts, NVME_BLOCK_OPT_NAMESPACE, 1);
895 ret = nvme_init(bs, device, namespace, errp);
896 qemu_opts_del(opts);
897 if (ret) {
898 goto fail;
899 }
900 if (flags & BDRV_O_NOCACHE) {
901 if (!s->write_cache_supported) {
902 error_setg(errp,
903 "NVMe controller doesn't support write cache configuration");
904 ret = -EINVAL;
905 } else {
906 ret = nvme_enable_disable_write_cache(bs, !(flags & BDRV_O_NOCACHE),
907 errp);
908 }
909 if (ret) {
910 goto fail;
911 }
912 }
bdd6a90a
FZ
913 return 0;
914fail:
915 nvme_close(bs);
916 return ret;
917}
918
919static int64_t nvme_getlength(BlockDriverState *bs)
920{
921 BDRVNVMeState *s = bs->opaque;
118d1b6a
ML
922 return s->nsze << s->blkshift;
923}
bdd6a90a 924
1120407b 925static uint32_t nvme_get_blocksize(BlockDriverState *bs)
118d1b6a
ML
926{
927 BDRVNVMeState *s = bs->opaque;
1120407b
HR
928 assert(s->blkshift >= BDRV_SECTOR_BITS && s->blkshift <= 12);
929 return UINT32_C(1) << s->blkshift;
118d1b6a
ML
930}
931
932static int nvme_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
933{
1120407b 934 uint32_t blocksize = nvme_get_blocksize(bs);
118d1b6a
ML
935 bsz->phys = blocksize;
936 bsz->log = blocksize;
937 return 0;
bdd6a90a
FZ
938}
939
940/* Called with s->dma_map_lock */
941static coroutine_fn int nvme_cmd_unmap_qiov(BlockDriverState *bs,
942 QEMUIOVector *qiov)
943{
944 int r = 0;
945 BDRVNVMeState *s = bs->opaque;
946
947 s->dma_map_count -= qiov->size;
948 if (!s->dma_map_count && !qemu_co_queue_empty(&s->dma_flush_queue)) {
949 r = qemu_vfio_dma_reset_temporary(s->vfio);
950 if (!r) {
951 qemu_co_queue_restart_all(&s->dma_flush_queue);
952 }
953 }
954 return r;
955}
956
957/* Called with s->dma_map_lock */
958static coroutine_fn int nvme_cmd_map_qiov(BlockDriverState *bs, NvmeCmd *cmd,
959 NVMeRequest *req, QEMUIOVector *qiov)
960{
961 BDRVNVMeState *s = bs->opaque;
962 uint64_t *pagelist = req->prp_list_page;
963 int i, j, r;
964 int entries = 0;
965
966 assert(qiov->size);
967 assert(QEMU_IS_ALIGNED(qiov->size, s->page_size));
968 assert(qiov->size / s->page_size <= s->page_size / sizeof(uint64_t));
969 for (i = 0; i < qiov->niov; ++i) {
970 bool retry = true;
971 uint64_t iova;
972try_map:
973 r = qemu_vfio_dma_map(s->vfio,
974 qiov->iov[i].iov_base,
975 qiov->iov[i].iov_len,
976 true, &iova);
977 if (r == -ENOMEM && retry) {
978 retry = false;
979 trace_nvme_dma_flush_queue_wait(s);
980 if (s->dma_map_count) {
981 trace_nvme_dma_map_flush(s);
982 qemu_co_queue_wait(&s->dma_flush_queue, &s->dma_map_lock);
983 } else {
984 r = qemu_vfio_dma_reset_temporary(s->vfio);
985 if (r) {
986 goto fail;
987 }
988 }
989 goto try_map;
990 }
991 if (r) {
992 goto fail;
993 }
994
995 for (j = 0; j < qiov->iov[i].iov_len / s->page_size; j++) {
2916405a 996 pagelist[entries++] = cpu_to_le64(iova + j * s->page_size);
bdd6a90a
FZ
997 }
998 trace_nvme_cmd_map_qiov_iov(s, i, qiov->iov[i].iov_base,
999 qiov->iov[i].iov_len / s->page_size);
1000 }
1001
1002 s->dma_map_count += qiov->size;
1003
1004 assert(entries <= s->page_size / sizeof(uint64_t));
1005 switch (entries) {
1006 case 0:
1007 abort();
1008 case 1:
c26f2173
KJ
1009 cmd->dptr.prp1 = pagelist[0];
1010 cmd->dptr.prp2 = 0;
bdd6a90a
FZ
1011 break;
1012 case 2:
c26f2173
KJ
1013 cmd->dptr.prp1 = pagelist[0];
1014 cmd->dptr.prp2 = pagelist[1];
bdd6a90a
FZ
1015 break;
1016 default:
c26f2173
KJ
1017 cmd->dptr.prp1 = pagelist[0];
1018 cmd->dptr.prp2 = cpu_to_le64(req->prp_list_iova + sizeof(uint64_t));
bdd6a90a
FZ
1019 break;
1020 }
1021 trace_nvme_cmd_map_qiov(s, cmd, req, qiov, entries);
1022 for (i = 0; i < entries; ++i) {
1023 trace_nvme_cmd_map_qiov_pages(s, i, pagelist[i]);
1024 }
1025 return 0;
1026fail:
1027 /* No need to unmap [0 - i) iovs even if we've failed, since we don't
1028 * increment s->dma_map_count. This is okay for fixed mapping memory areas
1029 * because they are already mapped before calling this function; for
1030 * temporary mappings, a later nvme_cmd_(un)map_qiov will reclaim by
1031 * calling qemu_vfio_dma_reset_temporary when necessary. */
1032 return r;
1033}
1034
1035typedef struct {
1036 Coroutine *co;
1037 int ret;
1038 AioContext *ctx;
1039} NVMeCoData;
1040
1041static void nvme_rw_cb_bh(void *opaque)
1042{
1043 NVMeCoData *data = opaque;
1044 qemu_coroutine_enter(data->co);
1045}
1046
1047static void nvme_rw_cb(void *opaque, int ret)
1048{
1049 NVMeCoData *data = opaque;
1050 data->ret = ret;
1051 if (!data->co) {
1052 /* The rw coroutine hasn't yielded, don't try to enter. */
1053 return;
1054 }
e4ec5ad4 1055 replay_bh_schedule_oneshot_event(data->ctx, nvme_rw_cb_bh, data);
bdd6a90a
FZ
1056}
1057
1058static coroutine_fn int nvme_co_prw_aligned(BlockDriverState *bs,
1059 uint64_t offset, uint64_t bytes,
1060 QEMUIOVector *qiov,
1061 bool is_write,
1062 int flags)
1063{
1064 int r;
1065 BDRVNVMeState *s = bs->opaque;
73159e52 1066 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
bdd6a90a 1067 NVMeRequest *req;
118d1b6a
ML
1068
1069 uint32_t cdw12 = (((bytes >> s->blkshift) - 1) & 0xFFFF) |
bdd6a90a
FZ
1070 (flags & BDRV_REQ_FUA ? 1 << 30 : 0);
1071 NvmeCmd cmd = {
1072 .opcode = is_write ? NVME_CMD_WRITE : NVME_CMD_READ,
1073 .nsid = cpu_to_le32(s->nsid),
118d1b6a
ML
1074 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1075 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
bdd6a90a
FZ
1076 .cdw12 = cpu_to_le32(cdw12),
1077 };
1078 NVMeCoData data = {
1079 .ctx = bdrv_get_aio_context(bs),
1080 .ret = -EINPROGRESS,
1081 };
1082
1083 trace_nvme_prw_aligned(s, is_write, offset, bytes, flags, qiov->niov);
1084 assert(s->nr_queues > 1);
1085 req = nvme_get_free_req(ioq);
1086 assert(req);
1087
1088 qemu_co_mutex_lock(&s->dma_map_lock);
1089 r = nvme_cmd_map_qiov(bs, &cmd, req, qiov);
1090 qemu_co_mutex_unlock(&s->dma_map_lock);
1091 if (r) {
b75fd5f5 1092 nvme_put_free_req_and_wake(ioq, req);
bdd6a90a
FZ
1093 return r;
1094 }
b75fd5f5 1095 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
bdd6a90a
FZ
1096
1097 data.co = qemu_coroutine_self();
1098 while (data.ret == -EINPROGRESS) {
1099 qemu_coroutine_yield();
1100 }
1101
1102 qemu_co_mutex_lock(&s->dma_map_lock);
1103 r = nvme_cmd_unmap_qiov(bs, qiov);
1104 qemu_co_mutex_unlock(&s->dma_map_lock);
1105 if (r) {
1106 return r;
1107 }
1108
1109 trace_nvme_rw_done(s, is_write, offset, bytes, data.ret);
1110 return data.ret;
1111}
1112
1113static inline bool nvme_qiov_aligned(BlockDriverState *bs,
1114 const QEMUIOVector *qiov)
1115{
1116 int i;
1117 BDRVNVMeState *s = bs->opaque;
1118
1119 for (i = 0; i < qiov->niov; ++i) {
1120 if (!QEMU_PTR_IS_ALIGNED(qiov->iov[i].iov_base, s->page_size) ||
1121 !QEMU_IS_ALIGNED(qiov->iov[i].iov_len, s->page_size)) {
1122 trace_nvme_qiov_unaligned(qiov, i, qiov->iov[i].iov_base,
1123 qiov->iov[i].iov_len, s->page_size);
1124 return false;
1125 }
1126 }
1127 return true;
1128}
1129
1130static int nvme_co_prw(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
1131 QEMUIOVector *qiov, bool is_write, int flags)
1132{
1133 BDRVNVMeState *s = bs->opaque;
1134 int r;
1135 uint8_t *buf = NULL;
1136 QEMUIOVector local_qiov;
1137
1138 assert(QEMU_IS_ALIGNED(offset, s->page_size));
1139 assert(QEMU_IS_ALIGNED(bytes, s->page_size));
1140 assert(bytes <= s->max_transfer);
1141 if (nvme_qiov_aligned(bs, qiov)) {
1142 return nvme_co_prw_aligned(bs, offset, bytes, qiov, is_write, flags);
1143 }
1144 trace_nvme_prw_buffered(s, offset, bytes, qiov->niov, is_write);
38e1f818 1145 buf = qemu_try_memalign(s->page_size, bytes);
bdd6a90a
FZ
1146
1147 if (!buf) {
1148 return -ENOMEM;
1149 }
1150 qemu_iovec_init(&local_qiov, 1);
1151 if (is_write) {
1152 qemu_iovec_to_buf(qiov, 0, buf, bytes);
1153 }
1154 qemu_iovec_add(&local_qiov, buf, bytes);
1155 r = nvme_co_prw_aligned(bs, offset, bytes, &local_qiov, is_write, flags);
1156 qemu_iovec_destroy(&local_qiov);
1157 if (!r && !is_write) {
1158 qemu_iovec_from_buf(qiov, 0, buf, bytes);
1159 }
1160 qemu_vfree(buf);
1161 return r;
1162}
1163
1164static coroutine_fn int nvme_co_preadv(BlockDriverState *bs,
1165 uint64_t offset, uint64_t bytes,
1166 QEMUIOVector *qiov, int flags)
1167{
1168 return nvme_co_prw(bs, offset, bytes, qiov, false, flags);
1169}
1170
1171static coroutine_fn int nvme_co_pwritev(BlockDriverState *bs,
1172 uint64_t offset, uint64_t bytes,
1173 QEMUIOVector *qiov, int flags)
1174{
1175 return nvme_co_prw(bs, offset, bytes, qiov, true, flags);
1176}
1177
1178static coroutine_fn int nvme_co_flush(BlockDriverState *bs)
1179{
1180 BDRVNVMeState *s = bs->opaque;
73159e52 1181 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
bdd6a90a
FZ
1182 NVMeRequest *req;
1183 NvmeCmd cmd = {
1184 .opcode = NVME_CMD_FLUSH,
1185 .nsid = cpu_to_le32(s->nsid),
1186 };
1187 NVMeCoData data = {
1188 .ctx = bdrv_get_aio_context(bs),
1189 .ret = -EINPROGRESS,
1190 };
1191
1192 assert(s->nr_queues > 1);
1193 req = nvme_get_free_req(ioq);
1194 assert(req);
b75fd5f5 1195 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
bdd6a90a
FZ
1196
1197 data.co = qemu_coroutine_self();
1198 if (data.ret == -EINPROGRESS) {
1199 qemu_coroutine_yield();
1200 }
1201
1202 return data.ret;
1203}
1204
1205
e0dd95e3
ML
1206static coroutine_fn int nvme_co_pwrite_zeroes(BlockDriverState *bs,
1207 int64_t offset,
1208 int bytes,
1209 BdrvRequestFlags flags)
1210{
1211 BDRVNVMeState *s = bs->opaque;
73159e52 1212 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
e0dd95e3
ML
1213 NVMeRequest *req;
1214
1215 uint32_t cdw12 = ((bytes >> s->blkshift) - 1) & 0xFFFF;
1216
1217 if (!s->supports_write_zeroes) {
1218 return -ENOTSUP;
1219 }
1220
1221 NvmeCmd cmd = {
69265150 1222 .opcode = NVME_CMD_WRITE_ZEROES,
e0dd95e3
ML
1223 .nsid = cpu_to_le32(s->nsid),
1224 .cdw10 = cpu_to_le32((offset >> s->blkshift) & 0xFFFFFFFF),
1225 .cdw11 = cpu_to_le32(((offset >> s->blkshift) >> 32) & 0xFFFFFFFF),
1226 };
1227
1228 NVMeCoData data = {
1229 .ctx = bdrv_get_aio_context(bs),
1230 .ret = -EINPROGRESS,
1231 };
1232
1233 if (flags & BDRV_REQ_MAY_UNMAP) {
1234 cdw12 |= (1 << 25);
1235 }
1236
1237 if (flags & BDRV_REQ_FUA) {
1238 cdw12 |= (1 << 30);
1239 }
1240
1241 cmd.cdw12 = cpu_to_le32(cdw12);
1242
1243 trace_nvme_write_zeroes(s, offset, bytes, flags);
1244 assert(s->nr_queues > 1);
1245 req = nvme_get_free_req(ioq);
1246 assert(req);
1247
b75fd5f5 1248 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
e0dd95e3
ML
1249
1250 data.co = qemu_coroutine_self();
1251 while (data.ret == -EINPROGRESS) {
1252 qemu_coroutine_yield();
1253 }
1254
1255 trace_nvme_rw_done(s, true, offset, bytes, data.ret);
1256 return data.ret;
1257}
1258
1259
e87a09d6
ML
1260static int coroutine_fn nvme_co_pdiscard(BlockDriverState *bs,
1261 int64_t offset,
1262 int bytes)
1263{
1264 BDRVNVMeState *s = bs->opaque;
73159e52 1265 NVMeQueuePair *ioq = s->queues[INDEX_IO(0)];
e87a09d6
ML
1266 NVMeRequest *req;
1267 NvmeDsmRange *buf;
1268 QEMUIOVector local_qiov;
1269 int ret;
1270
1271 NvmeCmd cmd = {
1272 .opcode = NVME_CMD_DSM,
1273 .nsid = cpu_to_le32(s->nsid),
1274 .cdw10 = cpu_to_le32(0), /*number of ranges - 0 based*/
1275 .cdw11 = cpu_to_le32(1 << 2), /*deallocate bit*/
1276 };
1277
1278 NVMeCoData data = {
1279 .ctx = bdrv_get_aio_context(bs),
1280 .ret = -EINPROGRESS,
1281 };
1282
1283 if (!s->supports_discard) {
1284 return -ENOTSUP;
1285 }
1286
1287 assert(s->nr_queues > 1);
1288
38e1f818 1289 buf = qemu_try_memalign(s->page_size, s->page_size);
e87a09d6
ML
1290 if (!buf) {
1291 return -ENOMEM;
1292 }
2ed84693 1293 memset(buf, 0, s->page_size);
e87a09d6
ML
1294 buf->nlb = cpu_to_le32(bytes >> s->blkshift);
1295 buf->slba = cpu_to_le64(offset >> s->blkshift);
1296 buf->cattr = 0;
1297
1298 qemu_iovec_init(&local_qiov, 1);
1299 qemu_iovec_add(&local_qiov, buf, 4096);
1300
1301 req = nvme_get_free_req(ioq);
1302 assert(req);
1303
1304 qemu_co_mutex_lock(&s->dma_map_lock);
1305 ret = nvme_cmd_map_qiov(bs, &cmd, req, &local_qiov);
1306 qemu_co_mutex_unlock(&s->dma_map_lock);
1307
1308 if (ret) {
b75fd5f5 1309 nvme_put_free_req_and_wake(ioq, req);
e87a09d6
ML
1310 goto out;
1311 }
1312
1313 trace_nvme_dsm(s, offset, bytes);
1314
b75fd5f5 1315 nvme_submit_command(ioq, req, &cmd, nvme_rw_cb, &data);
e87a09d6
ML
1316
1317 data.co = qemu_coroutine_self();
1318 while (data.ret == -EINPROGRESS) {
1319 qemu_coroutine_yield();
1320 }
1321
1322 qemu_co_mutex_lock(&s->dma_map_lock);
1323 ret = nvme_cmd_unmap_qiov(bs, &local_qiov);
1324 qemu_co_mutex_unlock(&s->dma_map_lock);
1325
1326 if (ret) {
1327 goto out;
1328 }
1329
1330 ret = data.ret;
1331 trace_nvme_dsm_done(s, offset, bytes, ret);
1332out:
1333 qemu_iovec_destroy(&local_qiov);
1334 qemu_vfree(buf);
1335 return ret;
1336
1337}
1338
1339
bdd6a90a
FZ
1340static int nvme_reopen_prepare(BDRVReopenState *reopen_state,
1341 BlockReopenQueue *queue, Error **errp)
1342{
1343 return 0;
1344}
1345
998b3a1e 1346static void nvme_refresh_filename(BlockDriverState *bs)
bdd6a90a 1347{
cc61b074 1348 BDRVNVMeState *s = bs->opaque;
bdd6a90a 1349
cc61b074
HR
1350 snprintf(bs->exact_filename, sizeof(bs->exact_filename), "nvme://%s/%i",
1351 s->device, s->nsid);
bdd6a90a
FZ
1352}
1353
1354static void nvme_refresh_limits(BlockDriverState *bs, Error **errp)
1355{
1356 BDRVNVMeState *s = bs->opaque;
1357
1358 bs->bl.opt_mem_alignment = s->page_size;
1359 bs->bl.request_alignment = s->page_size;
1360 bs->bl.max_transfer = s->max_transfer;
1361}
1362
1363static void nvme_detach_aio_context(BlockDriverState *bs)
1364{
1365 BDRVNVMeState *s = bs->opaque;
1366
7838c67f
SH
1367 for (int i = 0; i < s->nr_queues; i++) {
1368 NVMeQueuePair *q = s->queues[i];
1369
1370 qemu_bh_delete(q->completion_bh);
1371 q->completion_bh = NULL;
1372 }
1373
bdd6a90a
FZ
1374 aio_set_event_notifier(bdrv_get_aio_context(bs), &s->irq_notifier,
1375 false, NULL, NULL);
1376}
1377
1378static void nvme_attach_aio_context(BlockDriverState *bs,
1379 AioContext *new_context)
1380{
1381 BDRVNVMeState *s = bs->opaque;
1382
1383 s->aio_context = new_context;
1384 aio_set_event_notifier(new_context, &s->irq_notifier,
1385 false, nvme_handle_event, nvme_poll_cb);
7838c67f
SH
1386
1387 for (int i = 0; i < s->nr_queues; i++) {
1388 NVMeQueuePair *q = s->queues[i];
1389
1390 q->completion_bh =
1391 aio_bh_new(new_context, nvme_process_completion_bh, q);
1392 }
bdd6a90a
FZ
1393}
1394
1395static void nvme_aio_plug(BlockDriverState *bs)
1396{
1397 BDRVNVMeState *s = bs->opaque;
2f0d8947
PB
1398 assert(!s->plugged);
1399 s->plugged = true;
bdd6a90a
FZ
1400}
1401
1402static void nvme_aio_unplug(BlockDriverState *bs)
1403{
1404 int i;
1405 BDRVNVMeState *s = bs->opaque;
1406 assert(s->plugged);
2f0d8947 1407 s->plugged = false;
73159e52 1408 for (i = INDEX_IO(0); i < s->nr_queues; i++) {
2f0d8947
PB
1409 NVMeQueuePair *q = s->queues[i];
1410 qemu_mutex_lock(&q->lock);
b75fd5f5
SH
1411 nvme_kick(q);
1412 nvme_process_completion(q);
2f0d8947 1413 qemu_mutex_unlock(&q->lock);
bdd6a90a
FZ
1414 }
1415}
1416
9ed61612
FZ
1417static void nvme_register_buf(BlockDriverState *bs, void *host, size_t size)
1418{
1419 int ret;
1420 BDRVNVMeState *s = bs->opaque;
1421
1422 ret = qemu_vfio_dma_map(s->vfio, host, size, false, NULL);
1423 if (ret) {
1424 /* FIXME: we may run out of IOVA addresses after repeated
1425 * bdrv_register_buf/bdrv_unregister_buf, because nvme_vfio_dma_unmap
1426 * doesn't reclaim addresses for fixed mappings. */
1427 error_report("nvme_register_buf failed: %s", strerror(-ret));
1428 }
1429}
1430
1431static void nvme_unregister_buf(BlockDriverState *bs, void *host)
1432{
1433 BDRVNVMeState *s = bs->opaque;
1434
1435 qemu_vfio_dma_unmap(s->vfio, host);
1436}
1437
2654267c
HR
1438static const char *const nvme_strong_runtime_opts[] = {
1439 NVME_BLOCK_OPT_DEVICE,
1440 NVME_BLOCK_OPT_NAMESPACE,
1441
1442 NULL
1443};
1444
bdd6a90a
FZ
1445static BlockDriver bdrv_nvme = {
1446 .format_name = "nvme",
1447 .protocol_name = "nvme",
1448 .instance_size = sizeof(BDRVNVMeState),
1449
5a5e7f8c
ML
1450 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
1451 .create_opts = &bdrv_create_opts_simple,
1452
bdd6a90a
FZ
1453 .bdrv_parse_filename = nvme_parse_filename,
1454 .bdrv_file_open = nvme_file_open,
1455 .bdrv_close = nvme_close,
1456 .bdrv_getlength = nvme_getlength,
118d1b6a 1457 .bdrv_probe_blocksizes = nvme_probe_blocksizes,
bdd6a90a
FZ
1458
1459 .bdrv_co_preadv = nvme_co_preadv,
1460 .bdrv_co_pwritev = nvme_co_pwritev,
e0dd95e3
ML
1461
1462 .bdrv_co_pwrite_zeroes = nvme_co_pwrite_zeroes,
e87a09d6 1463 .bdrv_co_pdiscard = nvme_co_pdiscard,
e0dd95e3 1464
bdd6a90a
FZ
1465 .bdrv_co_flush_to_disk = nvme_co_flush,
1466 .bdrv_reopen_prepare = nvme_reopen_prepare,
1467
bdd6a90a
FZ
1468 .bdrv_refresh_filename = nvme_refresh_filename,
1469 .bdrv_refresh_limits = nvme_refresh_limits,
2654267c 1470 .strong_runtime_opts = nvme_strong_runtime_opts,
bdd6a90a
FZ
1471
1472 .bdrv_detach_aio_context = nvme_detach_aio_context,
1473 .bdrv_attach_aio_context = nvme_attach_aio_context,
1474
1475 .bdrv_io_plug = nvme_aio_plug,
1476 .bdrv_io_unplug = nvme_aio_unplug,
9ed61612
FZ
1477
1478 .bdrv_register_buf = nvme_register_buf,
1479 .bdrv_unregister_buf = nvme_unregister_buf,
bdd6a90a
FZ
1480};
1481
1482static void bdrv_nvme_init(void)
1483{
1484 bdrv_register(&bdrv_nvme);
1485}
1486
1487block_init(bdrv_nvme_init);