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