hw/block/nvme: remove the req dependency in map functions
[qemu/ar7.git] / hw / block / nvme.c
blob59942f88113fb64148d0868d2827c86ed608c16b
1 /*
2 * QEMU NVM Express Controller
4 * Copyright (c) 2012, Intel Corporation
6 * Written by Keith Busch <keith.busch@intel.com>
8 * This code is licensed under the GNU GPL v2 or later.
9 */
11 /**
12 * Reference Specs: http://www.nvmexpress.org, 1.4, 1.3, 1.2, 1.1, 1.0e
14 * https://nvmexpress.org/developers/nvme-specification/
17 /**
18 * Usage: add options:
19 * -drive file=<file>,if=none,id=<drive_id>
20 * -device nvme-subsys,id=<subsys_id>,nqn=<nqn_id>
21 * -device nvme,serial=<serial>,id=<bus_name>, \
22 * cmb_size_mb=<cmb_size_mb[optional]>, \
23 * [pmrdev=<mem_backend_file_id>,] \
24 * max_ioqpairs=<N[optional]>, \
25 * aerl=<N[optional]>,aer_max_queued=<N[optional]>, \
26 * mdts=<N[optional]>,zoned.zasl=<N[optional]>, \
27 * subsys=<subsys_id>
28 * -device nvme-ns,drive=<drive_id>,bus=<bus_name>,nsid=<nsid>,\
29 * zoned=<true|false[optional]>, \
30 * subsys=<subsys_id>
32 * Note cmb_size_mb denotes size of CMB in MB. CMB is assumed to be at
33 * offset 0 in BAR2 and supports only WDS, RDS and SQS for now. By default, the
34 * device will use the "v1.4 CMB scheme" - use the `legacy-cmb` parameter to
35 * always enable the CMBLOC and CMBSZ registers (v1.3 behavior).
37 * Enabling pmr emulation can be achieved by pointing to memory-backend-file.
38 * For example:
39 * -object memory-backend-file,id=<mem_id>,share=on,mem-path=<file_path>, \
40 * size=<size> .... -device nvme,...,pmrdev=<mem_id>
42 * The PMR will use BAR 4/5 exclusively.
44 * To place controller(s) and namespace(s) to a subsystem, then provide
45 * nvme-subsys device as above.
47 * nvme subsystem device parameters
48 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
49 * - `nqn`
50 * This parameter provides the `<nqn_id>` part of the string
51 * `nqn.2019-08.org.qemu:<nqn_id>` which will be reported in the SUBNQN field
52 * of subsystem controllers. Note that `<nqn_id>` should be unique per
53 * subsystem, but this is not enforced by QEMU. If not specified, it will
54 * default to the value of the `id` parameter (`<subsys_id>`).
56 * nvme device parameters
57 * ~~~~~~~~~~~~~~~~~~~~~~
58 * - `subsys`
59 * Specifying this parameter attaches the controller to the subsystem and
60 * the SUBNQN field in the controller will report the NQN of the subsystem
61 * device. This also enables multi controller capability represented in
62 * Identify Controller data structure in CMIC (Controller Multi-path I/O and
63 * Namesapce Sharing Capabilities).
65 * - `aerl`
66 * The Asynchronous Event Request Limit (AERL). Indicates the maximum number
67 * of concurrently outstanding Asynchronous Event Request commands support
68 * by the controller. This is a 0's based value.
70 * - `aer_max_queued`
71 * This is the maximum number of events that the device will enqueue for
72 * completion when there are no outstanding AERs. When the maximum number of
73 * enqueued events are reached, subsequent events will be dropped.
75 * - `mdts`
76 * Indicates the maximum data transfer size for a command that transfers data
77 * between host-accessible memory and the controller. The value is specified
78 * as a power of two (2^n) and is in units of the minimum memory page size
79 * (CAP.MPSMIN). The default value is 7 (i.e. 512 KiB).
81 * - `zoned.zasl`
82 * Indicates the maximum data transfer size for the Zone Append command. Like
83 * `mdts`, the value is specified as a power of two (2^n) and is in units of
84 * the minimum memory page size (CAP.MPSMIN). The default value is 0 (i.e.
85 * defaulting to the value of `mdts`).
87 * nvme namespace device parameters
88 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
89 * - `subsys`
90 * If given, the namespace will be attached to all controllers in the
91 * subsystem. Otherwise, `bus` must be given to attach this namespace to a
92 * specific controller as a non-shared namespace.
94 * Setting `zoned` to true selects Zoned Command Set at the namespace.
95 * In this case, the following namespace properties are available to configure
96 * zoned operation:
97 * zoned.zone_size=<zone size in bytes, default: 128MiB>
98 * The number may be followed by K, M, G as in kilo-, mega- or giga-.
100 * zoned.zone_capacity=<zone capacity in bytes, default: zone size>
101 * The value 0 (default) forces zone capacity to be the same as zone
102 * size. The value of this property may not exceed zone size.
104 * zoned.descr_ext_size=<zone descriptor extension size, default 0>
105 * This value needs to be specified in 64B units. If it is zero,
106 * namespace(s) will not support zone descriptor extensions.
108 * zoned.max_active=<Maximum Active Resources (zones), default: 0>
109 * The default value means there is no limit to the number of
110 * concurrently active zones.
112 * zoned.max_open=<Maximum Open Resources (zones), default: 0>
113 * The default value means there is no limit to the number of
114 * concurrently open zones.
116 * zoned.cross_read=<enable RAZB, default: false>
117 * Setting this property to true enables Read Across Zone Boundaries.
120 #include "qemu/osdep.h"
121 #include "qemu/units.h"
122 #include "qemu/error-report.h"
123 #include "hw/block/block.h"
124 #include "hw/pci/msix.h"
125 #include "hw/pci/pci.h"
126 #include "hw/qdev-properties.h"
127 #include "migration/vmstate.h"
128 #include "sysemu/sysemu.h"
129 #include "qapi/error.h"
130 #include "qapi/visitor.h"
131 #include "sysemu/hostmem.h"
132 #include "sysemu/block-backend.h"
133 #include "exec/memory.h"
134 #include "qemu/log.h"
135 #include "qemu/module.h"
136 #include "qemu/cutils.h"
137 #include "trace.h"
138 #include "nvme.h"
139 #include "nvme-ns.h"
141 #define NVME_MAX_IOQPAIRS 0xffff
142 #define NVME_DB_SIZE 4
143 #define NVME_SPEC_VER 0x00010400
144 #define NVME_CMB_BIR 2
145 #define NVME_PMR_BIR 4
146 #define NVME_TEMPERATURE 0x143
147 #define NVME_TEMPERATURE_WARNING 0x157
148 #define NVME_TEMPERATURE_CRITICAL 0x175
149 #define NVME_NUM_FW_SLOTS 1
151 #define NVME_GUEST_ERR(trace, fmt, ...) \
152 do { \
153 (trace_##trace)(__VA_ARGS__); \
154 qemu_log_mask(LOG_GUEST_ERROR, #trace \
155 " in %s: " fmt "\n", __func__, ## __VA_ARGS__); \
156 } while (0)
158 static const bool nvme_feature_support[NVME_FID_MAX] = {
159 [NVME_ARBITRATION] = true,
160 [NVME_POWER_MANAGEMENT] = true,
161 [NVME_TEMPERATURE_THRESHOLD] = true,
162 [NVME_ERROR_RECOVERY] = true,
163 [NVME_VOLATILE_WRITE_CACHE] = true,
164 [NVME_NUMBER_OF_QUEUES] = true,
165 [NVME_INTERRUPT_COALESCING] = true,
166 [NVME_INTERRUPT_VECTOR_CONF] = true,
167 [NVME_WRITE_ATOMICITY] = true,
168 [NVME_ASYNCHRONOUS_EVENT_CONF] = true,
169 [NVME_TIMESTAMP] = true,
172 static const uint32_t nvme_feature_cap[NVME_FID_MAX] = {
173 [NVME_TEMPERATURE_THRESHOLD] = NVME_FEAT_CAP_CHANGE,
174 [NVME_ERROR_RECOVERY] = NVME_FEAT_CAP_CHANGE | NVME_FEAT_CAP_NS,
175 [NVME_VOLATILE_WRITE_CACHE] = NVME_FEAT_CAP_CHANGE,
176 [NVME_NUMBER_OF_QUEUES] = NVME_FEAT_CAP_CHANGE,
177 [NVME_ASYNCHRONOUS_EVENT_CONF] = NVME_FEAT_CAP_CHANGE,
178 [NVME_TIMESTAMP] = NVME_FEAT_CAP_CHANGE,
181 static const uint32_t nvme_cse_acs[256] = {
182 [NVME_ADM_CMD_DELETE_SQ] = NVME_CMD_EFF_CSUPP,
183 [NVME_ADM_CMD_CREATE_SQ] = NVME_CMD_EFF_CSUPP,
184 [NVME_ADM_CMD_GET_LOG_PAGE] = NVME_CMD_EFF_CSUPP,
185 [NVME_ADM_CMD_DELETE_CQ] = NVME_CMD_EFF_CSUPP,
186 [NVME_ADM_CMD_CREATE_CQ] = NVME_CMD_EFF_CSUPP,
187 [NVME_ADM_CMD_IDENTIFY] = NVME_CMD_EFF_CSUPP,
188 [NVME_ADM_CMD_ABORT] = NVME_CMD_EFF_CSUPP,
189 [NVME_ADM_CMD_SET_FEATURES] = NVME_CMD_EFF_CSUPP,
190 [NVME_ADM_CMD_GET_FEATURES] = NVME_CMD_EFF_CSUPP,
191 [NVME_ADM_CMD_ASYNC_EV_REQ] = NVME_CMD_EFF_CSUPP,
194 static const uint32_t nvme_cse_iocs_none[256];
196 static const uint32_t nvme_cse_iocs_nvm[256] = {
197 [NVME_CMD_FLUSH] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
198 [NVME_CMD_WRITE_ZEROES] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
199 [NVME_CMD_WRITE] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
200 [NVME_CMD_READ] = NVME_CMD_EFF_CSUPP,
201 [NVME_CMD_DSM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
202 [NVME_CMD_COPY] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
203 [NVME_CMD_COMPARE] = NVME_CMD_EFF_CSUPP,
206 static const uint32_t nvme_cse_iocs_zoned[256] = {
207 [NVME_CMD_FLUSH] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
208 [NVME_CMD_WRITE_ZEROES] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
209 [NVME_CMD_WRITE] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
210 [NVME_CMD_READ] = NVME_CMD_EFF_CSUPP,
211 [NVME_CMD_DSM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
212 [NVME_CMD_COPY] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
213 [NVME_CMD_COMPARE] = NVME_CMD_EFF_CSUPP,
214 [NVME_CMD_ZONE_APPEND] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
215 [NVME_CMD_ZONE_MGMT_SEND] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
216 [NVME_CMD_ZONE_MGMT_RECV] = NVME_CMD_EFF_CSUPP,
219 static void nvme_process_sq(void *opaque);
221 static uint16_t nvme_cid(NvmeRequest *req)
223 if (!req) {
224 return 0xffff;
227 return le16_to_cpu(req->cqe.cid);
230 static uint16_t nvme_sqid(NvmeRequest *req)
232 return le16_to_cpu(req->sq->sqid);
235 static void nvme_assign_zone_state(NvmeNamespace *ns, NvmeZone *zone,
236 NvmeZoneState state)
238 if (QTAILQ_IN_USE(zone, entry)) {
239 switch (nvme_get_zone_state(zone)) {
240 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
241 QTAILQ_REMOVE(&ns->exp_open_zones, zone, entry);
242 break;
243 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
244 QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
245 break;
246 case NVME_ZONE_STATE_CLOSED:
247 QTAILQ_REMOVE(&ns->closed_zones, zone, entry);
248 break;
249 case NVME_ZONE_STATE_FULL:
250 QTAILQ_REMOVE(&ns->full_zones, zone, entry);
251 default:
256 nvme_set_zone_state(zone, state);
258 switch (state) {
259 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
260 QTAILQ_INSERT_TAIL(&ns->exp_open_zones, zone, entry);
261 break;
262 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
263 QTAILQ_INSERT_TAIL(&ns->imp_open_zones, zone, entry);
264 break;
265 case NVME_ZONE_STATE_CLOSED:
266 QTAILQ_INSERT_TAIL(&ns->closed_zones, zone, entry);
267 break;
268 case NVME_ZONE_STATE_FULL:
269 QTAILQ_INSERT_TAIL(&ns->full_zones, zone, entry);
270 case NVME_ZONE_STATE_READ_ONLY:
271 break;
272 default:
273 zone->d.za = 0;
278 * Check if we can open a zone without exceeding open/active limits.
279 * AOR stands for "Active and Open Resources" (see TP 4053 section 2.5).
281 static int nvme_aor_check(NvmeNamespace *ns, uint32_t act, uint32_t opn)
283 if (ns->params.max_active_zones != 0 &&
284 ns->nr_active_zones + act > ns->params.max_active_zones) {
285 trace_pci_nvme_err_insuff_active_res(ns->params.max_active_zones);
286 return NVME_ZONE_TOO_MANY_ACTIVE | NVME_DNR;
288 if (ns->params.max_open_zones != 0 &&
289 ns->nr_open_zones + opn > ns->params.max_open_zones) {
290 trace_pci_nvme_err_insuff_open_res(ns->params.max_open_zones);
291 return NVME_ZONE_TOO_MANY_OPEN | NVME_DNR;
294 return NVME_SUCCESS;
297 static bool nvme_addr_is_cmb(NvmeCtrl *n, hwaddr addr)
299 hwaddr hi, lo;
301 if (!n->cmb.cmse) {
302 return false;
305 lo = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
306 hi = lo + int128_get64(n->cmb.mem.size);
308 return addr >= lo && addr < hi;
311 static inline void *nvme_addr_to_cmb(NvmeCtrl *n, hwaddr addr)
313 hwaddr base = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
314 return &n->cmb.buf[addr - base];
317 static bool nvme_addr_is_pmr(NvmeCtrl *n, hwaddr addr)
319 hwaddr hi;
321 if (!n->pmr.cmse) {
322 return false;
325 hi = n->pmr.cba + int128_get64(n->pmr.dev->mr.size);
327 return addr >= n->pmr.cba && addr < hi;
330 static inline void *nvme_addr_to_pmr(NvmeCtrl *n, hwaddr addr)
332 return memory_region_get_ram_ptr(&n->pmr.dev->mr) + (addr - n->pmr.cba);
335 static int nvme_addr_read(NvmeCtrl *n, hwaddr addr, void *buf, int size)
337 hwaddr hi = addr + size - 1;
338 if (hi < addr) {
339 return 1;
342 if (n->bar.cmbsz && nvme_addr_is_cmb(n, addr) && nvme_addr_is_cmb(n, hi)) {
343 memcpy(buf, nvme_addr_to_cmb(n, addr), size);
344 return 0;
347 if (nvme_addr_is_pmr(n, addr) && nvme_addr_is_pmr(n, hi)) {
348 memcpy(buf, nvme_addr_to_pmr(n, addr), size);
349 return 0;
352 return pci_dma_read(&n->parent_obj, addr, buf, size);
355 static bool nvme_nsid_valid(NvmeCtrl *n, uint32_t nsid)
357 return nsid && (nsid == NVME_NSID_BROADCAST || nsid <= n->num_namespaces);
360 static int nvme_check_sqid(NvmeCtrl *n, uint16_t sqid)
362 return sqid < n->params.max_ioqpairs + 1 && n->sq[sqid] != NULL ? 0 : -1;
365 static int nvme_check_cqid(NvmeCtrl *n, uint16_t cqid)
367 return cqid < n->params.max_ioqpairs + 1 && n->cq[cqid] != NULL ? 0 : -1;
370 static void nvme_inc_cq_tail(NvmeCQueue *cq)
372 cq->tail++;
373 if (cq->tail >= cq->size) {
374 cq->tail = 0;
375 cq->phase = !cq->phase;
379 static void nvme_inc_sq_head(NvmeSQueue *sq)
381 sq->head = (sq->head + 1) % sq->size;
384 static uint8_t nvme_cq_full(NvmeCQueue *cq)
386 return (cq->tail + 1) % cq->size == cq->head;
389 static uint8_t nvme_sq_empty(NvmeSQueue *sq)
391 return sq->head == sq->tail;
394 static void nvme_irq_check(NvmeCtrl *n)
396 if (msix_enabled(&(n->parent_obj))) {
397 return;
399 if (~n->bar.intms & n->irq_status) {
400 pci_irq_assert(&n->parent_obj);
401 } else {
402 pci_irq_deassert(&n->parent_obj);
406 static void nvme_irq_assert(NvmeCtrl *n, NvmeCQueue *cq)
408 if (cq->irq_enabled) {
409 if (msix_enabled(&(n->parent_obj))) {
410 trace_pci_nvme_irq_msix(cq->vector);
411 msix_notify(&(n->parent_obj), cq->vector);
412 } else {
413 trace_pci_nvme_irq_pin();
414 assert(cq->vector < 32);
415 n->irq_status |= 1 << cq->vector;
416 nvme_irq_check(n);
418 } else {
419 trace_pci_nvme_irq_masked();
423 static void nvme_irq_deassert(NvmeCtrl *n, NvmeCQueue *cq)
425 if (cq->irq_enabled) {
426 if (msix_enabled(&(n->parent_obj))) {
427 return;
428 } else {
429 assert(cq->vector < 32);
430 n->irq_status &= ~(1 << cq->vector);
431 nvme_irq_check(n);
436 static void nvme_req_clear(NvmeRequest *req)
438 req->ns = NULL;
439 req->opaque = NULL;
440 memset(&req->cqe, 0x0, sizeof(req->cqe));
441 req->status = NVME_SUCCESS;
444 static inline void nvme_sg_init(NvmeCtrl *n, NvmeSg *sg, bool dma)
446 if (dma) {
447 pci_dma_sglist_init(&sg->qsg, &n->parent_obj, 0);
448 sg->flags = NVME_SG_DMA;
449 } else {
450 qemu_iovec_init(&sg->iov, 0);
453 sg->flags |= NVME_SG_ALLOC;
456 static inline void nvme_sg_unmap(NvmeSg *sg)
458 if (!(sg->flags & NVME_SG_ALLOC)) {
459 return;
462 if (sg->flags & NVME_SG_DMA) {
463 qemu_sglist_destroy(&sg->qsg);
464 } else {
465 qemu_iovec_destroy(&sg->iov);
468 memset(sg, 0x0, sizeof(*sg));
471 static uint16_t nvme_map_addr_cmb(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
472 size_t len)
474 if (!len) {
475 return NVME_SUCCESS;
478 trace_pci_nvme_map_addr_cmb(addr, len);
480 if (!nvme_addr_is_cmb(n, addr) || !nvme_addr_is_cmb(n, addr + len - 1)) {
481 return NVME_DATA_TRAS_ERROR;
484 qemu_iovec_add(iov, nvme_addr_to_cmb(n, addr), len);
486 return NVME_SUCCESS;
489 static uint16_t nvme_map_addr_pmr(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
490 size_t len)
492 if (!len) {
493 return NVME_SUCCESS;
496 if (!nvme_addr_is_pmr(n, addr) || !nvme_addr_is_pmr(n, addr + len - 1)) {
497 return NVME_DATA_TRAS_ERROR;
500 qemu_iovec_add(iov, nvme_addr_to_pmr(n, addr), len);
502 return NVME_SUCCESS;
505 static uint16_t nvme_map_addr(NvmeCtrl *n, NvmeSg *sg, hwaddr addr, size_t len)
507 bool cmb = false, pmr = false;
509 if (!len) {
510 return NVME_SUCCESS;
513 trace_pci_nvme_map_addr(addr, len);
515 if (nvme_addr_is_cmb(n, addr)) {
516 cmb = true;
517 } else if (nvme_addr_is_pmr(n, addr)) {
518 pmr = true;
521 if (cmb || pmr) {
522 if (sg->flags & NVME_SG_DMA) {
523 return NVME_INVALID_USE_OF_CMB | NVME_DNR;
526 if (cmb) {
527 return nvme_map_addr_cmb(n, &sg->iov, addr, len);
528 } else {
529 return nvme_map_addr_pmr(n, &sg->iov, addr, len);
533 if (!(sg->flags & NVME_SG_DMA)) {
534 return NVME_INVALID_USE_OF_CMB | NVME_DNR;
537 qemu_sglist_add(&sg->qsg, addr, len);
539 return NVME_SUCCESS;
542 static inline bool nvme_addr_is_dma(NvmeCtrl *n, hwaddr addr)
544 return !(nvme_addr_is_cmb(n, addr) || nvme_addr_is_pmr(n, addr));
547 static uint16_t nvme_map_prp(NvmeCtrl *n, NvmeSg *sg, uint64_t prp1,
548 uint64_t prp2, uint32_t len)
550 hwaddr trans_len = n->page_size - (prp1 % n->page_size);
551 trans_len = MIN(len, trans_len);
552 int num_prps = (len >> n->page_bits) + 1;
553 uint16_t status;
554 int ret;
556 trace_pci_nvme_map_prp(trans_len, len, prp1, prp2, num_prps);
558 nvme_sg_init(n, sg, nvme_addr_is_dma(n, prp1));
560 status = nvme_map_addr(n, sg, prp1, trans_len);
561 if (status) {
562 goto unmap;
565 len -= trans_len;
566 if (len) {
567 if (len > n->page_size) {
568 uint64_t prp_list[n->max_prp_ents];
569 uint32_t nents, prp_trans;
570 int i = 0;
572 nents = (len + n->page_size - 1) >> n->page_bits;
573 prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);
574 ret = nvme_addr_read(n, prp2, (void *)prp_list, prp_trans);
575 if (ret) {
576 trace_pci_nvme_err_addr_read(prp2);
577 status = NVME_DATA_TRAS_ERROR;
578 goto unmap;
580 while (len != 0) {
581 uint64_t prp_ent = le64_to_cpu(prp_list[i]);
583 if (i == n->max_prp_ents - 1 && len > n->page_size) {
584 if (unlikely(prp_ent & (n->page_size - 1))) {
585 trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
586 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
587 goto unmap;
590 i = 0;
591 nents = (len + n->page_size - 1) >> n->page_bits;
592 prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);
593 ret = nvme_addr_read(n, prp_ent, (void *)prp_list,
594 prp_trans);
595 if (ret) {
596 trace_pci_nvme_err_addr_read(prp_ent);
597 status = NVME_DATA_TRAS_ERROR;
598 goto unmap;
600 prp_ent = le64_to_cpu(prp_list[i]);
603 if (unlikely(prp_ent & (n->page_size - 1))) {
604 trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
605 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
606 goto unmap;
609 trans_len = MIN(len, n->page_size);
610 status = nvme_map_addr(n, sg, prp_ent, trans_len);
611 if (status) {
612 goto unmap;
615 len -= trans_len;
616 i++;
618 } else {
619 if (unlikely(prp2 & (n->page_size - 1))) {
620 trace_pci_nvme_err_invalid_prp2_align(prp2);
621 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
622 goto unmap;
624 status = nvme_map_addr(n, sg, prp2, len);
625 if (status) {
626 goto unmap;
631 return NVME_SUCCESS;
633 unmap:
634 nvme_sg_unmap(sg);
635 return status;
639 * Map 'nsgld' data descriptors from 'segment'. The function will subtract the
640 * number of bytes mapped in len.
642 static uint16_t nvme_map_sgl_data(NvmeCtrl *n, NvmeSg *sg,
643 NvmeSglDescriptor *segment, uint64_t nsgld,
644 size_t *len, NvmeCmd *cmd)
646 dma_addr_t addr, trans_len;
647 uint32_t dlen;
648 uint16_t status;
650 for (int i = 0; i < nsgld; i++) {
651 uint8_t type = NVME_SGL_TYPE(segment[i].type);
653 switch (type) {
654 case NVME_SGL_DESCR_TYPE_BIT_BUCKET:
655 if (cmd->opcode == NVME_CMD_WRITE) {
656 continue;
658 case NVME_SGL_DESCR_TYPE_DATA_BLOCK:
659 break;
660 case NVME_SGL_DESCR_TYPE_SEGMENT:
661 case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
662 return NVME_INVALID_NUM_SGL_DESCRS | NVME_DNR;
663 default:
664 return NVME_SGL_DESCR_TYPE_INVALID | NVME_DNR;
667 dlen = le32_to_cpu(segment[i].len);
669 if (!dlen) {
670 continue;
673 if (*len == 0) {
675 * All data has been mapped, but the SGL contains additional
676 * segments and/or descriptors. The controller might accept
677 * ignoring the rest of the SGL.
679 uint32_t sgls = le32_to_cpu(n->id_ctrl.sgls);
680 if (sgls & NVME_CTRL_SGLS_EXCESS_LENGTH) {
681 break;
684 trace_pci_nvme_err_invalid_sgl_excess_length(dlen);
685 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
688 trans_len = MIN(*len, dlen);
690 if (type == NVME_SGL_DESCR_TYPE_BIT_BUCKET) {
691 goto next;
694 addr = le64_to_cpu(segment[i].addr);
696 if (UINT64_MAX - addr < dlen) {
697 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
700 status = nvme_map_addr(n, sg, addr, trans_len);
701 if (status) {
702 return status;
705 next:
706 *len -= trans_len;
709 return NVME_SUCCESS;
712 static uint16_t nvme_map_sgl(NvmeCtrl *n, NvmeSg *sg, NvmeSglDescriptor sgl,
713 size_t len, NvmeCmd *cmd)
716 * Read the segment in chunks of 256 descriptors (one 4k page) to avoid
717 * dynamically allocating a potentially huge SGL. The spec allows the SGL
718 * to be larger (as in number of bytes required to describe the SGL
719 * descriptors and segment chain) than the command transfer size, so it is
720 * not bounded by MDTS.
722 const int SEG_CHUNK_SIZE = 256;
724 NvmeSglDescriptor segment[SEG_CHUNK_SIZE], *sgld, *last_sgld;
725 uint64_t nsgld;
726 uint32_t seg_len;
727 uint16_t status;
728 hwaddr addr;
729 int ret;
731 sgld = &sgl;
732 addr = le64_to_cpu(sgl.addr);
734 trace_pci_nvme_map_sgl(NVME_SGL_TYPE(sgl.type), len);
736 nvme_sg_init(n, sg, nvme_addr_is_dma(n, addr));
739 * If the entire transfer can be described with a single data block it can
740 * be mapped directly.
742 if (NVME_SGL_TYPE(sgl.type) == NVME_SGL_DESCR_TYPE_DATA_BLOCK) {
743 status = nvme_map_sgl_data(n, sg, sgld, 1, &len, cmd);
744 if (status) {
745 goto unmap;
748 goto out;
751 for (;;) {
752 switch (NVME_SGL_TYPE(sgld->type)) {
753 case NVME_SGL_DESCR_TYPE_SEGMENT:
754 case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
755 break;
756 default:
757 return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
760 seg_len = le32_to_cpu(sgld->len);
762 /* check the length of the (Last) Segment descriptor */
763 if ((!seg_len || seg_len & 0xf) &&
764 (NVME_SGL_TYPE(sgld->type) != NVME_SGL_DESCR_TYPE_BIT_BUCKET)) {
765 return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
768 if (UINT64_MAX - addr < seg_len) {
769 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
772 nsgld = seg_len / sizeof(NvmeSglDescriptor);
774 while (nsgld > SEG_CHUNK_SIZE) {
775 if (nvme_addr_read(n, addr, segment, sizeof(segment))) {
776 trace_pci_nvme_err_addr_read(addr);
777 status = NVME_DATA_TRAS_ERROR;
778 goto unmap;
781 status = nvme_map_sgl_data(n, sg, segment, SEG_CHUNK_SIZE,
782 &len, cmd);
783 if (status) {
784 goto unmap;
787 nsgld -= SEG_CHUNK_SIZE;
788 addr += SEG_CHUNK_SIZE * sizeof(NvmeSglDescriptor);
791 ret = nvme_addr_read(n, addr, segment, nsgld *
792 sizeof(NvmeSglDescriptor));
793 if (ret) {
794 trace_pci_nvme_err_addr_read(addr);
795 status = NVME_DATA_TRAS_ERROR;
796 goto unmap;
799 last_sgld = &segment[nsgld - 1];
802 * If the segment ends with a Data Block or Bit Bucket Descriptor Type,
803 * then we are done.
805 switch (NVME_SGL_TYPE(last_sgld->type)) {
806 case NVME_SGL_DESCR_TYPE_DATA_BLOCK:
807 case NVME_SGL_DESCR_TYPE_BIT_BUCKET:
808 status = nvme_map_sgl_data(n, sg, segment, nsgld, &len, cmd);
809 if (status) {
810 goto unmap;
813 goto out;
815 default:
816 break;
820 * If the last descriptor was not a Data Block or Bit Bucket, then the
821 * current segment must not be a Last Segment.
823 if (NVME_SGL_TYPE(sgld->type) == NVME_SGL_DESCR_TYPE_LAST_SEGMENT) {
824 status = NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
825 goto unmap;
828 sgld = last_sgld;
829 addr = le64_to_cpu(sgld->addr);
832 * Do not map the last descriptor; it will be a Segment or Last Segment
833 * descriptor and is handled by the next iteration.
835 status = nvme_map_sgl_data(n, sg, segment, nsgld - 1, &len, cmd);
836 if (status) {
837 goto unmap;
841 out:
842 /* if there is any residual left in len, the SGL was too short */
843 if (len) {
844 status = NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
845 goto unmap;
848 return NVME_SUCCESS;
850 unmap:
851 nvme_sg_unmap(sg);
852 return status;
855 static uint16_t nvme_map_dptr(NvmeCtrl *n, NvmeSg *sg, size_t len,
856 NvmeCmd *cmd)
858 uint64_t prp1, prp2;
860 switch (NVME_CMD_FLAGS_PSDT(cmd->flags)) {
861 case NVME_PSDT_PRP:
862 prp1 = le64_to_cpu(cmd->dptr.prp1);
863 prp2 = le64_to_cpu(cmd->dptr.prp2);
865 return nvme_map_prp(n, sg, prp1, prp2, len);
866 case NVME_PSDT_SGL_MPTR_CONTIGUOUS:
867 case NVME_PSDT_SGL_MPTR_SGL:
868 return nvme_map_sgl(n, sg, cmd->dptr.sgl, len, cmd);
869 default:
870 return NVME_INVALID_FIELD;
874 static uint16_t nvme_dma(NvmeCtrl *n, uint8_t *ptr, uint32_t len,
875 DMADirection dir, NvmeRequest *req)
877 uint16_t status = NVME_SUCCESS;
879 status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
880 if (status) {
881 return status;
884 if (req->sg.flags & NVME_SG_DMA) {
885 uint64_t residual;
887 if (dir == DMA_DIRECTION_TO_DEVICE) {
888 residual = dma_buf_write(ptr, len, &req->sg.qsg);
889 } else {
890 residual = dma_buf_read(ptr, len, &req->sg.qsg);
893 if (unlikely(residual)) {
894 trace_pci_nvme_err_invalid_dma();
895 status = NVME_INVALID_FIELD | NVME_DNR;
897 } else {
898 size_t bytes;
900 if (dir == DMA_DIRECTION_TO_DEVICE) {
901 bytes = qemu_iovec_to_buf(&req->sg.iov, 0, ptr, len);
902 } else {
903 bytes = qemu_iovec_from_buf(&req->sg.iov, 0, ptr, len);
906 if (unlikely(bytes != len)) {
907 trace_pci_nvme_err_invalid_dma();
908 status = NVME_INVALID_FIELD | NVME_DNR;
912 return status;
915 static inline void nvme_blk_read(BlockBackend *blk, int64_t offset,
916 BlockCompletionFunc *cb, NvmeRequest *req)
918 assert(req->sg.flags & NVME_SG_ALLOC);
920 if (req->sg.flags & NVME_SG_DMA) {
921 req->aiocb = dma_blk_read(blk, &req->sg.qsg, offset, BDRV_SECTOR_SIZE,
922 cb, req);
923 } else {
924 req->aiocb = blk_aio_preadv(blk, offset, &req->sg.iov, 0, cb, req);
928 static inline void nvme_blk_write(BlockBackend *blk, int64_t offset,
929 BlockCompletionFunc *cb, NvmeRequest *req)
931 assert(req->sg.flags & NVME_SG_ALLOC);
933 if (req->sg.flags & NVME_SG_DMA) {
934 req->aiocb = dma_blk_write(blk, &req->sg.qsg, offset, BDRV_SECTOR_SIZE,
935 cb, req);
936 } else {
937 req->aiocb = blk_aio_pwritev(blk, offset, &req->sg.iov, 0, cb, req);
941 static void nvme_post_cqes(void *opaque)
943 NvmeCQueue *cq = opaque;
944 NvmeCtrl *n = cq->ctrl;
945 NvmeRequest *req, *next;
946 int ret;
948 QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {
949 NvmeSQueue *sq;
950 hwaddr addr;
952 if (nvme_cq_full(cq)) {
953 break;
956 sq = req->sq;
957 req->cqe.status = cpu_to_le16((req->status << 1) | cq->phase);
958 req->cqe.sq_id = cpu_to_le16(sq->sqid);
959 req->cqe.sq_head = cpu_to_le16(sq->head);
960 addr = cq->dma_addr + cq->tail * n->cqe_size;
961 ret = pci_dma_write(&n->parent_obj, addr, (void *)&req->cqe,
962 sizeof(req->cqe));
963 if (ret) {
964 trace_pci_nvme_err_addr_write(addr);
965 trace_pci_nvme_err_cfs();
966 n->bar.csts = NVME_CSTS_FAILED;
967 break;
969 QTAILQ_REMOVE(&cq->req_list, req, entry);
970 nvme_inc_cq_tail(cq);
971 nvme_sg_unmap(&req->sg);
972 QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);
974 if (cq->tail != cq->head) {
975 nvme_irq_assert(n, cq);
979 static void nvme_enqueue_req_completion(NvmeCQueue *cq, NvmeRequest *req)
981 assert(cq->cqid == req->sq->cqid);
982 trace_pci_nvme_enqueue_req_completion(nvme_cid(req), cq->cqid,
983 req->status);
985 if (req->status) {
986 trace_pci_nvme_err_req_status(nvme_cid(req), nvme_nsid(req->ns),
987 req->status, req->cmd.opcode);
990 QTAILQ_REMOVE(&req->sq->out_req_list, req, entry);
991 QTAILQ_INSERT_TAIL(&cq->req_list, req, entry);
992 timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
995 static void nvme_process_aers(void *opaque)
997 NvmeCtrl *n = opaque;
998 NvmeAsyncEvent *event, *next;
1000 trace_pci_nvme_process_aers(n->aer_queued);
1002 QTAILQ_FOREACH_SAFE(event, &n->aer_queue, entry, next) {
1003 NvmeRequest *req;
1004 NvmeAerResult *result;
1006 /* can't post cqe if there is nothing to complete */
1007 if (!n->outstanding_aers) {
1008 trace_pci_nvme_no_outstanding_aers();
1009 break;
1012 /* ignore if masked (cqe posted, but event not cleared) */
1013 if (n->aer_mask & (1 << event->result.event_type)) {
1014 trace_pci_nvme_aer_masked(event->result.event_type, n->aer_mask);
1015 continue;
1018 QTAILQ_REMOVE(&n->aer_queue, event, entry);
1019 n->aer_queued--;
1021 n->aer_mask |= 1 << event->result.event_type;
1022 n->outstanding_aers--;
1024 req = n->aer_reqs[n->outstanding_aers];
1026 result = (NvmeAerResult *) &req->cqe.result;
1027 result->event_type = event->result.event_type;
1028 result->event_info = event->result.event_info;
1029 result->log_page = event->result.log_page;
1030 g_free(event);
1032 trace_pci_nvme_aer_post_cqe(result->event_type, result->event_info,
1033 result->log_page);
1035 nvme_enqueue_req_completion(&n->admin_cq, req);
1039 static void nvme_enqueue_event(NvmeCtrl *n, uint8_t event_type,
1040 uint8_t event_info, uint8_t log_page)
1042 NvmeAsyncEvent *event;
1044 trace_pci_nvme_enqueue_event(event_type, event_info, log_page);
1046 if (n->aer_queued == n->params.aer_max_queued) {
1047 trace_pci_nvme_enqueue_event_noqueue(n->aer_queued);
1048 return;
1051 event = g_new(NvmeAsyncEvent, 1);
1052 event->result = (NvmeAerResult) {
1053 .event_type = event_type,
1054 .event_info = event_info,
1055 .log_page = log_page,
1058 QTAILQ_INSERT_TAIL(&n->aer_queue, event, entry);
1059 n->aer_queued++;
1061 nvme_process_aers(n);
1064 static void nvme_smart_event(NvmeCtrl *n, uint8_t event)
1066 uint8_t aer_info;
1068 /* Ref SPEC <Asynchronous Event Information 0x2013 SMART / Health Status> */
1069 if (!(NVME_AEC_SMART(n->features.async_config) & event)) {
1070 return;
1073 switch (event) {
1074 case NVME_SMART_SPARE:
1075 aer_info = NVME_AER_INFO_SMART_SPARE_THRESH;
1076 break;
1077 case NVME_SMART_TEMPERATURE:
1078 aer_info = NVME_AER_INFO_SMART_TEMP_THRESH;
1079 break;
1080 case NVME_SMART_RELIABILITY:
1081 case NVME_SMART_MEDIA_READ_ONLY:
1082 case NVME_SMART_FAILED_VOLATILE_MEDIA:
1083 case NVME_SMART_PMR_UNRELIABLE:
1084 aer_info = NVME_AER_INFO_SMART_RELIABILITY;
1085 break;
1086 default:
1087 return;
1090 nvme_enqueue_event(n, NVME_AER_TYPE_SMART, aer_info, NVME_LOG_SMART_INFO);
1093 static void nvme_clear_events(NvmeCtrl *n, uint8_t event_type)
1095 n->aer_mask &= ~(1 << event_type);
1096 if (!QTAILQ_EMPTY(&n->aer_queue)) {
1097 nvme_process_aers(n);
1101 static inline uint16_t nvme_check_mdts(NvmeCtrl *n, size_t len)
1103 uint8_t mdts = n->params.mdts;
1105 if (mdts && len > n->page_size << mdts) {
1106 trace_pci_nvme_err_mdts(len);
1107 return NVME_INVALID_FIELD | NVME_DNR;
1110 return NVME_SUCCESS;
1113 static inline uint16_t nvme_check_bounds(NvmeNamespace *ns, uint64_t slba,
1114 uint32_t nlb)
1116 uint64_t nsze = le64_to_cpu(ns->id_ns.nsze);
1118 if (unlikely(UINT64_MAX - slba < nlb || slba + nlb > nsze)) {
1119 return NVME_LBA_RANGE | NVME_DNR;
1122 return NVME_SUCCESS;
1125 static uint16_t nvme_check_dulbe(NvmeNamespace *ns, uint64_t slba,
1126 uint32_t nlb)
1128 BlockDriverState *bs = blk_bs(ns->blkconf.blk);
1130 int64_t pnum = 0, bytes = nvme_l2b(ns, nlb);
1131 int64_t offset = nvme_l2b(ns, slba);
1132 bool zeroed;
1133 int ret;
1135 Error *local_err = NULL;
1138 * `pnum` holds the number of bytes after offset that shares the same
1139 * allocation status as the byte at offset. If `pnum` is different from
1140 * `bytes`, we should check the allocation status of the next range and
1141 * continue this until all bytes have been checked.
1143 do {
1144 bytes -= pnum;
1146 ret = bdrv_block_status(bs, offset, bytes, &pnum, NULL, NULL);
1147 if (ret < 0) {
1148 error_setg_errno(&local_err, -ret, "unable to get block status");
1149 error_report_err(local_err);
1151 return NVME_INTERNAL_DEV_ERROR;
1154 zeroed = !!(ret & BDRV_BLOCK_ZERO);
1156 trace_pci_nvme_block_status(offset, bytes, pnum, ret, zeroed);
1158 if (zeroed) {
1159 return NVME_DULB;
1162 offset += pnum;
1163 } while (pnum != bytes);
1165 return NVME_SUCCESS;
1168 static void nvme_aio_err(NvmeRequest *req, int ret)
1170 uint16_t status = NVME_SUCCESS;
1171 Error *local_err = NULL;
1173 switch (req->cmd.opcode) {
1174 case NVME_CMD_READ:
1175 status = NVME_UNRECOVERED_READ;
1176 break;
1177 case NVME_CMD_FLUSH:
1178 case NVME_CMD_WRITE:
1179 case NVME_CMD_WRITE_ZEROES:
1180 case NVME_CMD_ZONE_APPEND:
1181 status = NVME_WRITE_FAULT;
1182 break;
1183 default:
1184 status = NVME_INTERNAL_DEV_ERROR;
1185 break;
1188 trace_pci_nvme_err_aio(nvme_cid(req), strerror(-ret), status);
1190 error_setg_errno(&local_err, -ret, "aio failed");
1191 error_report_err(local_err);
1194 * Set the command status code to the first encountered error but allow a
1195 * subsequent Internal Device Error to trump it.
1197 if (req->status && status != NVME_INTERNAL_DEV_ERROR) {
1198 return;
1201 req->status = status;
1204 static inline uint32_t nvme_zone_idx(NvmeNamespace *ns, uint64_t slba)
1206 return ns->zone_size_log2 > 0 ? slba >> ns->zone_size_log2 :
1207 slba / ns->zone_size;
1210 static inline NvmeZone *nvme_get_zone_by_slba(NvmeNamespace *ns, uint64_t slba)
1212 uint32_t zone_idx = nvme_zone_idx(ns, slba);
1214 assert(zone_idx < ns->num_zones);
1215 return &ns->zone_array[zone_idx];
1218 static uint16_t nvme_check_zone_state_for_write(NvmeZone *zone)
1220 uint64_t zslba = zone->d.zslba;
1222 switch (nvme_get_zone_state(zone)) {
1223 case NVME_ZONE_STATE_EMPTY:
1224 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1225 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1226 case NVME_ZONE_STATE_CLOSED:
1227 return NVME_SUCCESS;
1228 case NVME_ZONE_STATE_FULL:
1229 trace_pci_nvme_err_zone_is_full(zslba);
1230 return NVME_ZONE_FULL;
1231 case NVME_ZONE_STATE_OFFLINE:
1232 trace_pci_nvme_err_zone_is_offline(zslba);
1233 return NVME_ZONE_OFFLINE;
1234 case NVME_ZONE_STATE_READ_ONLY:
1235 trace_pci_nvme_err_zone_is_read_only(zslba);
1236 return NVME_ZONE_READ_ONLY;
1237 default:
1238 assert(false);
1241 return NVME_INTERNAL_DEV_ERROR;
1244 static uint16_t nvme_check_zone_write(NvmeNamespace *ns, NvmeZone *zone,
1245 uint64_t slba, uint32_t nlb)
1247 uint64_t zcap = nvme_zone_wr_boundary(zone);
1248 uint16_t status;
1250 status = nvme_check_zone_state_for_write(zone);
1251 if (status) {
1252 return status;
1255 if (unlikely(slba != zone->w_ptr)) {
1256 trace_pci_nvme_err_write_not_at_wp(slba, zone->d.zslba, zone->w_ptr);
1257 return NVME_ZONE_INVALID_WRITE;
1260 if (unlikely((slba + nlb) > zcap)) {
1261 trace_pci_nvme_err_zone_boundary(slba, nlb, zcap);
1262 return NVME_ZONE_BOUNDARY_ERROR;
1265 return NVME_SUCCESS;
1268 static uint16_t nvme_check_zone_state_for_read(NvmeZone *zone)
1270 switch (nvme_get_zone_state(zone)) {
1271 case NVME_ZONE_STATE_EMPTY:
1272 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1273 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1274 case NVME_ZONE_STATE_FULL:
1275 case NVME_ZONE_STATE_CLOSED:
1276 case NVME_ZONE_STATE_READ_ONLY:
1277 return NVME_SUCCESS;
1278 case NVME_ZONE_STATE_OFFLINE:
1279 trace_pci_nvme_err_zone_is_offline(zone->d.zslba);
1280 return NVME_ZONE_OFFLINE;
1281 default:
1282 assert(false);
1285 return NVME_INTERNAL_DEV_ERROR;
1288 static uint16_t nvme_check_zone_read(NvmeNamespace *ns, uint64_t slba,
1289 uint32_t nlb)
1291 NvmeZone *zone = nvme_get_zone_by_slba(ns, slba);
1292 uint64_t bndry = nvme_zone_rd_boundary(ns, zone);
1293 uint64_t end = slba + nlb;
1294 uint16_t status;
1296 status = nvme_check_zone_state_for_read(zone);
1297 if (status) {
1299 } else if (unlikely(end > bndry)) {
1300 if (!ns->params.cross_zone_read) {
1301 status = NVME_ZONE_BOUNDARY_ERROR;
1302 } else {
1304 * Read across zone boundary - check that all subsequent
1305 * zones that are being read have an appropriate state.
1307 do {
1308 zone++;
1309 status = nvme_check_zone_state_for_read(zone);
1310 if (status) {
1311 break;
1313 } while (end > nvme_zone_rd_boundary(ns, zone));
1317 return status;
1320 static uint16_t nvme_zrm_finish(NvmeNamespace *ns, NvmeZone *zone)
1322 switch (nvme_get_zone_state(zone)) {
1323 case NVME_ZONE_STATE_FULL:
1324 return NVME_SUCCESS;
1326 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1327 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1328 nvme_aor_dec_open(ns);
1329 /* fallthrough */
1330 case NVME_ZONE_STATE_CLOSED:
1331 nvme_aor_dec_active(ns);
1332 /* fallthrough */
1333 case NVME_ZONE_STATE_EMPTY:
1334 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_FULL);
1335 return NVME_SUCCESS;
1337 default:
1338 return NVME_ZONE_INVAL_TRANSITION;
1342 static uint16_t nvme_zrm_close(NvmeNamespace *ns, NvmeZone *zone)
1344 switch (nvme_get_zone_state(zone)) {
1345 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1346 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1347 nvme_aor_dec_open(ns);
1348 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
1349 /* fall through */
1350 case NVME_ZONE_STATE_CLOSED:
1351 return NVME_SUCCESS;
1353 default:
1354 return NVME_ZONE_INVAL_TRANSITION;
1358 static void nvme_zrm_auto_transition_zone(NvmeNamespace *ns)
1360 NvmeZone *zone;
1362 if (ns->params.max_open_zones &&
1363 ns->nr_open_zones == ns->params.max_open_zones) {
1364 zone = QTAILQ_FIRST(&ns->imp_open_zones);
1365 if (zone) {
1367 * Automatically close this implicitly open zone.
1369 QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
1370 nvme_zrm_close(ns, zone);
1375 static uint16_t __nvme_zrm_open(NvmeNamespace *ns, NvmeZone *zone,
1376 bool implicit)
1378 int act = 0;
1379 uint16_t status;
1381 switch (nvme_get_zone_state(zone)) {
1382 case NVME_ZONE_STATE_EMPTY:
1383 act = 1;
1385 /* fallthrough */
1387 case NVME_ZONE_STATE_CLOSED:
1388 nvme_zrm_auto_transition_zone(ns);
1389 status = nvme_aor_check(ns, act, 1);
1390 if (status) {
1391 return status;
1394 if (act) {
1395 nvme_aor_inc_active(ns);
1398 nvme_aor_inc_open(ns);
1400 if (implicit) {
1401 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_IMPLICITLY_OPEN);
1402 return NVME_SUCCESS;
1405 /* fallthrough */
1407 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1408 if (implicit) {
1409 return NVME_SUCCESS;
1412 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EXPLICITLY_OPEN);
1414 /* fallthrough */
1416 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1417 return NVME_SUCCESS;
1419 default:
1420 return NVME_ZONE_INVAL_TRANSITION;
1424 static inline uint16_t nvme_zrm_auto(NvmeNamespace *ns, NvmeZone *zone)
1426 return __nvme_zrm_open(ns, zone, true);
1429 static inline uint16_t nvme_zrm_open(NvmeNamespace *ns, NvmeZone *zone)
1431 return __nvme_zrm_open(ns, zone, false);
1434 static void __nvme_advance_zone_wp(NvmeNamespace *ns, NvmeZone *zone,
1435 uint32_t nlb)
1437 zone->d.wp += nlb;
1439 if (zone->d.wp == nvme_zone_wr_boundary(zone)) {
1440 nvme_zrm_finish(ns, zone);
1444 static void nvme_finalize_zoned_write(NvmeNamespace *ns, NvmeRequest *req)
1446 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1447 NvmeZone *zone;
1448 uint64_t slba;
1449 uint32_t nlb;
1451 slba = le64_to_cpu(rw->slba);
1452 nlb = le16_to_cpu(rw->nlb) + 1;
1453 zone = nvme_get_zone_by_slba(ns, slba);
1455 __nvme_advance_zone_wp(ns, zone, nlb);
1458 static inline bool nvme_is_write(NvmeRequest *req)
1460 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1462 return rw->opcode == NVME_CMD_WRITE ||
1463 rw->opcode == NVME_CMD_ZONE_APPEND ||
1464 rw->opcode == NVME_CMD_WRITE_ZEROES;
1467 static void nvme_rw_cb(void *opaque, int ret)
1469 NvmeRequest *req = opaque;
1470 NvmeNamespace *ns = req->ns;
1472 BlockBackend *blk = ns->blkconf.blk;
1473 BlockAcctCookie *acct = &req->acct;
1474 BlockAcctStats *stats = blk_get_stats(blk);
1476 trace_pci_nvme_rw_cb(nvme_cid(req), blk_name(blk));
1478 if (ns->params.zoned && nvme_is_write(req)) {
1479 nvme_finalize_zoned_write(ns, req);
1482 if (!ret) {
1483 block_acct_done(stats, acct);
1484 } else {
1485 block_acct_failed(stats, acct);
1486 nvme_aio_err(req, ret);
1489 nvme_enqueue_req_completion(nvme_cq(req), req);
1492 struct nvme_aio_flush_ctx {
1493 NvmeRequest *req;
1494 NvmeNamespace *ns;
1495 BlockAcctCookie acct;
1498 static void nvme_aio_flush_cb(void *opaque, int ret)
1500 struct nvme_aio_flush_ctx *ctx = opaque;
1501 NvmeRequest *req = ctx->req;
1502 uintptr_t *num_flushes = (uintptr_t *)&req->opaque;
1504 BlockBackend *blk = ctx->ns->blkconf.blk;
1505 BlockAcctCookie *acct = &ctx->acct;
1506 BlockAcctStats *stats = blk_get_stats(blk);
1508 trace_pci_nvme_aio_flush_cb(nvme_cid(req), blk_name(blk));
1510 if (!ret) {
1511 block_acct_done(stats, acct);
1512 } else {
1513 block_acct_failed(stats, acct);
1514 nvme_aio_err(req, ret);
1517 (*num_flushes)--;
1518 g_free(ctx);
1520 if (*num_flushes) {
1521 return;
1524 nvme_enqueue_req_completion(nvme_cq(req), req);
1527 static void nvme_aio_discard_cb(void *opaque, int ret)
1529 NvmeRequest *req = opaque;
1530 uintptr_t *discards = (uintptr_t *)&req->opaque;
1532 trace_pci_nvme_aio_discard_cb(nvme_cid(req));
1534 if (ret) {
1535 nvme_aio_err(req, ret);
1538 (*discards)--;
1540 if (*discards) {
1541 return;
1544 nvme_enqueue_req_completion(nvme_cq(req), req);
1547 struct nvme_zone_reset_ctx {
1548 NvmeRequest *req;
1549 NvmeZone *zone;
1552 static void nvme_aio_zone_reset_cb(void *opaque, int ret)
1554 struct nvme_zone_reset_ctx *ctx = opaque;
1555 NvmeRequest *req = ctx->req;
1556 NvmeNamespace *ns = req->ns;
1557 NvmeZone *zone = ctx->zone;
1558 uintptr_t *resets = (uintptr_t *)&req->opaque;
1560 g_free(ctx);
1562 trace_pci_nvme_aio_zone_reset_cb(nvme_cid(req), zone->d.zslba);
1564 if (!ret) {
1565 switch (nvme_get_zone_state(zone)) {
1566 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1567 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1568 nvme_aor_dec_open(ns);
1569 /* fall through */
1570 case NVME_ZONE_STATE_CLOSED:
1571 nvme_aor_dec_active(ns);
1572 /* fall through */
1573 case NVME_ZONE_STATE_FULL:
1574 zone->w_ptr = zone->d.zslba;
1575 zone->d.wp = zone->w_ptr;
1576 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EMPTY);
1577 /* fall through */
1578 default:
1579 break;
1581 } else {
1582 nvme_aio_err(req, ret);
1585 (*resets)--;
1587 if (*resets) {
1588 return;
1591 nvme_enqueue_req_completion(nvme_cq(req), req);
1594 struct nvme_copy_ctx {
1595 int copies;
1596 uint8_t *bounce;
1597 uint32_t nlb;
1600 struct nvme_copy_in_ctx {
1601 NvmeRequest *req;
1602 QEMUIOVector iov;
1605 static void nvme_copy_cb(void *opaque, int ret)
1607 NvmeRequest *req = opaque;
1608 NvmeNamespace *ns = req->ns;
1609 struct nvme_copy_ctx *ctx = req->opaque;
1611 trace_pci_nvme_copy_cb(nvme_cid(req));
1613 if (ns->params.zoned) {
1614 NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
1615 uint64_t sdlba = le64_to_cpu(copy->sdlba);
1616 NvmeZone *zone = nvme_get_zone_by_slba(ns, sdlba);
1618 __nvme_advance_zone_wp(ns, zone, ctx->nlb);
1621 if (!ret) {
1622 block_acct_done(blk_get_stats(ns->blkconf.blk), &req->acct);
1623 } else {
1624 block_acct_failed(blk_get_stats(ns->blkconf.blk), &req->acct);
1625 nvme_aio_err(req, ret);
1628 g_free(ctx->bounce);
1629 g_free(ctx);
1631 nvme_enqueue_req_completion(nvme_cq(req), req);
1634 static void nvme_copy_in_complete(NvmeRequest *req)
1636 NvmeNamespace *ns = req->ns;
1637 NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
1638 struct nvme_copy_ctx *ctx = req->opaque;
1639 uint64_t sdlba = le64_to_cpu(copy->sdlba);
1640 uint16_t status;
1642 trace_pci_nvme_copy_in_complete(nvme_cid(req));
1644 block_acct_done(blk_get_stats(ns->blkconf.blk), &req->acct);
1646 status = nvme_check_bounds(ns, sdlba, ctx->nlb);
1647 if (status) {
1648 trace_pci_nvme_err_invalid_lba_range(sdlba, ctx->nlb, ns->id_ns.nsze);
1649 goto invalid;
1652 if (ns->params.zoned) {
1653 NvmeZone *zone = nvme_get_zone_by_slba(ns, sdlba);
1655 status = nvme_check_zone_write(ns, zone, sdlba, ctx->nlb);
1656 if (status) {
1657 goto invalid;
1660 status = nvme_zrm_auto(ns, zone);
1661 if (status) {
1662 goto invalid;
1665 zone->w_ptr += ctx->nlb;
1668 qemu_iovec_init(&req->sg.iov, 1);
1669 qemu_iovec_add(&req->sg.iov, ctx->bounce, nvme_l2b(ns, ctx->nlb));
1671 block_acct_start(blk_get_stats(ns->blkconf.blk), &req->acct, 0,
1672 BLOCK_ACCT_WRITE);
1674 req->aiocb = blk_aio_pwritev(ns->blkconf.blk, nvme_l2b(ns, sdlba),
1675 &req->sg.iov, 0, nvme_copy_cb, req);
1677 return;
1679 invalid:
1680 req->status = status;
1682 g_free(ctx->bounce);
1683 g_free(ctx);
1685 nvme_enqueue_req_completion(nvme_cq(req), req);
1688 static void nvme_aio_copy_in_cb(void *opaque, int ret)
1690 struct nvme_copy_in_ctx *in_ctx = opaque;
1691 NvmeRequest *req = in_ctx->req;
1692 NvmeNamespace *ns = req->ns;
1693 struct nvme_copy_ctx *ctx = req->opaque;
1695 qemu_iovec_destroy(&in_ctx->iov);
1696 g_free(in_ctx);
1698 trace_pci_nvme_aio_copy_in_cb(nvme_cid(req));
1700 if (ret) {
1701 nvme_aio_err(req, ret);
1704 ctx->copies--;
1706 if (ctx->copies) {
1707 return;
1710 if (req->status) {
1711 block_acct_failed(blk_get_stats(ns->blkconf.blk), &req->acct);
1713 g_free(ctx->bounce);
1714 g_free(ctx);
1716 nvme_enqueue_req_completion(nvme_cq(req), req);
1718 return;
1721 nvme_copy_in_complete(req);
1724 struct nvme_compare_ctx {
1725 QEMUIOVector iov;
1726 uint8_t *bounce;
1729 static void nvme_compare_cb(void *opaque, int ret)
1731 NvmeRequest *req = opaque;
1732 NvmeNamespace *ns = req->ns;
1733 struct nvme_compare_ctx *ctx = req->opaque;
1734 g_autofree uint8_t *buf = NULL;
1735 uint16_t status;
1737 trace_pci_nvme_compare_cb(nvme_cid(req));
1739 if (!ret) {
1740 block_acct_done(blk_get_stats(ns->blkconf.blk), &req->acct);
1741 } else {
1742 block_acct_failed(blk_get_stats(ns->blkconf.blk), &req->acct);
1743 nvme_aio_err(req, ret);
1744 goto out;
1747 buf = g_malloc(ctx->iov.size);
1749 status = nvme_dma(nvme_ctrl(req), buf, ctx->iov.size,
1750 DMA_DIRECTION_TO_DEVICE, req);
1751 if (status) {
1752 req->status = status;
1753 goto out;
1756 if (memcmp(buf, ctx->bounce, ctx->iov.size)) {
1757 req->status = NVME_CMP_FAILURE;
1760 out:
1761 qemu_iovec_destroy(&ctx->iov);
1762 g_free(ctx->bounce);
1763 g_free(ctx);
1765 nvme_enqueue_req_completion(nvme_cq(req), req);
1768 static uint16_t nvme_dsm(NvmeCtrl *n, NvmeRequest *req)
1770 NvmeNamespace *ns = req->ns;
1771 NvmeDsmCmd *dsm = (NvmeDsmCmd *) &req->cmd;
1773 uint32_t attr = le32_to_cpu(dsm->attributes);
1774 uint32_t nr = (le32_to_cpu(dsm->nr) & 0xff) + 1;
1776 uint16_t status = NVME_SUCCESS;
1778 trace_pci_nvme_dsm(nvme_cid(req), nvme_nsid(ns), nr, attr);
1780 if (attr & NVME_DSMGMT_AD) {
1781 int64_t offset;
1782 size_t len;
1783 NvmeDsmRange range[nr];
1784 uintptr_t *discards = (uintptr_t *)&req->opaque;
1786 status = nvme_dma(n, (uint8_t *)range, sizeof(range),
1787 DMA_DIRECTION_TO_DEVICE, req);
1788 if (status) {
1789 return status;
1793 * AIO callbacks may be called immediately, so initialize discards to 1
1794 * to make sure the the callback does not complete the request before
1795 * all discards have been issued.
1797 *discards = 1;
1799 for (int i = 0; i < nr; i++) {
1800 uint64_t slba = le64_to_cpu(range[i].slba);
1801 uint32_t nlb = le32_to_cpu(range[i].nlb);
1803 if (nvme_check_bounds(ns, slba, nlb)) {
1804 trace_pci_nvme_err_invalid_lba_range(slba, nlb,
1805 ns->id_ns.nsze);
1806 continue;
1809 trace_pci_nvme_dsm_deallocate(nvme_cid(req), nvme_nsid(ns), slba,
1810 nlb);
1812 if (nlb > n->dmrsl) {
1813 trace_pci_nvme_dsm_single_range_limit_exceeded(nlb, n->dmrsl);
1816 offset = nvme_l2b(ns, slba);
1817 len = nvme_l2b(ns, nlb);
1819 while (len) {
1820 size_t bytes = MIN(BDRV_REQUEST_MAX_BYTES, len);
1822 (*discards)++;
1824 blk_aio_pdiscard(ns->blkconf.blk, offset, bytes,
1825 nvme_aio_discard_cb, req);
1827 offset += bytes;
1828 len -= bytes;
1832 /* account for the 1-initialization */
1833 (*discards)--;
1835 if (*discards) {
1836 status = NVME_NO_COMPLETE;
1837 } else {
1838 status = req->status;
1842 return status;
1845 static uint16_t nvme_copy(NvmeCtrl *n, NvmeRequest *req)
1847 NvmeNamespace *ns = req->ns;
1848 NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
1849 g_autofree NvmeCopySourceRange *range = NULL;
1851 uint16_t nr = copy->nr + 1;
1852 uint8_t format = copy->control[0] & 0xf;
1853 uint32_t nlb = 0;
1855 uint8_t *bounce = NULL, *bouncep = NULL;
1856 struct nvme_copy_ctx *ctx;
1857 uint16_t status;
1858 int i;
1860 trace_pci_nvme_copy(nvme_cid(req), nvme_nsid(ns), nr, format);
1862 if (!(n->id_ctrl.ocfs & (1 << format))) {
1863 trace_pci_nvme_err_copy_invalid_format(format);
1864 return NVME_INVALID_FIELD | NVME_DNR;
1867 if (nr > ns->id_ns.msrc + 1) {
1868 return NVME_CMD_SIZE_LIMIT | NVME_DNR;
1871 range = g_new(NvmeCopySourceRange, nr);
1873 status = nvme_dma(n, (uint8_t *)range, nr * sizeof(NvmeCopySourceRange),
1874 DMA_DIRECTION_TO_DEVICE, req);
1875 if (status) {
1876 return status;
1879 for (i = 0; i < nr; i++) {
1880 uint64_t slba = le64_to_cpu(range[i].slba);
1881 uint32_t _nlb = le16_to_cpu(range[i].nlb) + 1;
1883 if (_nlb > le16_to_cpu(ns->id_ns.mssrl)) {
1884 return NVME_CMD_SIZE_LIMIT | NVME_DNR;
1887 status = nvme_check_bounds(ns, slba, _nlb);
1888 if (status) {
1889 trace_pci_nvme_err_invalid_lba_range(slba, _nlb, ns->id_ns.nsze);
1890 return status;
1893 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
1894 status = nvme_check_dulbe(ns, slba, _nlb);
1895 if (status) {
1896 return status;
1900 if (ns->params.zoned) {
1901 status = nvme_check_zone_read(ns, slba, _nlb);
1902 if (status) {
1903 return status;
1907 nlb += _nlb;
1910 if (nlb > le32_to_cpu(ns->id_ns.mcl)) {
1911 return NVME_CMD_SIZE_LIMIT | NVME_DNR;
1914 bounce = bouncep = g_malloc(nvme_l2b(ns, nlb));
1916 block_acct_start(blk_get_stats(ns->blkconf.blk), &req->acct, 0,
1917 BLOCK_ACCT_READ);
1919 ctx = g_new(struct nvme_copy_ctx, 1);
1921 ctx->bounce = bounce;
1922 ctx->nlb = nlb;
1923 ctx->copies = 1;
1925 req->opaque = ctx;
1927 for (i = 0; i < nr; i++) {
1928 uint64_t slba = le64_to_cpu(range[i].slba);
1929 uint32_t nlb = le16_to_cpu(range[i].nlb) + 1;
1931 size_t len = nvme_l2b(ns, nlb);
1932 int64_t offset = nvme_l2b(ns, slba);
1934 trace_pci_nvme_copy_source_range(slba, nlb);
1936 struct nvme_copy_in_ctx *in_ctx = g_new(struct nvme_copy_in_ctx, 1);
1937 in_ctx->req = req;
1939 qemu_iovec_init(&in_ctx->iov, 1);
1940 qemu_iovec_add(&in_ctx->iov, bouncep, len);
1942 ctx->copies++;
1944 blk_aio_preadv(ns->blkconf.blk, offset, &in_ctx->iov, 0,
1945 nvme_aio_copy_in_cb, in_ctx);
1947 bouncep += len;
1950 /* account for the 1-initialization */
1951 ctx->copies--;
1953 if (!ctx->copies) {
1954 nvme_copy_in_complete(req);
1957 return NVME_NO_COMPLETE;
1960 static uint16_t nvme_compare(NvmeCtrl *n, NvmeRequest *req)
1962 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1963 NvmeNamespace *ns = req->ns;
1964 BlockBackend *blk = ns->blkconf.blk;
1965 uint64_t slba = le64_to_cpu(rw->slba);
1966 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
1967 size_t len = nvme_l2b(ns, nlb);
1968 int64_t offset = nvme_l2b(ns, slba);
1969 uint8_t *bounce = NULL;
1970 struct nvme_compare_ctx *ctx = NULL;
1971 uint16_t status;
1973 trace_pci_nvme_compare(nvme_cid(req), nvme_nsid(ns), slba, nlb);
1975 status = nvme_check_mdts(n, len);
1976 if (status) {
1977 return status;
1980 status = nvme_check_bounds(ns, slba, nlb);
1981 if (status) {
1982 trace_pci_nvme_err_invalid_lba_range(slba, nlb, ns->id_ns.nsze);
1983 return status;
1986 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
1987 status = nvme_check_dulbe(ns, slba, nlb);
1988 if (status) {
1989 return status;
1993 bounce = g_malloc(len);
1995 ctx = g_new(struct nvme_compare_ctx, 1);
1996 ctx->bounce = bounce;
1998 req->opaque = ctx;
2000 qemu_iovec_init(&ctx->iov, 1);
2001 qemu_iovec_add(&ctx->iov, bounce, len);
2003 block_acct_start(blk_get_stats(blk), &req->acct, len, BLOCK_ACCT_READ);
2004 blk_aio_preadv(blk, offset, &ctx->iov, 0, nvme_compare_cb, req);
2006 return NVME_NO_COMPLETE;
2009 static uint16_t nvme_flush(NvmeCtrl *n, NvmeRequest *req)
2011 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
2012 uintptr_t *num_flushes = (uintptr_t *)&req->opaque;
2013 uint16_t status;
2014 struct nvme_aio_flush_ctx *ctx;
2015 NvmeNamespace *ns;
2017 trace_pci_nvme_flush(nvme_cid(req), nsid);
2019 if (nsid != NVME_NSID_BROADCAST) {
2020 req->ns = nvme_ns(n, nsid);
2021 if (unlikely(!req->ns)) {
2022 return NVME_INVALID_FIELD | NVME_DNR;
2025 block_acct_start(blk_get_stats(req->ns->blkconf.blk), &req->acct, 0,
2026 BLOCK_ACCT_FLUSH);
2027 req->aiocb = blk_aio_flush(req->ns->blkconf.blk, nvme_rw_cb, req);
2028 return NVME_NO_COMPLETE;
2031 /* 1-initialize; see comment in nvme_dsm */
2032 *num_flushes = 1;
2034 for (int i = 1; i <= n->num_namespaces; i++) {
2035 ns = nvme_ns(n, i);
2036 if (!ns) {
2037 continue;
2040 ctx = g_new(struct nvme_aio_flush_ctx, 1);
2041 ctx->req = req;
2042 ctx->ns = ns;
2044 (*num_flushes)++;
2046 block_acct_start(blk_get_stats(ns->blkconf.blk), &ctx->acct, 0,
2047 BLOCK_ACCT_FLUSH);
2048 blk_aio_flush(ns->blkconf.blk, nvme_aio_flush_cb, ctx);
2051 /* account for the 1-initialization */
2052 (*num_flushes)--;
2054 if (*num_flushes) {
2055 status = NVME_NO_COMPLETE;
2056 } else {
2057 status = req->status;
2060 return status;
2063 static uint16_t nvme_read(NvmeCtrl *n, NvmeRequest *req)
2065 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2066 NvmeNamespace *ns = req->ns;
2067 uint64_t slba = le64_to_cpu(rw->slba);
2068 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
2069 uint64_t data_size = nvme_l2b(ns, nlb);
2070 uint64_t data_offset;
2071 BlockBackend *blk = ns->blkconf.blk;
2072 uint16_t status;
2074 trace_pci_nvme_read(nvme_cid(req), nvme_nsid(ns), nlb, data_size, slba);
2076 status = nvme_check_mdts(n, data_size);
2077 if (status) {
2078 goto invalid;
2081 status = nvme_check_bounds(ns, slba, nlb);
2082 if (status) {
2083 trace_pci_nvme_err_invalid_lba_range(slba, nlb, ns->id_ns.nsze);
2084 goto invalid;
2087 if (ns->params.zoned) {
2088 status = nvme_check_zone_read(ns, slba, nlb);
2089 if (status) {
2090 trace_pci_nvme_err_zone_read_not_ok(slba, nlb, status);
2091 goto invalid;
2095 status = nvme_map_dptr(n, &req->sg, data_size, &req->cmd);
2096 if (status) {
2097 goto invalid;
2100 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
2101 status = nvme_check_dulbe(ns, slba, nlb);
2102 if (status) {
2103 goto invalid;
2107 data_offset = nvme_l2b(ns, slba);
2109 block_acct_start(blk_get_stats(blk), &req->acct, data_size,
2110 BLOCK_ACCT_READ);
2111 nvme_blk_read(blk, data_offset, nvme_rw_cb, req);
2112 return NVME_NO_COMPLETE;
2114 invalid:
2115 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
2116 return status | NVME_DNR;
2119 static uint16_t nvme_do_write(NvmeCtrl *n, NvmeRequest *req, bool append,
2120 bool wrz)
2122 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2123 NvmeNamespace *ns = req->ns;
2124 uint64_t slba = le64_to_cpu(rw->slba);
2125 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
2126 uint64_t data_size = nvme_l2b(ns, nlb);
2127 uint64_t data_offset;
2128 NvmeZone *zone;
2129 NvmeZonedResult *res = (NvmeZonedResult *)&req->cqe;
2130 BlockBackend *blk = ns->blkconf.blk;
2131 uint16_t status;
2133 trace_pci_nvme_write(nvme_cid(req), nvme_io_opc_str(rw->opcode),
2134 nvme_nsid(ns), nlb, data_size, slba);
2136 if (!wrz) {
2137 status = nvme_check_mdts(n, data_size);
2138 if (status) {
2139 goto invalid;
2143 status = nvme_check_bounds(ns, slba, nlb);
2144 if (status) {
2145 trace_pci_nvme_err_invalid_lba_range(slba, nlb, ns->id_ns.nsze);
2146 goto invalid;
2149 if (ns->params.zoned) {
2150 zone = nvme_get_zone_by_slba(ns, slba);
2152 if (append) {
2153 if (unlikely(slba != zone->d.zslba)) {
2154 trace_pci_nvme_err_append_not_at_start(slba, zone->d.zslba);
2155 status = NVME_INVALID_FIELD;
2156 goto invalid;
2159 if (n->params.zasl && data_size > n->page_size << n->params.zasl) {
2160 trace_pci_nvme_err_zasl(data_size);
2161 return NVME_INVALID_FIELD | NVME_DNR;
2164 slba = zone->w_ptr;
2165 res->slba = cpu_to_le64(slba);
2168 status = nvme_check_zone_write(ns, zone, slba, nlb);
2169 if (status) {
2170 goto invalid;
2173 status = nvme_zrm_auto(ns, zone);
2174 if (status) {
2175 goto invalid;
2178 zone->w_ptr += nlb;
2181 data_offset = nvme_l2b(ns, slba);
2183 if (!wrz) {
2184 status = nvme_map_dptr(n, &req->sg, data_size, &req->cmd);
2185 if (status) {
2186 goto invalid;
2189 block_acct_start(blk_get_stats(blk), &req->acct, data_size,
2190 BLOCK_ACCT_WRITE);
2191 nvme_blk_write(blk, data_offset, nvme_rw_cb, req);
2192 } else {
2193 req->aiocb = blk_aio_pwrite_zeroes(blk, data_offset, data_size,
2194 BDRV_REQ_MAY_UNMAP, nvme_rw_cb,
2195 req);
2197 return NVME_NO_COMPLETE;
2199 invalid:
2200 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
2201 return status | NVME_DNR;
2204 static inline uint16_t nvme_write(NvmeCtrl *n, NvmeRequest *req)
2206 return nvme_do_write(n, req, false, false);
2209 static inline uint16_t nvme_write_zeroes(NvmeCtrl *n, NvmeRequest *req)
2211 return nvme_do_write(n, req, false, true);
2214 static inline uint16_t nvme_zone_append(NvmeCtrl *n, NvmeRequest *req)
2216 return nvme_do_write(n, req, true, false);
2219 static uint16_t nvme_get_mgmt_zone_slba_idx(NvmeNamespace *ns, NvmeCmd *c,
2220 uint64_t *slba, uint32_t *zone_idx)
2222 uint32_t dw10 = le32_to_cpu(c->cdw10);
2223 uint32_t dw11 = le32_to_cpu(c->cdw11);
2225 if (!ns->params.zoned) {
2226 trace_pci_nvme_err_invalid_opc(c->opcode);
2227 return NVME_INVALID_OPCODE | NVME_DNR;
2230 *slba = ((uint64_t)dw11) << 32 | dw10;
2231 if (unlikely(*slba >= ns->id_ns.nsze)) {
2232 trace_pci_nvme_err_invalid_lba_range(*slba, 0, ns->id_ns.nsze);
2233 *slba = 0;
2234 return NVME_LBA_RANGE | NVME_DNR;
2237 *zone_idx = nvme_zone_idx(ns, *slba);
2238 assert(*zone_idx < ns->num_zones);
2240 return NVME_SUCCESS;
2243 typedef uint16_t (*op_handler_t)(NvmeNamespace *, NvmeZone *, NvmeZoneState,
2244 NvmeRequest *);
2246 enum NvmeZoneProcessingMask {
2247 NVME_PROC_CURRENT_ZONE = 0,
2248 NVME_PROC_OPENED_ZONES = 1 << 0,
2249 NVME_PROC_CLOSED_ZONES = 1 << 1,
2250 NVME_PROC_READ_ONLY_ZONES = 1 << 2,
2251 NVME_PROC_FULL_ZONES = 1 << 3,
2254 static uint16_t nvme_open_zone(NvmeNamespace *ns, NvmeZone *zone,
2255 NvmeZoneState state, NvmeRequest *req)
2257 return nvme_zrm_open(ns, zone);
2260 static uint16_t nvme_close_zone(NvmeNamespace *ns, NvmeZone *zone,
2261 NvmeZoneState state, NvmeRequest *req)
2263 return nvme_zrm_close(ns, zone);
2266 static uint16_t nvme_finish_zone(NvmeNamespace *ns, NvmeZone *zone,
2267 NvmeZoneState state, NvmeRequest *req)
2269 return nvme_zrm_finish(ns, zone);
2272 static uint16_t nvme_reset_zone(NvmeNamespace *ns, NvmeZone *zone,
2273 NvmeZoneState state, NvmeRequest *req)
2275 uintptr_t *resets = (uintptr_t *)&req->opaque;
2276 struct nvme_zone_reset_ctx *ctx;
2278 switch (state) {
2279 case NVME_ZONE_STATE_EMPTY:
2280 return NVME_SUCCESS;
2281 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
2282 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
2283 case NVME_ZONE_STATE_CLOSED:
2284 case NVME_ZONE_STATE_FULL:
2285 break;
2286 default:
2287 return NVME_ZONE_INVAL_TRANSITION;
2291 * The zone reset aio callback needs to know the zone that is being reset
2292 * in order to transition the zone on completion.
2294 ctx = g_new(struct nvme_zone_reset_ctx, 1);
2295 ctx->req = req;
2296 ctx->zone = zone;
2298 (*resets)++;
2300 blk_aio_pwrite_zeroes(ns->blkconf.blk, nvme_l2b(ns, zone->d.zslba),
2301 nvme_l2b(ns, ns->zone_size), BDRV_REQ_MAY_UNMAP,
2302 nvme_aio_zone_reset_cb, ctx);
2304 return NVME_NO_COMPLETE;
2307 static uint16_t nvme_offline_zone(NvmeNamespace *ns, NvmeZone *zone,
2308 NvmeZoneState state, NvmeRequest *req)
2310 switch (state) {
2311 case NVME_ZONE_STATE_READ_ONLY:
2312 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_OFFLINE);
2313 /* fall through */
2314 case NVME_ZONE_STATE_OFFLINE:
2315 return NVME_SUCCESS;
2316 default:
2317 return NVME_ZONE_INVAL_TRANSITION;
2321 static uint16_t nvme_set_zd_ext(NvmeNamespace *ns, NvmeZone *zone)
2323 uint16_t status;
2324 uint8_t state = nvme_get_zone_state(zone);
2326 if (state == NVME_ZONE_STATE_EMPTY) {
2327 status = nvme_aor_check(ns, 1, 0);
2328 if (status) {
2329 return status;
2331 nvme_aor_inc_active(ns);
2332 zone->d.za |= NVME_ZA_ZD_EXT_VALID;
2333 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
2334 return NVME_SUCCESS;
2337 return NVME_ZONE_INVAL_TRANSITION;
2340 static uint16_t nvme_bulk_proc_zone(NvmeNamespace *ns, NvmeZone *zone,
2341 enum NvmeZoneProcessingMask proc_mask,
2342 op_handler_t op_hndlr, NvmeRequest *req)
2344 uint16_t status = NVME_SUCCESS;
2345 NvmeZoneState zs = nvme_get_zone_state(zone);
2346 bool proc_zone;
2348 switch (zs) {
2349 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
2350 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
2351 proc_zone = proc_mask & NVME_PROC_OPENED_ZONES;
2352 break;
2353 case NVME_ZONE_STATE_CLOSED:
2354 proc_zone = proc_mask & NVME_PROC_CLOSED_ZONES;
2355 break;
2356 case NVME_ZONE_STATE_READ_ONLY:
2357 proc_zone = proc_mask & NVME_PROC_READ_ONLY_ZONES;
2358 break;
2359 case NVME_ZONE_STATE_FULL:
2360 proc_zone = proc_mask & NVME_PROC_FULL_ZONES;
2361 break;
2362 default:
2363 proc_zone = false;
2366 if (proc_zone) {
2367 status = op_hndlr(ns, zone, zs, req);
2370 return status;
2373 static uint16_t nvme_do_zone_op(NvmeNamespace *ns, NvmeZone *zone,
2374 enum NvmeZoneProcessingMask proc_mask,
2375 op_handler_t op_hndlr, NvmeRequest *req)
2377 NvmeZone *next;
2378 uint16_t status = NVME_SUCCESS;
2379 int i;
2381 if (!proc_mask) {
2382 status = op_hndlr(ns, zone, nvme_get_zone_state(zone), req);
2383 } else {
2384 if (proc_mask & NVME_PROC_CLOSED_ZONES) {
2385 QTAILQ_FOREACH_SAFE(zone, &ns->closed_zones, entry, next) {
2386 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
2387 req);
2388 if (status && status != NVME_NO_COMPLETE) {
2389 goto out;
2393 if (proc_mask & NVME_PROC_OPENED_ZONES) {
2394 QTAILQ_FOREACH_SAFE(zone, &ns->imp_open_zones, entry, next) {
2395 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
2396 req);
2397 if (status && status != NVME_NO_COMPLETE) {
2398 goto out;
2402 QTAILQ_FOREACH_SAFE(zone, &ns->exp_open_zones, entry, next) {
2403 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
2404 req);
2405 if (status && status != NVME_NO_COMPLETE) {
2406 goto out;
2410 if (proc_mask & NVME_PROC_FULL_ZONES) {
2411 QTAILQ_FOREACH_SAFE(zone, &ns->full_zones, entry, next) {
2412 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
2413 req);
2414 if (status && status != NVME_NO_COMPLETE) {
2415 goto out;
2420 if (proc_mask & NVME_PROC_READ_ONLY_ZONES) {
2421 for (i = 0; i < ns->num_zones; i++, zone++) {
2422 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
2423 req);
2424 if (status && status != NVME_NO_COMPLETE) {
2425 goto out;
2431 out:
2432 return status;
2435 static uint16_t nvme_zone_mgmt_send(NvmeCtrl *n, NvmeRequest *req)
2437 NvmeCmd *cmd = (NvmeCmd *)&req->cmd;
2438 NvmeNamespace *ns = req->ns;
2439 NvmeZone *zone;
2440 uintptr_t *resets;
2441 uint8_t *zd_ext;
2442 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
2443 uint64_t slba = 0;
2444 uint32_t zone_idx = 0;
2445 uint16_t status;
2446 uint8_t action;
2447 bool all;
2448 enum NvmeZoneProcessingMask proc_mask = NVME_PROC_CURRENT_ZONE;
2450 action = dw13 & 0xff;
2451 all = dw13 & 0x100;
2453 req->status = NVME_SUCCESS;
2455 if (!all) {
2456 status = nvme_get_mgmt_zone_slba_idx(ns, cmd, &slba, &zone_idx);
2457 if (status) {
2458 return status;
2462 zone = &ns->zone_array[zone_idx];
2463 if (slba != zone->d.zslba) {
2464 trace_pci_nvme_err_unaligned_zone_cmd(action, slba, zone->d.zslba);
2465 return NVME_INVALID_FIELD | NVME_DNR;
2468 switch (action) {
2470 case NVME_ZONE_ACTION_OPEN:
2471 if (all) {
2472 proc_mask = NVME_PROC_CLOSED_ZONES;
2474 trace_pci_nvme_open_zone(slba, zone_idx, all);
2475 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_open_zone, req);
2476 break;
2478 case NVME_ZONE_ACTION_CLOSE:
2479 if (all) {
2480 proc_mask = NVME_PROC_OPENED_ZONES;
2482 trace_pci_nvme_close_zone(slba, zone_idx, all);
2483 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_close_zone, req);
2484 break;
2486 case NVME_ZONE_ACTION_FINISH:
2487 if (all) {
2488 proc_mask = NVME_PROC_OPENED_ZONES | NVME_PROC_CLOSED_ZONES;
2490 trace_pci_nvme_finish_zone(slba, zone_idx, all);
2491 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_finish_zone, req);
2492 break;
2494 case NVME_ZONE_ACTION_RESET:
2495 resets = (uintptr_t *)&req->opaque;
2497 if (all) {
2498 proc_mask = NVME_PROC_OPENED_ZONES | NVME_PROC_CLOSED_ZONES |
2499 NVME_PROC_FULL_ZONES;
2501 trace_pci_nvme_reset_zone(slba, zone_idx, all);
2503 *resets = 1;
2505 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_reset_zone, req);
2507 (*resets)--;
2509 return *resets ? NVME_NO_COMPLETE : req->status;
2511 case NVME_ZONE_ACTION_OFFLINE:
2512 if (all) {
2513 proc_mask = NVME_PROC_READ_ONLY_ZONES;
2515 trace_pci_nvme_offline_zone(slba, zone_idx, all);
2516 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_offline_zone, req);
2517 break;
2519 case NVME_ZONE_ACTION_SET_ZD_EXT:
2520 trace_pci_nvme_set_descriptor_extension(slba, zone_idx);
2521 if (all || !ns->params.zd_extension_size) {
2522 return NVME_INVALID_FIELD | NVME_DNR;
2524 zd_ext = nvme_get_zd_extension(ns, zone_idx);
2525 status = nvme_dma(n, zd_ext, ns->params.zd_extension_size,
2526 DMA_DIRECTION_TO_DEVICE, req);
2527 if (status) {
2528 trace_pci_nvme_err_zd_extension_map_error(zone_idx);
2529 return status;
2532 status = nvme_set_zd_ext(ns, zone);
2533 if (status == NVME_SUCCESS) {
2534 trace_pci_nvme_zd_extension_set(zone_idx);
2535 return status;
2537 break;
2539 default:
2540 trace_pci_nvme_err_invalid_mgmt_action(action);
2541 status = NVME_INVALID_FIELD;
2544 if (status == NVME_ZONE_INVAL_TRANSITION) {
2545 trace_pci_nvme_err_invalid_zone_state_transition(action, slba,
2546 zone->d.za);
2548 if (status) {
2549 status |= NVME_DNR;
2552 return status;
2555 static bool nvme_zone_matches_filter(uint32_t zafs, NvmeZone *zl)
2557 NvmeZoneState zs = nvme_get_zone_state(zl);
2559 switch (zafs) {
2560 case NVME_ZONE_REPORT_ALL:
2561 return true;
2562 case NVME_ZONE_REPORT_EMPTY:
2563 return zs == NVME_ZONE_STATE_EMPTY;
2564 case NVME_ZONE_REPORT_IMPLICITLY_OPEN:
2565 return zs == NVME_ZONE_STATE_IMPLICITLY_OPEN;
2566 case NVME_ZONE_REPORT_EXPLICITLY_OPEN:
2567 return zs == NVME_ZONE_STATE_EXPLICITLY_OPEN;
2568 case NVME_ZONE_REPORT_CLOSED:
2569 return zs == NVME_ZONE_STATE_CLOSED;
2570 case NVME_ZONE_REPORT_FULL:
2571 return zs == NVME_ZONE_STATE_FULL;
2572 case NVME_ZONE_REPORT_READ_ONLY:
2573 return zs == NVME_ZONE_STATE_READ_ONLY;
2574 case NVME_ZONE_REPORT_OFFLINE:
2575 return zs == NVME_ZONE_STATE_OFFLINE;
2576 default:
2577 return false;
2581 static uint16_t nvme_zone_mgmt_recv(NvmeCtrl *n, NvmeRequest *req)
2583 NvmeCmd *cmd = (NvmeCmd *)&req->cmd;
2584 NvmeNamespace *ns = req->ns;
2585 /* cdw12 is zero-based number of dwords to return. Convert to bytes */
2586 uint32_t data_size = (le32_to_cpu(cmd->cdw12) + 1) << 2;
2587 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
2588 uint32_t zone_idx, zra, zrasf, partial;
2589 uint64_t max_zones, nr_zones = 0;
2590 uint16_t status;
2591 uint64_t slba, capacity = nvme_ns_nlbas(ns);
2592 NvmeZoneDescr *z;
2593 NvmeZone *zone;
2594 NvmeZoneReportHeader *header;
2595 void *buf, *buf_p;
2596 size_t zone_entry_sz;
2598 req->status = NVME_SUCCESS;
2600 status = nvme_get_mgmt_zone_slba_idx(ns, cmd, &slba, &zone_idx);
2601 if (status) {
2602 return status;
2605 zra = dw13 & 0xff;
2606 if (zra != NVME_ZONE_REPORT && zra != NVME_ZONE_REPORT_EXTENDED) {
2607 return NVME_INVALID_FIELD | NVME_DNR;
2609 if (zra == NVME_ZONE_REPORT_EXTENDED && !ns->params.zd_extension_size) {
2610 return NVME_INVALID_FIELD | NVME_DNR;
2613 zrasf = (dw13 >> 8) & 0xff;
2614 if (zrasf > NVME_ZONE_REPORT_OFFLINE) {
2615 return NVME_INVALID_FIELD | NVME_DNR;
2618 if (data_size < sizeof(NvmeZoneReportHeader)) {
2619 return NVME_INVALID_FIELD | NVME_DNR;
2622 status = nvme_check_mdts(n, data_size);
2623 if (status) {
2624 return status;
2627 partial = (dw13 >> 16) & 0x01;
2629 zone_entry_sz = sizeof(NvmeZoneDescr);
2630 if (zra == NVME_ZONE_REPORT_EXTENDED) {
2631 zone_entry_sz += ns->params.zd_extension_size;
2634 max_zones = (data_size - sizeof(NvmeZoneReportHeader)) / zone_entry_sz;
2635 buf = g_malloc0(data_size);
2637 zone = &ns->zone_array[zone_idx];
2638 for (; slba < capacity; slba += ns->zone_size) {
2639 if (partial && nr_zones >= max_zones) {
2640 break;
2642 if (nvme_zone_matches_filter(zrasf, zone++)) {
2643 nr_zones++;
2646 header = (NvmeZoneReportHeader *)buf;
2647 header->nr_zones = cpu_to_le64(nr_zones);
2649 buf_p = buf + sizeof(NvmeZoneReportHeader);
2650 for (; zone_idx < ns->num_zones && max_zones > 0; zone_idx++) {
2651 zone = &ns->zone_array[zone_idx];
2652 if (nvme_zone_matches_filter(zrasf, zone)) {
2653 z = (NvmeZoneDescr *)buf_p;
2654 buf_p += sizeof(NvmeZoneDescr);
2656 z->zt = zone->d.zt;
2657 z->zs = zone->d.zs;
2658 z->zcap = cpu_to_le64(zone->d.zcap);
2659 z->zslba = cpu_to_le64(zone->d.zslba);
2660 z->za = zone->d.za;
2662 if (nvme_wp_is_valid(zone)) {
2663 z->wp = cpu_to_le64(zone->d.wp);
2664 } else {
2665 z->wp = cpu_to_le64(~0ULL);
2668 if (zra == NVME_ZONE_REPORT_EXTENDED) {
2669 if (zone->d.za & NVME_ZA_ZD_EXT_VALID) {
2670 memcpy(buf_p, nvme_get_zd_extension(ns, zone_idx),
2671 ns->params.zd_extension_size);
2673 buf_p += ns->params.zd_extension_size;
2676 max_zones--;
2680 status = nvme_dma(n, (uint8_t *)buf, data_size,
2681 DMA_DIRECTION_FROM_DEVICE, req);
2683 g_free(buf);
2685 return status;
2688 static uint16_t nvme_io_cmd(NvmeCtrl *n, NvmeRequest *req)
2690 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
2692 trace_pci_nvme_io_cmd(nvme_cid(req), nsid, nvme_sqid(req),
2693 req->cmd.opcode, nvme_io_opc_str(req->cmd.opcode));
2695 if (!nvme_nsid_valid(n, nsid)) {
2696 return NVME_INVALID_NSID | NVME_DNR;
2700 * In the base NVM command set, Flush may apply to all namespaces
2701 * (indicated by NSID being set to 0xFFFFFFFF). But if that feature is used
2702 * along with TP 4056 (Namespace Types), it may be pretty screwed up.
2704 * If NSID is indeed set to 0xFFFFFFFF, we simply cannot associate the
2705 * opcode with a specific command since we cannot determine a unique I/O
2706 * command set. Opcode 0x0 could have any other meaning than something
2707 * equivalent to flushing and say it DOES have completely different
2708 * semantics in some other command set - does an NSID of 0xFFFFFFFF then
2709 * mean "for all namespaces, apply whatever command set specific command
2710 * that uses the 0x0 opcode?" Or does it mean "for all namespaces, apply
2711 * whatever command that uses the 0x0 opcode if, and only if, it allows
2712 * NSID to be 0xFFFFFFFF"?
2714 * Anyway (and luckily), for now, we do not care about this since the
2715 * device only supports namespace types that includes the NVM Flush command
2716 * (NVM and Zoned), so always do an NVM Flush.
2718 if (req->cmd.opcode == NVME_CMD_FLUSH) {
2719 return nvme_flush(n, req);
2722 req->ns = nvme_ns(n, nsid);
2723 if (unlikely(!req->ns)) {
2724 return NVME_INVALID_FIELD | NVME_DNR;
2727 if (!(req->ns->iocs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
2728 trace_pci_nvme_err_invalid_opc(req->cmd.opcode);
2729 return NVME_INVALID_OPCODE | NVME_DNR;
2732 switch (req->cmd.opcode) {
2733 case NVME_CMD_WRITE_ZEROES:
2734 return nvme_write_zeroes(n, req);
2735 case NVME_CMD_ZONE_APPEND:
2736 return nvme_zone_append(n, req);
2737 case NVME_CMD_WRITE:
2738 return nvme_write(n, req);
2739 case NVME_CMD_READ:
2740 return nvme_read(n, req);
2741 case NVME_CMD_COMPARE:
2742 return nvme_compare(n, req);
2743 case NVME_CMD_DSM:
2744 return nvme_dsm(n, req);
2745 case NVME_CMD_COPY:
2746 return nvme_copy(n, req);
2747 case NVME_CMD_ZONE_MGMT_SEND:
2748 return nvme_zone_mgmt_send(n, req);
2749 case NVME_CMD_ZONE_MGMT_RECV:
2750 return nvme_zone_mgmt_recv(n, req);
2751 default:
2752 assert(false);
2755 return NVME_INVALID_OPCODE | NVME_DNR;
2758 static void nvme_free_sq(NvmeSQueue *sq, NvmeCtrl *n)
2760 n->sq[sq->sqid] = NULL;
2761 timer_free(sq->timer);
2762 g_free(sq->io_req);
2763 if (sq->sqid) {
2764 g_free(sq);
2768 static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeRequest *req)
2770 NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
2771 NvmeRequest *r, *next;
2772 NvmeSQueue *sq;
2773 NvmeCQueue *cq;
2774 uint16_t qid = le16_to_cpu(c->qid);
2776 if (unlikely(!qid || nvme_check_sqid(n, qid))) {
2777 trace_pci_nvme_err_invalid_del_sq(qid);
2778 return NVME_INVALID_QID | NVME_DNR;
2781 trace_pci_nvme_del_sq(qid);
2783 sq = n->sq[qid];
2784 while (!QTAILQ_EMPTY(&sq->out_req_list)) {
2785 r = QTAILQ_FIRST(&sq->out_req_list);
2786 assert(r->aiocb);
2787 blk_aio_cancel(r->aiocb);
2789 if (!nvme_check_cqid(n, sq->cqid)) {
2790 cq = n->cq[sq->cqid];
2791 QTAILQ_REMOVE(&cq->sq_list, sq, entry);
2793 nvme_post_cqes(cq);
2794 QTAILQ_FOREACH_SAFE(r, &cq->req_list, entry, next) {
2795 if (r->sq == sq) {
2796 QTAILQ_REMOVE(&cq->req_list, r, entry);
2797 QTAILQ_INSERT_TAIL(&sq->req_list, r, entry);
2802 nvme_free_sq(sq, n);
2803 return NVME_SUCCESS;
2806 static void nvme_init_sq(NvmeSQueue *sq, NvmeCtrl *n, uint64_t dma_addr,
2807 uint16_t sqid, uint16_t cqid, uint16_t size)
2809 int i;
2810 NvmeCQueue *cq;
2812 sq->ctrl = n;
2813 sq->dma_addr = dma_addr;
2814 sq->sqid = sqid;
2815 sq->size = size;
2816 sq->cqid = cqid;
2817 sq->head = sq->tail = 0;
2818 sq->io_req = g_new0(NvmeRequest, sq->size);
2820 QTAILQ_INIT(&sq->req_list);
2821 QTAILQ_INIT(&sq->out_req_list);
2822 for (i = 0; i < sq->size; i++) {
2823 sq->io_req[i].sq = sq;
2824 QTAILQ_INSERT_TAIL(&(sq->req_list), &sq->io_req[i], entry);
2826 sq->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, nvme_process_sq, sq);
2828 assert(n->cq[cqid]);
2829 cq = n->cq[cqid];
2830 QTAILQ_INSERT_TAIL(&(cq->sq_list), sq, entry);
2831 n->sq[sqid] = sq;
2834 static uint16_t nvme_create_sq(NvmeCtrl *n, NvmeRequest *req)
2836 NvmeSQueue *sq;
2837 NvmeCreateSq *c = (NvmeCreateSq *)&req->cmd;
2839 uint16_t cqid = le16_to_cpu(c->cqid);
2840 uint16_t sqid = le16_to_cpu(c->sqid);
2841 uint16_t qsize = le16_to_cpu(c->qsize);
2842 uint16_t qflags = le16_to_cpu(c->sq_flags);
2843 uint64_t prp1 = le64_to_cpu(c->prp1);
2845 trace_pci_nvme_create_sq(prp1, sqid, cqid, qsize, qflags);
2847 if (unlikely(!cqid || nvme_check_cqid(n, cqid))) {
2848 trace_pci_nvme_err_invalid_create_sq_cqid(cqid);
2849 return NVME_INVALID_CQID | NVME_DNR;
2851 if (unlikely(!sqid || sqid > n->params.max_ioqpairs ||
2852 n->sq[sqid] != NULL)) {
2853 trace_pci_nvme_err_invalid_create_sq_sqid(sqid);
2854 return NVME_INVALID_QID | NVME_DNR;
2856 if (unlikely(!qsize || qsize > NVME_CAP_MQES(n->bar.cap))) {
2857 trace_pci_nvme_err_invalid_create_sq_size(qsize);
2858 return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
2860 if (unlikely(prp1 & (n->page_size - 1))) {
2861 trace_pci_nvme_err_invalid_create_sq_addr(prp1);
2862 return NVME_INVALID_PRP_OFFSET | NVME_DNR;
2864 if (unlikely(!(NVME_SQ_FLAGS_PC(qflags)))) {
2865 trace_pci_nvme_err_invalid_create_sq_qflags(NVME_SQ_FLAGS_PC(qflags));
2866 return NVME_INVALID_FIELD | NVME_DNR;
2868 sq = g_malloc0(sizeof(*sq));
2869 nvme_init_sq(sq, n, prp1, sqid, cqid, qsize + 1);
2870 return NVME_SUCCESS;
2873 struct nvme_stats {
2874 uint64_t units_read;
2875 uint64_t units_written;
2876 uint64_t read_commands;
2877 uint64_t write_commands;
2880 static void nvme_set_blk_stats(NvmeNamespace *ns, struct nvme_stats *stats)
2882 BlockAcctStats *s = blk_get_stats(ns->blkconf.blk);
2884 stats->units_read += s->nr_bytes[BLOCK_ACCT_READ] >> BDRV_SECTOR_BITS;
2885 stats->units_written += s->nr_bytes[BLOCK_ACCT_WRITE] >> BDRV_SECTOR_BITS;
2886 stats->read_commands += s->nr_ops[BLOCK_ACCT_READ];
2887 stats->write_commands += s->nr_ops[BLOCK_ACCT_WRITE];
2890 static uint16_t nvme_smart_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
2891 uint64_t off, NvmeRequest *req)
2893 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
2894 struct nvme_stats stats = { 0 };
2895 NvmeSmartLog smart = { 0 };
2896 uint32_t trans_len;
2897 NvmeNamespace *ns;
2898 time_t current_ms;
2900 if (off >= sizeof(smart)) {
2901 return NVME_INVALID_FIELD | NVME_DNR;
2904 if (nsid != 0xffffffff) {
2905 ns = nvme_ns(n, nsid);
2906 if (!ns) {
2907 return NVME_INVALID_NSID | NVME_DNR;
2909 nvme_set_blk_stats(ns, &stats);
2910 } else {
2911 int i;
2913 for (i = 1; i <= n->num_namespaces; i++) {
2914 ns = nvme_ns(n, i);
2915 if (!ns) {
2916 continue;
2918 nvme_set_blk_stats(ns, &stats);
2922 trans_len = MIN(sizeof(smart) - off, buf_len);
2923 smart.critical_warning = n->smart_critical_warning;
2925 smart.data_units_read[0] = cpu_to_le64(DIV_ROUND_UP(stats.units_read,
2926 1000));
2927 smart.data_units_written[0] = cpu_to_le64(DIV_ROUND_UP(stats.units_written,
2928 1000));
2929 smart.host_read_commands[0] = cpu_to_le64(stats.read_commands);
2930 smart.host_write_commands[0] = cpu_to_le64(stats.write_commands);
2932 smart.temperature = cpu_to_le16(n->temperature);
2934 if ((n->temperature >= n->features.temp_thresh_hi) ||
2935 (n->temperature <= n->features.temp_thresh_low)) {
2936 smart.critical_warning |= NVME_SMART_TEMPERATURE;
2939 current_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
2940 smart.power_on_hours[0] =
2941 cpu_to_le64((((current_ms - n->starttime_ms) / 1000) / 60) / 60);
2943 if (!rae) {
2944 nvme_clear_events(n, NVME_AER_TYPE_SMART);
2947 return nvme_dma(n, (uint8_t *) &smart + off, trans_len,
2948 DMA_DIRECTION_FROM_DEVICE, req);
2951 static uint16_t nvme_fw_log_info(NvmeCtrl *n, uint32_t buf_len, uint64_t off,
2952 NvmeRequest *req)
2954 uint32_t trans_len;
2955 NvmeFwSlotInfoLog fw_log = {
2956 .afi = 0x1,
2959 if (off >= sizeof(fw_log)) {
2960 return NVME_INVALID_FIELD | NVME_DNR;
2963 strpadcpy((char *)&fw_log.frs1, sizeof(fw_log.frs1), "1.0", ' ');
2964 trans_len = MIN(sizeof(fw_log) - off, buf_len);
2966 return nvme_dma(n, (uint8_t *) &fw_log + off, trans_len,
2967 DMA_DIRECTION_FROM_DEVICE, req);
2970 static uint16_t nvme_error_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
2971 uint64_t off, NvmeRequest *req)
2973 uint32_t trans_len;
2974 NvmeErrorLog errlog;
2976 if (off >= sizeof(errlog)) {
2977 return NVME_INVALID_FIELD | NVME_DNR;
2980 if (!rae) {
2981 nvme_clear_events(n, NVME_AER_TYPE_ERROR);
2984 memset(&errlog, 0x0, sizeof(errlog));
2985 trans_len = MIN(sizeof(errlog) - off, buf_len);
2987 return nvme_dma(n, (uint8_t *)&errlog, trans_len,
2988 DMA_DIRECTION_FROM_DEVICE, req);
2991 static uint16_t nvme_cmd_effects(NvmeCtrl *n, uint8_t csi, uint32_t buf_len,
2992 uint64_t off, NvmeRequest *req)
2994 NvmeEffectsLog log = {};
2995 const uint32_t *src_iocs = NULL;
2996 uint32_t trans_len;
2998 if (off >= sizeof(log)) {
2999 trace_pci_nvme_err_invalid_log_page_offset(off, sizeof(log));
3000 return NVME_INVALID_FIELD | NVME_DNR;
3003 switch (NVME_CC_CSS(n->bar.cc)) {
3004 case NVME_CC_CSS_NVM:
3005 src_iocs = nvme_cse_iocs_nvm;
3006 /* fall through */
3007 case NVME_CC_CSS_ADMIN_ONLY:
3008 break;
3009 case NVME_CC_CSS_CSI:
3010 switch (csi) {
3011 case NVME_CSI_NVM:
3012 src_iocs = nvme_cse_iocs_nvm;
3013 break;
3014 case NVME_CSI_ZONED:
3015 src_iocs = nvme_cse_iocs_zoned;
3016 break;
3020 memcpy(log.acs, nvme_cse_acs, sizeof(nvme_cse_acs));
3022 if (src_iocs) {
3023 memcpy(log.iocs, src_iocs, sizeof(log.iocs));
3026 trans_len = MIN(sizeof(log) - off, buf_len);
3028 return nvme_dma(n, ((uint8_t *)&log) + off, trans_len,
3029 DMA_DIRECTION_FROM_DEVICE, req);
3032 static uint16_t nvme_get_log(NvmeCtrl *n, NvmeRequest *req)
3034 NvmeCmd *cmd = &req->cmd;
3036 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
3037 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
3038 uint32_t dw12 = le32_to_cpu(cmd->cdw12);
3039 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
3040 uint8_t lid = dw10 & 0xff;
3041 uint8_t lsp = (dw10 >> 8) & 0xf;
3042 uint8_t rae = (dw10 >> 15) & 0x1;
3043 uint8_t csi = le32_to_cpu(cmd->cdw14) >> 24;
3044 uint32_t numdl, numdu;
3045 uint64_t off, lpol, lpou;
3046 size_t len;
3047 uint16_t status;
3049 numdl = (dw10 >> 16);
3050 numdu = (dw11 & 0xffff);
3051 lpol = dw12;
3052 lpou = dw13;
3054 len = (((numdu << 16) | numdl) + 1) << 2;
3055 off = (lpou << 32ULL) | lpol;
3057 if (off & 0x3) {
3058 return NVME_INVALID_FIELD | NVME_DNR;
3061 trace_pci_nvme_get_log(nvme_cid(req), lid, lsp, rae, len, off);
3063 status = nvme_check_mdts(n, len);
3064 if (status) {
3065 return status;
3068 switch (lid) {
3069 case NVME_LOG_ERROR_INFO:
3070 return nvme_error_info(n, rae, len, off, req);
3071 case NVME_LOG_SMART_INFO:
3072 return nvme_smart_info(n, rae, len, off, req);
3073 case NVME_LOG_FW_SLOT_INFO:
3074 return nvme_fw_log_info(n, len, off, req);
3075 case NVME_LOG_CMD_EFFECTS:
3076 return nvme_cmd_effects(n, csi, len, off, req);
3077 default:
3078 trace_pci_nvme_err_invalid_log_page(nvme_cid(req), lid);
3079 return NVME_INVALID_FIELD | NVME_DNR;
3083 static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
3085 n->cq[cq->cqid] = NULL;
3086 timer_free(cq->timer);
3087 if (msix_enabled(&n->parent_obj)) {
3088 msix_vector_unuse(&n->parent_obj, cq->vector);
3090 if (cq->cqid) {
3091 g_free(cq);
3095 static uint16_t nvme_del_cq(NvmeCtrl *n, NvmeRequest *req)
3097 NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
3098 NvmeCQueue *cq;
3099 uint16_t qid = le16_to_cpu(c->qid);
3101 if (unlikely(!qid || nvme_check_cqid(n, qid))) {
3102 trace_pci_nvme_err_invalid_del_cq_cqid(qid);
3103 return NVME_INVALID_CQID | NVME_DNR;
3106 cq = n->cq[qid];
3107 if (unlikely(!QTAILQ_EMPTY(&cq->sq_list))) {
3108 trace_pci_nvme_err_invalid_del_cq_notempty(qid);
3109 return NVME_INVALID_QUEUE_DEL;
3111 nvme_irq_deassert(n, cq);
3112 trace_pci_nvme_del_cq(qid);
3113 nvme_free_cq(cq, n);
3114 return NVME_SUCCESS;
3117 static void nvme_init_cq(NvmeCQueue *cq, NvmeCtrl *n, uint64_t dma_addr,
3118 uint16_t cqid, uint16_t vector, uint16_t size,
3119 uint16_t irq_enabled)
3121 int ret;
3123 if (msix_enabled(&n->parent_obj)) {
3124 ret = msix_vector_use(&n->parent_obj, vector);
3125 assert(ret == 0);
3127 cq->ctrl = n;
3128 cq->cqid = cqid;
3129 cq->size = size;
3130 cq->dma_addr = dma_addr;
3131 cq->phase = 1;
3132 cq->irq_enabled = irq_enabled;
3133 cq->vector = vector;
3134 cq->head = cq->tail = 0;
3135 QTAILQ_INIT(&cq->req_list);
3136 QTAILQ_INIT(&cq->sq_list);
3137 n->cq[cqid] = cq;
3138 cq->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, nvme_post_cqes, cq);
3141 static uint16_t nvme_create_cq(NvmeCtrl *n, NvmeRequest *req)
3143 NvmeCQueue *cq;
3144 NvmeCreateCq *c = (NvmeCreateCq *)&req->cmd;
3145 uint16_t cqid = le16_to_cpu(c->cqid);
3146 uint16_t vector = le16_to_cpu(c->irq_vector);
3147 uint16_t qsize = le16_to_cpu(c->qsize);
3148 uint16_t qflags = le16_to_cpu(c->cq_flags);
3149 uint64_t prp1 = le64_to_cpu(c->prp1);
3151 trace_pci_nvme_create_cq(prp1, cqid, vector, qsize, qflags,
3152 NVME_CQ_FLAGS_IEN(qflags) != 0);
3154 if (unlikely(!cqid || cqid > n->params.max_ioqpairs ||
3155 n->cq[cqid] != NULL)) {
3156 trace_pci_nvme_err_invalid_create_cq_cqid(cqid);
3157 return NVME_INVALID_QID | NVME_DNR;
3159 if (unlikely(!qsize || qsize > NVME_CAP_MQES(n->bar.cap))) {
3160 trace_pci_nvme_err_invalid_create_cq_size(qsize);
3161 return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
3163 if (unlikely(prp1 & (n->page_size - 1))) {
3164 trace_pci_nvme_err_invalid_create_cq_addr(prp1);
3165 return NVME_INVALID_PRP_OFFSET | NVME_DNR;
3167 if (unlikely(!msix_enabled(&n->parent_obj) && vector)) {
3168 trace_pci_nvme_err_invalid_create_cq_vector(vector);
3169 return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
3171 if (unlikely(vector >= n->params.msix_qsize)) {
3172 trace_pci_nvme_err_invalid_create_cq_vector(vector);
3173 return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
3175 if (unlikely(!(NVME_CQ_FLAGS_PC(qflags)))) {
3176 trace_pci_nvme_err_invalid_create_cq_qflags(NVME_CQ_FLAGS_PC(qflags));
3177 return NVME_INVALID_FIELD | NVME_DNR;
3180 cq = g_malloc0(sizeof(*cq));
3181 nvme_init_cq(cq, n, prp1, cqid, vector, qsize + 1,
3182 NVME_CQ_FLAGS_IEN(qflags));
3185 * It is only required to set qs_created when creating a completion queue;
3186 * creating a submission queue without a matching completion queue will
3187 * fail.
3189 n->qs_created = true;
3190 return NVME_SUCCESS;
3193 static uint16_t nvme_rpt_empty_id_struct(NvmeCtrl *n, NvmeRequest *req)
3195 uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
3197 return nvme_dma(n, id, sizeof(id), DMA_DIRECTION_FROM_DEVICE, req);
3200 static inline bool nvme_csi_has_nvm_support(NvmeNamespace *ns)
3202 switch (ns->csi) {
3203 case NVME_CSI_NVM:
3204 case NVME_CSI_ZONED:
3205 return true;
3207 return false;
3210 static uint16_t nvme_identify_ctrl(NvmeCtrl *n, NvmeRequest *req)
3212 trace_pci_nvme_identify_ctrl();
3214 return nvme_dma(n, (uint8_t *)&n->id_ctrl, sizeof(n->id_ctrl),
3215 DMA_DIRECTION_FROM_DEVICE, req);
3218 static uint16_t nvme_identify_ctrl_csi(NvmeCtrl *n, NvmeRequest *req)
3220 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
3221 uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
3223 trace_pci_nvme_identify_ctrl_csi(c->csi);
3225 switch (c->csi) {
3226 case NVME_CSI_NVM:
3227 ((NvmeIdCtrlNvm *)&id)->dmrsl = cpu_to_le32(n->dmrsl);
3228 break;
3230 case NVME_CSI_ZONED:
3231 ((NvmeIdCtrlZoned *)&id)->zasl = n->params.zasl;
3232 break;
3234 default:
3235 return NVME_INVALID_FIELD | NVME_DNR;
3238 return nvme_dma(n, id, sizeof(id), DMA_DIRECTION_FROM_DEVICE, req);
3241 static uint16_t nvme_identify_ns(NvmeCtrl *n, NvmeRequest *req)
3243 NvmeNamespace *ns;
3244 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
3245 uint32_t nsid = le32_to_cpu(c->nsid);
3247 trace_pci_nvme_identify_ns(nsid);
3249 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
3250 return NVME_INVALID_NSID | NVME_DNR;
3253 ns = nvme_ns(n, nsid);
3254 if (unlikely(!ns)) {
3255 return nvme_rpt_empty_id_struct(n, req);
3258 if (c->csi == NVME_CSI_NVM && nvme_csi_has_nvm_support(ns)) {
3259 return nvme_dma(n, (uint8_t *)&ns->id_ns, sizeof(NvmeIdNs),
3260 DMA_DIRECTION_FROM_DEVICE, req);
3263 return NVME_INVALID_CMD_SET | NVME_DNR;
3266 static uint16_t nvme_identify_ns_csi(NvmeCtrl *n, NvmeRequest *req)
3268 NvmeNamespace *ns;
3269 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
3270 uint32_t nsid = le32_to_cpu(c->nsid);
3272 trace_pci_nvme_identify_ns_csi(nsid, c->csi);
3274 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
3275 return NVME_INVALID_NSID | NVME_DNR;
3278 ns = nvme_ns(n, nsid);
3279 if (unlikely(!ns)) {
3280 return nvme_rpt_empty_id_struct(n, req);
3283 if (c->csi == NVME_CSI_NVM && nvme_csi_has_nvm_support(ns)) {
3284 return nvme_rpt_empty_id_struct(n, req);
3285 } else if (c->csi == NVME_CSI_ZONED && ns->csi == NVME_CSI_ZONED) {
3286 return nvme_dma(n, (uint8_t *)ns->id_ns_zoned, sizeof(NvmeIdNsZoned),
3287 DMA_DIRECTION_FROM_DEVICE, req);
3290 return NVME_INVALID_FIELD | NVME_DNR;
3293 static uint16_t nvme_identify_nslist(NvmeCtrl *n, NvmeRequest *req)
3295 NvmeNamespace *ns;
3296 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
3297 uint32_t min_nsid = le32_to_cpu(c->nsid);
3298 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
3299 static const int data_len = sizeof(list);
3300 uint32_t *list_ptr = (uint32_t *)list;
3301 int i, j = 0;
3303 trace_pci_nvme_identify_nslist(min_nsid);
3306 * Both 0xffffffff (NVME_NSID_BROADCAST) and 0xfffffffe are invalid values
3307 * since the Active Namespace ID List should return namespaces with ids
3308 * *higher* than the NSID specified in the command. This is also specified
3309 * in the spec (NVM Express v1.3d, Section 5.15.4).
3311 if (min_nsid >= NVME_NSID_BROADCAST - 1) {
3312 return NVME_INVALID_NSID | NVME_DNR;
3315 for (i = 1; i <= n->num_namespaces; i++) {
3316 ns = nvme_ns(n, i);
3317 if (!ns) {
3318 continue;
3320 if (ns->params.nsid <= min_nsid) {
3321 continue;
3323 list_ptr[j++] = cpu_to_le32(ns->params.nsid);
3324 if (j == data_len / sizeof(uint32_t)) {
3325 break;
3329 return nvme_dma(n, list, data_len, DMA_DIRECTION_FROM_DEVICE, req);
3332 static uint16_t nvme_identify_nslist_csi(NvmeCtrl *n, NvmeRequest *req)
3334 NvmeNamespace *ns;
3335 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
3336 uint32_t min_nsid = le32_to_cpu(c->nsid);
3337 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
3338 static const int data_len = sizeof(list);
3339 uint32_t *list_ptr = (uint32_t *)list;
3340 int i, j = 0;
3342 trace_pci_nvme_identify_nslist_csi(min_nsid, c->csi);
3345 * Same as in nvme_identify_nslist(), 0xffffffff/0xfffffffe are invalid.
3347 if (min_nsid >= NVME_NSID_BROADCAST - 1) {
3348 return NVME_INVALID_NSID | NVME_DNR;
3351 if (c->csi != NVME_CSI_NVM && c->csi != NVME_CSI_ZONED) {
3352 return NVME_INVALID_FIELD | NVME_DNR;
3355 for (i = 1; i <= n->num_namespaces; i++) {
3356 ns = nvme_ns(n, i);
3357 if (!ns) {
3358 continue;
3360 if (ns->params.nsid <= min_nsid || c->csi != ns->csi) {
3361 continue;
3363 list_ptr[j++] = cpu_to_le32(ns->params.nsid);
3364 if (j == data_len / sizeof(uint32_t)) {
3365 break;
3369 return nvme_dma(n, list, data_len, DMA_DIRECTION_FROM_DEVICE, req);
3372 static uint16_t nvme_identify_ns_descr_list(NvmeCtrl *n, NvmeRequest *req)
3374 NvmeNamespace *ns;
3375 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
3376 uint32_t nsid = le32_to_cpu(c->nsid);
3377 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
3379 struct data {
3380 struct {
3381 NvmeIdNsDescr hdr;
3382 uint8_t v[NVME_NIDL_UUID];
3383 } uuid;
3384 struct {
3385 NvmeIdNsDescr hdr;
3386 uint8_t v;
3387 } csi;
3390 struct data *ns_descrs = (struct data *)list;
3392 trace_pci_nvme_identify_ns_descr_list(nsid);
3394 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
3395 return NVME_INVALID_NSID | NVME_DNR;
3398 ns = nvme_ns(n, nsid);
3399 if (unlikely(!ns)) {
3400 return NVME_INVALID_FIELD | NVME_DNR;
3404 * Because the NGUID and EUI64 fields are 0 in the Identify Namespace data
3405 * structure, a Namespace UUID (nidt = 0x3) must be reported in the
3406 * Namespace Identification Descriptor. Add the namespace UUID here.
3408 ns_descrs->uuid.hdr.nidt = NVME_NIDT_UUID;
3409 ns_descrs->uuid.hdr.nidl = NVME_NIDL_UUID;
3410 memcpy(&ns_descrs->uuid.v, ns->params.uuid.data, NVME_NIDL_UUID);
3412 ns_descrs->csi.hdr.nidt = NVME_NIDT_CSI;
3413 ns_descrs->csi.hdr.nidl = NVME_NIDL_CSI;
3414 ns_descrs->csi.v = ns->csi;
3416 return nvme_dma(n, list, sizeof(list), DMA_DIRECTION_FROM_DEVICE, req);
3419 static uint16_t nvme_identify_cmd_set(NvmeCtrl *n, NvmeRequest *req)
3421 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
3422 static const int data_len = sizeof(list);
3424 trace_pci_nvme_identify_cmd_set();
3426 NVME_SET_CSI(*list, NVME_CSI_NVM);
3427 NVME_SET_CSI(*list, NVME_CSI_ZONED);
3429 return nvme_dma(n, list, data_len, DMA_DIRECTION_FROM_DEVICE, req);
3432 static uint16_t nvme_identify(NvmeCtrl *n, NvmeRequest *req)
3434 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
3436 trace_pci_nvme_identify(nvme_cid(req), c->cns, le16_to_cpu(c->ctrlid),
3437 c->csi);
3439 switch (c->cns) {
3440 case NVME_ID_CNS_NS:
3441 /* fall through */
3442 case NVME_ID_CNS_NS_PRESENT:
3443 return nvme_identify_ns(n, req);
3444 case NVME_ID_CNS_CS_NS:
3445 /* fall through */
3446 case NVME_ID_CNS_CS_NS_PRESENT:
3447 return nvme_identify_ns_csi(n, req);
3448 case NVME_ID_CNS_CTRL:
3449 return nvme_identify_ctrl(n, req);
3450 case NVME_ID_CNS_CS_CTRL:
3451 return nvme_identify_ctrl_csi(n, req);
3452 case NVME_ID_CNS_NS_ACTIVE_LIST:
3453 /* fall through */
3454 case NVME_ID_CNS_NS_PRESENT_LIST:
3455 return nvme_identify_nslist(n, req);
3456 case NVME_ID_CNS_CS_NS_ACTIVE_LIST:
3457 /* fall through */
3458 case NVME_ID_CNS_CS_NS_PRESENT_LIST:
3459 return nvme_identify_nslist_csi(n, req);
3460 case NVME_ID_CNS_NS_DESCR_LIST:
3461 return nvme_identify_ns_descr_list(n, req);
3462 case NVME_ID_CNS_IO_COMMAND_SET:
3463 return nvme_identify_cmd_set(n, req);
3464 default:
3465 trace_pci_nvme_err_invalid_identify_cns(le32_to_cpu(c->cns));
3466 return NVME_INVALID_FIELD | NVME_DNR;
3470 static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
3472 uint16_t sqid = le32_to_cpu(req->cmd.cdw10) & 0xffff;
3474 req->cqe.result = 1;
3475 if (nvme_check_sqid(n, sqid)) {
3476 return NVME_INVALID_FIELD | NVME_DNR;
3479 return NVME_SUCCESS;
3482 static inline void nvme_set_timestamp(NvmeCtrl *n, uint64_t ts)
3484 trace_pci_nvme_setfeat_timestamp(ts);
3486 n->host_timestamp = le64_to_cpu(ts);
3487 n->timestamp_set_qemu_clock_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
3490 static inline uint64_t nvme_get_timestamp(const NvmeCtrl *n)
3492 uint64_t current_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
3493 uint64_t elapsed_time = current_time - n->timestamp_set_qemu_clock_ms;
3495 union nvme_timestamp {
3496 struct {
3497 uint64_t timestamp:48;
3498 uint64_t sync:1;
3499 uint64_t origin:3;
3500 uint64_t rsvd1:12;
3502 uint64_t all;
3505 union nvme_timestamp ts;
3506 ts.all = 0;
3507 ts.timestamp = n->host_timestamp + elapsed_time;
3509 /* If the host timestamp is non-zero, set the timestamp origin */
3510 ts.origin = n->host_timestamp ? 0x01 : 0x00;
3512 trace_pci_nvme_getfeat_timestamp(ts.all);
3514 return cpu_to_le64(ts.all);
3517 static uint16_t nvme_get_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
3519 uint64_t timestamp = nvme_get_timestamp(n);
3521 return nvme_dma(n, (uint8_t *)&timestamp, sizeof(timestamp),
3522 DMA_DIRECTION_FROM_DEVICE, req);
3525 static uint16_t nvme_get_feature(NvmeCtrl *n, NvmeRequest *req)
3527 NvmeCmd *cmd = &req->cmd;
3528 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
3529 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
3530 uint32_t nsid = le32_to_cpu(cmd->nsid);
3531 uint32_t result;
3532 uint8_t fid = NVME_GETSETFEAT_FID(dw10);
3533 NvmeGetFeatureSelect sel = NVME_GETFEAT_SELECT(dw10);
3534 uint16_t iv;
3535 NvmeNamespace *ns;
3536 int i;
3538 static const uint32_t nvme_feature_default[NVME_FID_MAX] = {
3539 [NVME_ARBITRATION] = NVME_ARB_AB_NOLIMIT,
3542 trace_pci_nvme_getfeat(nvme_cid(req), nsid, fid, sel, dw11);
3544 if (!nvme_feature_support[fid]) {
3545 return NVME_INVALID_FIELD | NVME_DNR;
3548 if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
3549 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
3551 * The Reservation Notification Mask and Reservation Persistence
3552 * features require a status code of Invalid Field in Command when
3553 * NSID is 0xFFFFFFFF. Since the device does not support those
3554 * features we can always return Invalid Namespace or Format as we
3555 * should do for all other features.
3557 return NVME_INVALID_NSID | NVME_DNR;
3560 if (!nvme_ns(n, nsid)) {
3561 return NVME_INVALID_FIELD | NVME_DNR;
3565 switch (sel) {
3566 case NVME_GETFEAT_SELECT_CURRENT:
3567 break;
3568 case NVME_GETFEAT_SELECT_SAVED:
3569 /* no features are saveable by the controller; fallthrough */
3570 case NVME_GETFEAT_SELECT_DEFAULT:
3571 goto defaults;
3572 case NVME_GETFEAT_SELECT_CAP:
3573 result = nvme_feature_cap[fid];
3574 goto out;
3577 switch (fid) {
3578 case NVME_TEMPERATURE_THRESHOLD:
3579 result = 0;
3582 * The controller only implements the Composite Temperature sensor, so
3583 * return 0 for all other sensors.
3585 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
3586 goto out;
3589 switch (NVME_TEMP_THSEL(dw11)) {
3590 case NVME_TEMP_THSEL_OVER:
3591 result = n->features.temp_thresh_hi;
3592 goto out;
3593 case NVME_TEMP_THSEL_UNDER:
3594 result = n->features.temp_thresh_low;
3595 goto out;
3598 return NVME_INVALID_FIELD | NVME_DNR;
3599 case NVME_ERROR_RECOVERY:
3600 if (!nvme_nsid_valid(n, nsid)) {
3601 return NVME_INVALID_NSID | NVME_DNR;
3604 ns = nvme_ns(n, nsid);
3605 if (unlikely(!ns)) {
3606 return NVME_INVALID_FIELD | NVME_DNR;
3609 result = ns->features.err_rec;
3610 goto out;
3611 case NVME_VOLATILE_WRITE_CACHE:
3612 result = 0;
3613 for (i = 1; i <= n->num_namespaces; i++) {
3614 ns = nvme_ns(n, i);
3615 if (!ns) {
3616 continue;
3619 result = blk_enable_write_cache(ns->blkconf.blk);
3620 if (result) {
3621 break;
3624 trace_pci_nvme_getfeat_vwcache(result ? "enabled" : "disabled");
3625 goto out;
3626 case NVME_ASYNCHRONOUS_EVENT_CONF:
3627 result = n->features.async_config;
3628 goto out;
3629 case NVME_TIMESTAMP:
3630 return nvme_get_feature_timestamp(n, req);
3631 default:
3632 break;
3635 defaults:
3636 switch (fid) {
3637 case NVME_TEMPERATURE_THRESHOLD:
3638 result = 0;
3640 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
3641 break;
3644 if (NVME_TEMP_THSEL(dw11) == NVME_TEMP_THSEL_OVER) {
3645 result = NVME_TEMPERATURE_WARNING;
3648 break;
3649 case NVME_NUMBER_OF_QUEUES:
3650 result = (n->params.max_ioqpairs - 1) |
3651 ((n->params.max_ioqpairs - 1) << 16);
3652 trace_pci_nvme_getfeat_numq(result);
3653 break;
3654 case NVME_INTERRUPT_VECTOR_CONF:
3655 iv = dw11 & 0xffff;
3656 if (iv >= n->params.max_ioqpairs + 1) {
3657 return NVME_INVALID_FIELD | NVME_DNR;
3660 result = iv;
3661 if (iv == n->admin_cq.vector) {
3662 result |= NVME_INTVC_NOCOALESCING;
3664 break;
3665 case NVME_COMMAND_SET_PROFILE:
3666 result = 0;
3667 break;
3668 default:
3669 result = nvme_feature_default[fid];
3670 break;
3673 out:
3674 req->cqe.result = cpu_to_le32(result);
3675 return NVME_SUCCESS;
3678 static uint16_t nvme_set_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
3680 uint16_t ret;
3681 uint64_t timestamp;
3683 ret = nvme_dma(n, (uint8_t *)&timestamp, sizeof(timestamp),
3684 DMA_DIRECTION_TO_DEVICE, req);
3685 if (ret) {
3686 return ret;
3689 nvme_set_timestamp(n, timestamp);
3691 return NVME_SUCCESS;
3694 static uint16_t nvme_set_feature(NvmeCtrl *n, NvmeRequest *req)
3696 NvmeNamespace *ns = NULL;
3698 NvmeCmd *cmd = &req->cmd;
3699 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
3700 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
3701 uint32_t nsid = le32_to_cpu(cmd->nsid);
3702 uint8_t fid = NVME_GETSETFEAT_FID(dw10);
3703 uint8_t save = NVME_SETFEAT_SAVE(dw10);
3704 int i;
3706 trace_pci_nvme_setfeat(nvme_cid(req), nsid, fid, save, dw11);
3708 if (save && !(nvme_feature_cap[fid] & NVME_FEAT_CAP_SAVE)) {
3709 return NVME_FID_NOT_SAVEABLE | NVME_DNR;
3712 if (!nvme_feature_support[fid]) {
3713 return NVME_INVALID_FIELD | NVME_DNR;
3716 if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
3717 if (nsid != NVME_NSID_BROADCAST) {
3718 if (!nvme_nsid_valid(n, nsid)) {
3719 return NVME_INVALID_NSID | NVME_DNR;
3722 ns = nvme_ns(n, nsid);
3723 if (unlikely(!ns)) {
3724 return NVME_INVALID_FIELD | NVME_DNR;
3727 } else if (nsid && nsid != NVME_NSID_BROADCAST) {
3728 if (!nvme_nsid_valid(n, nsid)) {
3729 return NVME_INVALID_NSID | NVME_DNR;
3732 return NVME_FEAT_NOT_NS_SPEC | NVME_DNR;
3735 if (!(nvme_feature_cap[fid] & NVME_FEAT_CAP_CHANGE)) {
3736 return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
3739 switch (fid) {
3740 case NVME_TEMPERATURE_THRESHOLD:
3741 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
3742 break;
3745 switch (NVME_TEMP_THSEL(dw11)) {
3746 case NVME_TEMP_THSEL_OVER:
3747 n->features.temp_thresh_hi = NVME_TEMP_TMPTH(dw11);
3748 break;
3749 case NVME_TEMP_THSEL_UNDER:
3750 n->features.temp_thresh_low = NVME_TEMP_TMPTH(dw11);
3751 break;
3752 default:
3753 return NVME_INVALID_FIELD | NVME_DNR;
3756 if ((n->temperature >= n->features.temp_thresh_hi) ||
3757 (n->temperature <= n->features.temp_thresh_low)) {
3758 nvme_smart_event(n, NVME_AER_INFO_SMART_TEMP_THRESH);
3761 break;
3762 case NVME_ERROR_RECOVERY:
3763 if (nsid == NVME_NSID_BROADCAST) {
3764 for (i = 1; i <= n->num_namespaces; i++) {
3765 ns = nvme_ns(n, i);
3767 if (!ns) {
3768 continue;
3771 if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat)) {
3772 ns->features.err_rec = dw11;
3776 break;
3779 assert(ns);
3780 if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat)) {
3781 ns->features.err_rec = dw11;
3783 break;
3784 case NVME_VOLATILE_WRITE_CACHE:
3785 for (i = 1; i <= n->num_namespaces; i++) {
3786 ns = nvme_ns(n, i);
3787 if (!ns) {
3788 continue;
3791 if (!(dw11 & 0x1) && blk_enable_write_cache(ns->blkconf.blk)) {
3792 blk_flush(ns->blkconf.blk);
3795 blk_set_enable_write_cache(ns->blkconf.blk, dw11 & 1);
3798 break;
3800 case NVME_NUMBER_OF_QUEUES:
3801 if (n->qs_created) {
3802 return NVME_CMD_SEQ_ERROR | NVME_DNR;
3806 * NVMe v1.3, Section 5.21.1.7: 0xffff is not an allowed value for NCQR
3807 * and NSQR.
3809 if ((dw11 & 0xffff) == 0xffff || ((dw11 >> 16) & 0xffff) == 0xffff) {
3810 return NVME_INVALID_FIELD | NVME_DNR;
3813 trace_pci_nvme_setfeat_numq((dw11 & 0xFFFF) + 1,
3814 ((dw11 >> 16) & 0xFFFF) + 1,
3815 n->params.max_ioqpairs,
3816 n->params.max_ioqpairs);
3817 req->cqe.result = cpu_to_le32((n->params.max_ioqpairs - 1) |
3818 ((n->params.max_ioqpairs - 1) << 16));
3819 break;
3820 case NVME_ASYNCHRONOUS_EVENT_CONF:
3821 n->features.async_config = dw11;
3822 break;
3823 case NVME_TIMESTAMP:
3824 return nvme_set_feature_timestamp(n, req);
3825 case NVME_COMMAND_SET_PROFILE:
3826 if (dw11 & 0x1ff) {
3827 trace_pci_nvme_err_invalid_iocsci(dw11 & 0x1ff);
3828 return NVME_CMD_SET_CMB_REJECTED | NVME_DNR;
3830 break;
3831 default:
3832 return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
3834 return NVME_SUCCESS;
3837 static uint16_t nvme_aer(NvmeCtrl *n, NvmeRequest *req)
3839 trace_pci_nvme_aer(nvme_cid(req));
3841 if (n->outstanding_aers > n->params.aerl) {
3842 trace_pci_nvme_aer_aerl_exceeded();
3843 return NVME_AER_LIMIT_EXCEEDED;
3846 n->aer_reqs[n->outstanding_aers] = req;
3847 n->outstanding_aers++;
3849 if (!QTAILQ_EMPTY(&n->aer_queue)) {
3850 nvme_process_aers(n);
3853 return NVME_NO_COMPLETE;
3856 static uint16_t nvme_admin_cmd(NvmeCtrl *n, NvmeRequest *req)
3858 trace_pci_nvme_admin_cmd(nvme_cid(req), nvme_sqid(req), req->cmd.opcode,
3859 nvme_adm_opc_str(req->cmd.opcode));
3861 if (!(nvme_cse_acs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
3862 trace_pci_nvme_err_invalid_admin_opc(req->cmd.opcode);
3863 return NVME_INVALID_OPCODE | NVME_DNR;
3866 /* SGLs shall not be used for Admin commands in NVMe over PCIe */
3867 if (NVME_CMD_FLAGS_PSDT(req->cmd.flags) != NVME_PSDT_PRP) {
3868 return NVME_INVALID_FIELD | NVME_DNR;
3871 switch (req->cmd.opcode) {
3872 case NVME_ADM_CMD_DELETE_SQ:
3873 return nvme_del_sq(n, req);
3874 case NVME_ADM_CMD_CREATE_SQ:
3875 return nvme_create_sq(n, req);
3876 case NVME_ADM_CMD_GET_LOG_PAGE:
3877 return nvme_get_log(n, req);
3878 case NVME_ADM_CMD_DELETE_CQ:
3879 return nvme_del_cq(n, req);
3880 case NVME_ADM_CMD_CREATE_CQ:
3881 return nvme_create_cq(n, req);
3882 case NVME_ADM_CMD_IDENTIFY:
3883 return nvme_identify(n, req);
3884 case NVME_ADM_CMD_ABORT:
3885 return nvme_abort(n, req);
3886 case NVME_ADM_CMD_SET_FEATURES:
3887 return nvme_set_feature(n, req);
3888 case NVME_ADM_CMD_GET_FEATURES:
3889 return nvme_get_feature(n, req);
3890 case NVME_ADM_CMD_ASYNC_EV_REQ:
3891 return nvme_aer(n, req);
3892 default:
3893 assert(false);
3896 return NVME_INVALID_OPCODE | NVME_DNR;
3899 static void nvme_process_sq(void *opaque)
3901 NvmeSQueue *sq = opaque;
3902 NvmeCtrl *n = sq->ctrl;
3903 NvmeCQueue *cq = n->cq[sq->cqid];
3905 uint16_t status;
3906 hwaddr addr;
3907 NvmeCmd cmd;
3908 NvmeRequest *req;
3910 while (!(nvme_sq_empty(sq) || QTAILQ_EMPTY(&sq->req_list))) {
3911 addr = sq->dma_addr + sq->head * n->sqe_size;
3912 if (nvme_addr_read(n, addr, (void *)&cmd, sizeof(cmd))) {
3913 trace_pci_nvme_err_addr_read(addr);
3914 trace_pci_nvme_err_cfs();
3915 n->bar.csts = NVME_CSTS_FAILED;
3916 break;
3918 nvme_inc_sq_head(sq);
3920 req = QTAILQ_FIRST(&sq->req_list);
3921 QTAILQ_REMOVE(&sq->req_list, req, entry);
3922 QTAILQ_INSERT_TAIL(&sq->out_req_list, req, entry);
3923 nvme_req_clear(req);
3924 req->cqe.cid = cmd.cid;
3925 memcpy(&req->cmd, &cmd, sizeof(NvmeCmd));
3927 status = sq->sqid ? nvme_io_cmd(n, req) :
3928 nvme_admin_cmd(n, req);
3929 if (status != NVME_NO_COMPLETE) {
3930 req->status = status;
3931 nvme_enqueue_req_completion(cq, req);
3936 static void nvme_ctrl_reset(NvmeCtrl *n)
3938 NvmeNamespace *ns;
3939 int i;
3941 for (i = 1; i <= n->num_namespaces; i++) {
3942 ns = nvme_ns(n, i);
3943 if (!ns) {
3944 continue;
3947 nvme_ns_drain(ns);
3950 for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
3951 if (n->sq[i] != NULL) {
3952 nvme_free_sq(n->sq[i], n);
3955 for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
3956 if (n->cq[i] != NULL) {
3957 nvme_free_cq(n->cq[i], n);
3961 while (!QTAILQ_EMPTY(&n->aer_queue)) {
3962 NvmeAsyncEvent *event = QTAILQ_FIRST(&n->aer_queue);
3963 QTAILQ_REMOVE(&n->aer_queue, event, entry);
3964 g_free(event);
3967 n->aer_queued = 0;
3968 n->outstanding_aers = 0;
3969 n->qs_created = false;
3971 n->bar.cc = 0;
3974 static void nvme_ctrl_shutdown(NvmeCtrl *n)
3976 NvmeNamespace *ns;
3977 int i;
3979 if (n->pmr.dev) {
3980 memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
3983 for (i = 1; i <= n->num_namespaces; i++) {
3984 ns = nvme_ns(n, i);
3985 if (!ns) {
3986 continue;
3989 nvme_ns_shutdown(ns);
3993 static void nvme_select_ns_iocs(NvmeCtrl *n)
3995 NvmeNamespace *ns;
3996 int i;
3998 for (i = 1; i <= n->num_namespaces; i++) {
3999 ns = nvme_ns(n, i);
4000 if (!ns) {
4001 continue;
4003 ns->iocs = nvme_cse_iocs_none;
4004 switch (ns->csi) {
4005 case NVME_CSI_NVM:
4006 if (NVME_CC_CSS(n->bar.cc) != NVME_CC_CSS_ADMIN_ONLY) {
4007 ns->iocs = nvme_cse_iocs_nvm;
4009 break;
4010 case NVME_CSI_ZONED:
4011 if (NVME_CC_CSS(n->bar.cc) == NVME_CC_CSS_CSI) {
4012 ns->iocs = nvme_cse_iocs_zoned;
4013 } else if (NVME_CC_CSS(n->bar.cc) == NVME_CC_CSS_NVM) {
4014 ns->iocs = nvme_cse_iocs_nvm;
4016 break;
4021 static int nvme_start_ctrl(NvmeCtrl *n)
4023 uint32_t page_bits = NVME_CC_MPS(n->bar.cc) + 12;
4024 uint32_t page_size = 1 << page_bits;
4026 if (unlikely(n->cq[0])) {
4027 trace_pci_nvme_err_startfail_cq();
4028 return -1;
4030 if (unlikely(n->sq[0])) {
4031 trace_pci_nvme_err_startfail_sq();
4032 return -1;
4034 if (unlikely(!n->bar.asq)) {
4035 trace_pci_nvme_err_startfail_nbarasq();
4036 return -1;
4038 if (unlikely(!n->bar.acq)) {
4039 trace_pci_nvme_err_startfail_nbaracq();
4040 return -1;
4042 if (unlikely(n->bar.asq & (page_size - 1))) {
4043 trace_pci_nvme_err_startfail_asq_misaligned(n->bar.asq);
4044 return -1;
4046 if (unlikely(n->bar.acq & (page_size - 1))) {
4047 trace_pci_nvme_err_startfail_acq_misaligned(n->bar.acq);
4048 return -1;
4050 if (unlikely(!(NVME_CAP_CSS(n->bar.cap) & (1 << NVME_CC_CSS(n->bar.cc))))) {
4051 trace_pci_nvme_err_startfail_css(NVME_CC_CSS(n->bar.cc));
4052 return -1;
4054 if (unlikely(NVME_CC_MPS(n->bar.cc) <
4055 NVME_CAP_MPSMIN(n->bar.cap))) {
4056 trace_pci_nvme_err_startfail_page_too_small(
4057 NVME_CC_MPS(n->bar.cc),
4058 NVME_CAP_MPSMIN(n->bar.cap));
4059 return -1;
4061 if (unlikely(NVME_CC_MPS(n->bar.cc) >
4062 NVME_CAP_MPSMAX(n->bar.cap))) {
4063 trace_pci_nvme_err_startfail_page_too_large(
4064 NVME_CC_MPS(n->bar.cc),
4065 NVME_CAP_MPSMAX(n->bar.cap));
4066 return -1;
4068 if (unlikely(NVME_CC_IOCQES(n->bar.cc) <
4069 NVME_CTRL_CQES_MIN(n->id_ctrl.cqes))) {
4070 trace_pci_nvme_err_startfail_cqent_too_small(
4071 NVME_CC_IOCQES(n->bar.cc),
4072 NVME_CTRL_CQES_MIN(n->bar.cap));
4073 return -1;
4075 if (unlikely(NVME_CC_IOCQES(n->bar.cc) >
4076 NVME_CTRL_CQES_MAX(n->id_ctrl.cqes))) {
4077 trace_pci_nvme_err_startfail_cqent_too_large(
4078 NVME_CC_IOCQES(n->bar.cc),
4079 NVME_CTRL_CQES_MAX(n->bar.cap));
4080 return -1;
4082 if (unlikely(NVME_CC_IOSQES(n->bar.cc) <
4083 NVME_CTRL_SQES_MIN(n->id_ctrl.sqes))) {
4084 trace_pci_nvme_err_startfail_sqent_too_small(
4085 NVME_CC_IOSQES(n->bar.cc),
4086 NVME_CTRL_SQES_MIN(n->bar.cap));
4087 return -1;
4089 if (unlikely(NVME_CC_IOSQES(n->bar.cc) >
4090 NVME_CTRL_SQES_MAX(n->id_ctrl.sqes))) {
4091 trace_pci_nvme_err_startfail_sqent_too_large(
4092 NVME_CC_IOSQES(n->bar.cc),
4093 NVME_CTRL_SQES_MAX(n->bar.cap));
4094 return -1;
4096 if (unlikely(!NVME_AQA_ASQS(n->bar.aqa))) {
4097 trace_pci_nvme_err_startfail_asqent_sz_zero();
4098 return -1;
4100 if (unlikely(!NVME_AQA_ACQS(n->bar.aqa))) {
4101 trace_pci_nvme_err_startfail_acqent_sz_zero();
4102 return -1;
4105 n->page_bits = page_bits;
4106 n->page_size = page_size;
4107 n->max_prp_ents = n->page_size / sizeof(uint64_t);
4108 n->cqe_size = 1 << NVME_CC_IOCQES(n->bar.cc);
4109 n->sqe_size = 1 << NVME_CC_IOSQES(n->bar.cc);
4110 nvme_init_cq(&n->admin_cq, n, n->bar.acq, 0, 0,
4111 NVME_AQA_ACQS(n->bar.aqa) + 1, 1);
4112 nvme_init_sq(&n->admin_sq, n, n->bar.asq, 0, 0,
4113 NVME_AQA_ASQS(n->bar.aqa) + 1);
4115 nvme_set_timestamp(n, 0ULL);
4117 QTAILQ_INIT(&n->aer_queue);
4119 nvme_select_ns_iocs(n);
4121 return 0;
4124 static void nvme_cmb_enable_regs(NvmeCtrl *n)
4126 NVME_CMBLOC_SET_CDPCILS(n->bar.cmbloc, 1);
4127 NVME_CMBLOC_SET_CDPMLS(n->bar.cmbloc, 1);
4128 NVME_CMBLOC_SET_BIR(n->bar.cmbloc, NVME_CMB_BIR);
4130 NVME_CMBSZ_SET_SQS(n->bar.cmbsz, 1);
4131 NVME_CMBSZ_SET_CQS(n->bar.cmbsz, 0);
4132 NVME_CMBSZ_SET_LISTS(n->bar.cmbsz, 1);
4133 NVME_CMBSZ_SET_RDS(n->bar.cmbsz, 1);
4134 NVME_CMBSZ_SET_WDS(n->bar.cmbsz, 1);
4135 NVME_CMBSZ_SET_SZU(n->bar.cmbsz, 2); /* MBs */
4136 NVME_CMBSZ_SET_SZ(n->bar.cmbsz, n->params.cmb_size_mb);
4139 static void nvme_write_bar(NvmeCtrl *n, hwaddr offset, uint64_t data,
4140 unsigned size)
4142 if (unlikely(offset & (sizeof(uint32_t) - 1))) {
4143 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_misaligned32,
4144 "MMIO write not 32-bit aligned,"
4145 " offset=0x%"PRIx64"", offset);
4146 /* should be ignored, fall through for now */
4149 if (unlikely(size < sizeof(uint32_t))) {
4150 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_toosmall,
4151 "MMIO write smaller than 32-bits,"
4152 " offset=0x%"PRIx64", size=%u",
4153 offset, size);
4154 /* should be ignored, fall through for now */
4157 switch (offset) {
4158 case 0xc: /* INTMS */
4159 if (unlikely(msix_enabled(&(n->parent_obj)))) {
4160 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
4161 "undefined access to interrupt mask set"
4162 " when MSI-X is enabled");
4163 /* should be ignored, fall through for now */
4165 n->bar.intms |= data & 0xffffffff;
4166 n->bar.intmc = n->bar.intms;
4167 trace_pci_nvme_mmio_intm_set(data & 0xffffffff, n->bar.intmc);
4168 nvme_irq_check(n);
4169 break;
4170 case 0x10: /* INTMC */
4171 if (unlikely(msix_enabled(&(n->parent_obj)))) {
4172 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
4173 "undefined access to interrupt mask clr"
4174 " when MSI-X is enabled");
4175 /* should be ignored, fall through for now */
4177 n->bar.intms &= ~(data & 0xffffffff);
4178 n->bar.intmc = n->bar.intms;
4179 trace_pci_nvme_mmio_intm_clr(data & 0xffffffff, n->bar.intmc);
4180 nvme_irq_check(n);
4181 break;
4182 case 0x14: /* CC */
4183 trace_pci_nvme_mmio_cfg(data & 0xffffffff);
4184 /* Windows first sends data, then sends enable bit */
4185 if (!NVME_CC_EN(data) && !NVME_CC_EN(n->bar.cc) &&
4186 !NVME_CC_SHN(data) && !NVME_CC_SHN(n->bar.cc))
4188 n->bar.cc = data;
4191 if (NVME_CC_EN(data) && !NVME_CC_EN(n->bar.cc)) {
4192 n->bar.cc = data;
4193 if (unlikely(nvme_start_ctrl(n))) {
4194 trace_pci_nvme_err_startfail();
4195 n->bar.csts = NVME_CSTS_FAILED;
4196 } else {
4197 trace_pci_nvme_mmio_start_success();
4198 n->bar.csts = NVME_CSTS_READY;
4200 } else if (!NVME_CC_EN(data) && NVME_CC_EN(n->bar.cc)) {
4201 trace_pci_nvme_mmio_stopped();
4202 nvme_ctrl_reset(n);
4203 n->bar.csts &= ~NVME_CSTS_READY;
4205 if (NVME_CC_SHN(data) && !(NVME_CC_SHN(n->bar.cc))) {
4206 trace_pci_nvme_mmio_shutdown_set();
4207 nvme_ctrl_shutdown(n);
4208 n->bar.cc = data;
4209 n->bar.csts |= NVME_CSTS_SHST_COMPLETE;
4210 } else if (!NVME_CC_SHN(data) && NVME_CC_SHN(n->bar.cc)) {
4211 trace_pci_nvme_mmio_shutdown_cleared();
4212 n->bar.csts &= ~NVME_CSTS_SHST_COMPLETE;
4213 n->bar.cc = data;
4215 break;
4216 case 0x1C: /* CSTS */
4217 if (data & (1 << 4)) {
4218 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ssreset_w1c_unsupported,
4219 "attempted to W1C CSTS.NSSRO"
4220 " but CAP.NSSRS is zero (not supported)");
4221 } else if (data != 0) {
4222 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ro_csts,
4223 "attempted to set a read only bit"
4224 " of controller status");
4226 break;
4227 case 0x20: /* NSSR */
4228 if (data == 0x4E564D65) {
4229 trace_pci_nvme_ub_mmiowr_ssreset_unsupported();
4230 } else {
4231 /* The spec says that writes of other values have no effect */
4232 return;
4234 break;
4235 case 0x24: /* AQA */
4236 n->bar.aqa = data & 0xffffffff;
4237 trace_pci_nvme_mmio_aqattr(data & 0xffffffff);
4238 break;
4239 case 0x28: /* ASQ */
4240 n->bar.asq = size == 8 ? data :
4241 (n->bar.asq & ~0xffffffffULL) | (data & 0xffffffff);
4242 trace_pci_nvme_mmio_asqaddr(data);
4243 break;
4244 case 0x2c: /* ASQ hi */
4245 n->bar.asq = (n->bar.asq & 0xffffffff) | (data << 32);
4246 trace_pci_nvme_mmio_asqaddr_hi(data, n->bar.asq);
4247 break;
4248 case 0x30: /* ACQ */
4249 trace_pci_nvme_mmio_acqaddr(data);
4250 n->bar.acq = size == 8 ? data :
4251 (n->bar.acq & ~0xffffffffULL) | (data & 0xffffffff);
4252 break;
4253 case 0x34: /* ACQ hi */
4254 n->bar.acq = (n->bar.acq & 0xffffffff) | (data << 32);
4255 trace_pci_nvme_mmio_acqaddr_hi(data, n->bar.acq);
4256 break;
4257 case 0x38: /* CMBLOC */
4258 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbloc_reserved,
4259 "invalid write to reserved CMBLOC"
4260 " when CMBSZ is zero, ignored");
4261 return;
4262 case 0x3C: /* CMBSZ */
4263 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbsz_readonly,
4264 "invalid write to read only CMBSZ, ignored");
4265 return;
4266 case 0x50: /* CMBMSC */
4267 if (!NVME_CAP_CMBS(n->bar.cap)) {
4268 return;
4271 n->bar.cmbmsc = size == 8 ? data :
4272 (n->bar.cmbmsc & ~0xffffffff) | (data & 0xffffffff);
4273 n->cmb.cmse = false;
4275 if (NVME_CMBMSC_CRE(data)) {
4276 nvme_cmb_enable_regs(n);
4278 if (NVME_CMBMSC_CMSE(data)) {
4279 hwaddr cba = NVME_CMBMSC_CBA(data) << CMBMSC_CBA_SHIFT;
4280 if (cba + int128_get64(n->cmb.mem.size) < cba) {
4281 NVME_CMBSTS_SET_CBAI(n->bar.cmbsts, 1);
4282 return;
4285 n->cmb.cba = cba;
4286 n->cmb.cmse = true;
4288 } else {
4289 n->bar.cmbsz = 0;
4290 n->bar.cmbloc = 0;
4293 return;
4294 case 0x54: /* CMBMSC hi */
4295 n->bar.cmbmsc = (n->bar.cmbmsc & 0xffffffff) | (data << 32);
4296 return;
4298 case 0xE00: /* PMRCAP */
4299 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrcap_readonly,
4300 "invalid write to PMRCAP register, ignored");
4301 return;
4302 case 0xE04: /* PMRCTL */
4303 n->bar.pmrctl = data;
4304 if (NVME_PMRCTL_EN(data)) {
4305 memory_region_set_enabled(&n->pmr.dev->mr, true);
4306 n->bar.pmrsts = 0;
4307 } else {
4308 memory_region_set_enabled(&n->pmr.dev->mr, false);
4309 NVME_PMRSTS_SET_NRDY(n->bar.pmrsts, 1);
4310 n->pmr.cmse = false;
4312 return;
4313 case 0xE08: /* PMRSTS */
4314 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrsts_readonly,
4315 "invalid write to PMRSTS register, ignored");
4316 return;
4317 case 0xE0C: /* PMREBS */
4318 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrebs_readonly,
4319 "invalid write to PMREBS register, ignored");
4320 return;
4321 case 0xE10: /* PMRSWTP */
4322 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrswtp_readonly,
4323 "invalid write to PMRSWTP register, ignored");
4324 return;
4325 case 0xE14: /* PMRMSCL */
4326 if (!NVME_CAP_PMRS(n->bar.cap)) {
4327 return;
4330 n->bar.pmrmsc = (n->bar.pmrmsc & ~0xffffffff) | (data & 0xffffffff);
4331 n->pmr.cmse = false;
4333 if (NVME_PMRMSC_CMSE(n->bar.pmrmsc)) {
4334 hwaddr cba = NVME_PMRMSC_CBA(n->bar.pmrmsc) << PMRMSC_CBA_SHIFT;
4335 if (cba + int128_get64(n->pmr.dev->mr.size) < cba) {
4336 NVME_PMRSTS_SET_CBAI(n->bar.pmrsts, 1);
4337 return;
4340 n->pmr.cmse = true;
4341 n->pmr.cba = cba;
4344 return;
4345 case 0xE18: /* PMRMSCU */
4346 if (!NVME_CAP_PMRS(n->bar.cap)) {
4347 return;
4350 n->bar.pmrmsc = (n->bar.pmrmsc & 0xffffffff) | (data << 32);
4351 return;
4352 default:
4353 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_invalid,
4354 "invalid MMIO write,"
4355 " offset=0x%"PRIx64", data=%"PRIx64"",
4356 offset, data);
4357 break;
4361 static uint64_t nvme_mmio_read(void *opaque, hwaddr addr, unsigned size)
4363 NvmeCtrl *n = (NvmeCtrl *)opaque;
4364 uint8_t *ptr = (uint8_t *)&n->bar;
4365 uint64_t val = 0;
4367 trace_pci_nvme_mmio_read(addr, size);
4369 if (unlikely(addr & (sizeof(uint32_t) - 1))) {
4370 NVME_GUEST_ERR(pci_nvme_ub_mmiord_misaligned32,
4371 "MMIO read not 32-bit aligned,"
4372 " offset=0x%"PRIx64"", addr);
4373 /* should RAZ, fall through for now */
4374 } else if (unlikely(size < sizeof(uint32_t))) {
4375 NVME_GUEST_ERR(pci_nvme_ub_mmiord_toosmall,
4376 "MMIO read smaller than 32-bits,"
4377 " offset=0x%"PRIx64"", addr);
4378 /* should RAZ, fall through for now */
4381 if (addr < sizeof(n->bar)) {
4383 * When PMRWBM bit 1 is set then read from
4384 * from PMRSTS should ensure prior writes
4385 * made it to persistent media
4387 if (addr == 0xE08 &&
4388 (NVME_PMRCAP_PMRWBM(n->bar.pmrcap) & 0x02)) {
4389 memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
4391 memcpy(&val, ptr + addr, size);
4392 } else {
4393 NVME_GUEST_ERR(pci_nvme_ub_mmiord_invalid_ofs,
4394 "MMIO read beyond last register,"
4395 " offset=0x%"PRIx64", returning 0", addr);
4398 return val;
4401 static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)
4403 uint32_t qid;
4405 if (unlikely(addr & ((1 << 2) - 1))) {
4406 NVME_GUEST_ERR(pci_nvme_ub_db_wr_misaligned,
4407 "doorbell write not 32-bit aligned,"
4408 " offset=0x%"PRIx64", ignoring", addr);
4409 return;
4412 if (((addr - 0x1000) >> 2) & 1) {
4413 /* Completion queue doorbell write */
4415 uint16_t new_head = val & 0xffff;
4416 int start_sqs;
4417 NvmeCQueue *cq;
4419 qid = (addr - (0x1000 + (1 << 2))) >> 3;
4420 if (unlikely(nvme_check_cqid(n, qid))) {
4421 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cq,
4422 "completion queue doorbell write"
4423 " for nonexistent queue,"
4424 " sqid=%"PRIu32", ignoring", qid);
4427 * NVM Express v1.3d, Section 4.1 state: "If host software writes
4428 * an invalid value to the Submission Queue Tail Doorbell or
4429 * Completion Queue Head Doorbell regiter and an Asynchronous Event
4430 * Request command is outstanding, then an asynchronous event is
4431 * posted to the Admin Completion Queue with a status code of
4432 * Invalid Doorbell Write Value."
4434 * Also note that the spec includes the "Invalid Doorbell Register"
4435 * status code, but nowhere does it specify when to use it.
4436 * However, it seems reasonable to use it here in a similar
4437 * fashion.
4439 if (n->outstanding_aers) {
4440 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
4441 NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
4442 NVME_LOG_ERROR_INFO);
4445 return;
4448 cq = n->cq[qid];
4449 if (unlikely(new_head >= cq->size)) {
4450 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cqhead,
4451 "completion queue doorbell write value"
4452 " beyond queue size, sqid=%"PRIu32","
4453 " new_head=%"PRIu16", ignoring",
4454 qid, new_head);
4456 if (n->outstanding_aers) {
4457 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
4458 NVME_AER_INFO_ERR_INVALID_DB_VALUE,
4459 NVME_LOG_ERROR_INFO);
4462 return;
4465 trace_pci_nvme_mmio_doorbell_cq(cq->cqid, new_head);
4467 start_sqs = nvme_cq_full(cq) ? 1 : 0;
4468 cq->head = new_head;
4469 if (start_sqs) {
4470 NvmeSQueue *sq;
4471 QTAILQ_FOREACH(sq, &cq->sq_list, entry) {
4472 timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
4474 timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
4477 if (cq->tail == cq->head) {
4478 nvme_irq_deassert(n, cq);
4480 } else {
4481 /* Submission queue doorbell write */
4483 uint16_t new_tail = val & 0xffff;
4484 NvmeSQueue *sq;
4486 qid = (addr - 0x1000) >> 3;
4487 if (unlikely(nvme_check_sqid(n, qid))) {
4488 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sq,
4489 "submission queue doorbell write"
4490 " for nonexistent queue,"
4491 " sqid=%"PRIu32", ignoring", qid);
4493 if (n->outstanding_aers) {
4494 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
4495 NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
4496 NVME_LOG_ERROR_INFO);
4499 return;
4502 sq = n->sq[qid];
4503 if (unlikely(new_tail >= sq->size)) {
4504 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sqtail,
4505 "submission queue doorbell write value"
4506 " beyond queue size, sqid=%"PRIu32","
4507 " new_tail=%"PRIu16", ignoring",
4508 qid, new_tail);
4510 if (n->outstanding_aers) {
4511 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
4512 NVME_AER_INFO_ERR_INVALID_DB_VALUE,
4513 NVME_LOG_ERROR_INFO);
4516 return;
4519 trace_pci_nvme_mmio_doorbell_sq(sq->sqid, new_tail);
4521 sq->tail = new_tail;
4522 timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
4526 static void nvme_mmio_write(void *opaque, hwaddr addr, uint64_t data,
4527 unsigned size)
4529 NvmeCtrl *n = (NvmeCtrl *)opaque;
4531 trace_pci_nvme_mmio_write(addr, data, size);
4533 if (addr < sizeof(n->bar)) {
4534 nvme_write_bar(n, addr, data, size);
4535 } else {
4536 nvme_process_db(n, addr, data);
4540 static const MemoryRegionOps nvme_mmio_ops = {
4541 .read = nvme_mmio_read,
4542 .write = nvme_mmio_write,
4543 .endianness = DEVICE_LITTLE_ENDIAN,
4544 .impl = {
4545 .min_access_size = 2,
4546 .max_access_size = 8,
4550 static void nvme_cmb_write(void *opaque, hwaddr addr, uint64_t data,
4551 unsigned size)
4553 NvmeCtrl *n = (NvmeCtrl *)opaque;
4554 stn_le_p(&n->cmb.buf[addr], size, data);
4557 static uint64_t nvme_cmb_read(void *opaque, hwaddr addr, unsigned size)
4559 NvmeCtrl *n = (NvmeCtrl *)opaque;
4560 return ldn_le_p(&n->cmb.buf[addr], size);
4563 static const MemoryRegionOps nvme_cmb_ops = {
4564 .read = nvme_cmb_read,
4565 .write = nvme_cmb_write,
4566 .endianness = DEVICE_LITTLE_ENDIAN,
4567 .impl = {
4568 .min_access_size = 1,
4569 .max_access_size = 8,
4573 static void nvme_check_constraints(NvmeCtrl *n, Error **errp)
4575 NvmeParams *params = &n->params;
4577 if (params->num_queues) {
4578 warn_report("num_queues is deprecated; please use max_ioqpairs "
4579 "instead");
4581 params->max_ioqpairs = params->num_queues - 1;
4584 if (n->conf.blk) {
4585 warn_report("drive property is deprecated; "
4586 "please use an nvme-ns device instead");
4589 if (params->max_ioqpairs < 1 ||
4590 params->max_ioqpairs > NVME_MAX_IOQPAIRS) {
4591 error_setg(errp, "max_ioqpairs must be between 1 and %d",
4592 NVME_MAX_IOQPAIRS);
4593 return;
4596 if (params->msix_qsize < 1 ||
4597 params->msix_qsize > PCI_MSIX_FLAGS_QSIZE + 1) {
4598 error_setg(errp, "msix_qsize must be between 1 and %d",
4599 PCI_MSIX_FLAGS_QSIZE + 1);
4600 return;
4603 if (!params->serial) {
4604 error_setg(errp, "serial property not set");
4605 return;
4608 if (n->pmr.dev) {
4609 if (host_memory_backend_is_mapped(n->pmr.dev)) {
4610 error_setg(errp, "can't use already busy memdev: %s",
4611 object_get_canonical_path_component(OBJECT(n->pmr.dev)));
4612 return;
4615 if (!is_power_of_2(n->pmr.dev->size)) {
4616 error_setg(errp, "pmr backend size needs to be power of 2 in size");
4617 return;
4620 host_memory_backend_set_mapped(n->pmr.dev, true);
4623 if (n->params.zasl > n->params.mdts) {
4624 error_setg(errp, "zoned.zasl (Zone Append Size Limit) must be less "
4625 "than or equal to mdts (Maximum Data Transfer Size)");
4626 return;
4630 static void nvme_init_state(NvmeCtrl *n)
4632 n->num_namespaces = NVME_MAX_NAMESPACES;
4633 /* add one to max_ioqpairs to account for the admin queue pair */
4634 n->reg_size = pow2ceil(sizeof(NvmeBar) +
4635 2 * (n->params.max_ioqpairs + 1) * NVME_DB_SIZE);
4636 n->sq = g_new0(NvmeSQueue *, n->params.max_ioqpairs + 1);
4637 n->cq = g_new0(NvmeCQueue *, n->params.max_ioqpairs + 1);
4638 n->temperature = NVME_TEMPERATURE;
4639 n->features.temp_thresh_hi = NVME_TEMPERATURE_WARNING;
4640 n->starttime_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
4641 n->aer_reqs = g_new0(NvmeRequest *, n->params.aerl + 1);
4644 int nvme_register_namespace(NvmeCtrl *n, NvmeNamespace *ns, Error **errp)
4646 uint32_t nsid = nvme_nsid(ns);
4648 if (nsid > NVME_MAX_NAMESPACES) {
4649 error_setg(errp, "invalid namespace id (must be between 0 and %d)",
4650 NVME_MAX_NAMESPACES);
4651 return -1;
4654 if (!nsid) {
4655 for (int i = 1; i <= n->num_namespaces; i++) {
4656 if (!nvme_ns(n, i)) {
4657 nsid = ns->params.nsid = i;
4658 break;
4662 if (!nsid) {
4663 error_setg(errp, "no free namespace id");
4664 return -1;
4666 } else {
4667 if (n->namespaces[nsid - 1]) {
4668 error_setg(errp, "namespace id '%d' is already in use", nsid);
4669 return -1;
4673 trace_pci_nvme_register_namespace(nsid);
4675 n->namespaces[nsid - 1] = ns;
4677 n->dmrsl = MIN_NON_ZERO(n->dmrsl,
4678 BDRV_REQUEST_MAX_BYTES / nvme_l2b(ns, 1));
4680 return 0;
4683 static void nvme_init_cmb(NvmeCtrl *n, PCIDevice *pci_dev)
4685 uint64_t cmb_size = n->params.cmb_size_mb * MiB;
4687 n->cmb.buf = g_malloc0(cmb_size);
4688 memory_region_init_io(&n->cmb.mem, OBJECT(n), &nvme_cmb_ops, n,
4689 "nvme-cmb", cmb_size);
4690 pci_register_bar(pci_dev, NVME_CMB_BIR,
4691 PCI_BASE_ADDRESS_SPACE_MEMORY |
4692 PCI_BASE_ADDRESS_MEM_TYPE_64 |
4693 PCI_BASE_ADDRESS_MEM_PREFETCH, &n->cmb.mem);
4695 NVME_CAP_SET_CMBS(n->bar.cap, 1);
4697 if (n->params.legacy_cmb) {
4698 nvme_cmb_enable_regs(n);
4699 n->cmb.cmse = true;
4703 static void nvme_init_pmr(NvmeCtrl *n, PCIDevice *pci_dev)
4705 NVME_PMRCAP_SET_RDS(n->bar.pmrcap, 1);
4706 NVME_PMRCAP_SET_WDS(n->bar.pmrcap, 1);
4707 NVME_PMRCAP_SET_BIR(n->bar.pmrcap, NVME_PMR_BIR);
4708 /* Turn on bit 1 support */
4709 NVME_PMRCAP_SET_PMRWBM(n->bar.pmrcap, 0x02);
4710 NVME_PMRCAP_SET_CMSS(n->bar.pmrcap, 1);
4712 pci_register_bar(pci_dev, NVME_PMRCAP_BIR(n->bar.pmrcap),
4713 PCI_BASE_ADDRESS_SPACE_MEMORY |
4714 PCI_BASE_ADDRESS_MEM_TYPE_64 |
4715 PCI_BASE_ADDRESS_MEM_PREFETCH, &n->pmr.dev->mr);
4717 memory_region_set_enabled(&n->pmr.dev->mr, false);
4720 static int nvme_init_pci(NvmeCtrl *n, PCIDevice *pci_dev, Error **errp)
4722 uint8_t *pci_conf = pci_dev->config;
4723 uint64_t bar_size, msix_table_size, msix_pba_size;
4724 unsigned msix_table_offset, msix_pba_offset;
4725 int ret;
4727 Error *err = NULL;
4729 pci_conf[PCI_INTERRUPT_PIN] = 1;
4730 pci_config_set_prog_interface(pci_conf, 0x2);
4732 if (n->params.use_intel_id) {
4733 pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
4734 pci_config_set_device_id(pci_conf, 0x5845);
4735 } else {
4736 pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REDHAT);
4737 pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REDHAT_NVME);
4740 pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_EXPRESS);
4741 pcie_endpoint_cap_init(pci_dev, 0x80);
4743 bar_size = QEMU_ALIGN_UP(n->reg_size, 4 * KiB);
4744 msix_table_offset = bar_size;
4745 msix_table_size = PCI_MSIX_ENTRY_SIZE * n->params.msix_qsize;
4747 bar_size += msix_table_size;
4748 bar_size = QEMU_ALIGN_UP(bar_size, 4 * KiB);
4749 msix_pba_offset = bar_size;
4750 msix_pba_size = QEMU_ALIGN_UP(n->params.msix_qsize, 64) / 8;
4752 bar_size += msix_pba_size;
4753 bar_size = pow2ceil(bar_size);
4755 memory_region_init(&n->bar0, OBJECT(n), "nvme-bar0", bar_size);
4756 memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, "nvme",
4757 n->reg_size);
4758 memory_region_add_subregion(&n->bar0, 0, &n->iomem);
4760 pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |
4761 PCI_BASE_ADDRESS_MEM_TYPE_64, &n->bar0);
4762 ret = msix_init(pci_dev, n->params.msix_qsize,
4763 &n->bar0, 0, msix_table_offset,
4764 &n->bar0, 0, msix_pba_offset, 0, &err);
4765 if (ret < 0) {
4766 if (ret == -ENOTSUP) {
4767 warn_report_err(err);
4768 } else {
4769 error_propagate(errp, err);
4770 return ret;
4774 if (n->params.cmb_size_mb) {
4775 nvme_init_cmb(n, pci_dev);
4778 if (n->pmr.dev) {
4779 nvme_init_pmr(n, pci_dev);
4782 return 0;
4785 static void nvme_init_subnqn(NvmeCtrl *n)
4787 NvmeSubsystem *subsys = n->subsys;
4788 NvmeIdCtrl *id = &n->id_ctrl;
4790 if (!subsys) {
4791 snprintf((char *)id->subnqn, sizeof(id->subnqn),
4792 "nqn.2019-08.org.qemu:%s", n->params.serial);
4793 } else {
4794 pstrcpy((char *)id->subnqn, sizeof(id->subnqn), (char*)subsys->subnqn);
4798 static void nvme_init_ctrl(NvmeCtrl *n, PCIDevice *pci_dev)
4800 NvmeIdCtrl *id = &n->id_ctrl;
4801 uint8_t *pci_conf = pci_dev->config;
4803 id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID));
4804 id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID));
4805 strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' ');
4806 strpadcpy((char *)id->fr, sizeof(id->fr), "1.0", ' ');
4807 strpadcpy((char *)id->sn, sizeof(id->sn), n->params.serial, ' ');
4809 id->cntlid = cpu_to_le16(n->cntlid);
4811 id->rab = 6;
4813 if (n->params.use_intel_id) {
4814 id->ieee[0] = 0xb3;
4815 id->ieee[1] = 0x02;
4816 id->ieee[2] = 0x00;
4817 } else {
4818 id->ieee[0] = 0x00;
4819 id->ieee[1] = 0x54;
4820 id->ieee[2] = 0x52;
4823 id->mdts = n->params.mdts;
4824 id->ver = cpu_to_le32(NVME_SPEC_VER);
4825 id->oacs = cpu_to_le16(0);
4826 id->cntrltype = 0x1;
4829 * Because the controller always completes the Abort command immediately,
4830 * there can never be more than one concurrently executing Abort command,
4831 * so this value is never used for anything. Note that there can easily be
4832 * many Abort commands in the queues, but they are not considered
4833 * "executing" until processed by nvme_abort.
4835 * The specification recommends a value of 3 for Abort Command Limit (four
4836 * concurrently outstanding Abort commands), so lets use that though it is
4837 * inconsequential.
4839 id->acl = 3;
4840 id->aerl = n->params.aerl;
4841 id->frmw = (NVME_NUM_FW_SLOTS << 1) | NVME_FRMW_SLOT1_RO;
4842 id->lpa = NVME_LPA_NS_SMART | NVME_LPA_CSE | NVME_LPA_EXTENDED;
4844 /* recommended default value (~70 C) */
4845 id->wctemp = cpu_to_le16(NVME_TEMPERATURE_WARNING);
4846 id->cctemp = cpu_to_le16(NVME_TEMPERATURE_CRITICAL);
4848 id->sqes = (0x6 << 4) | 0x6;
4849 id->cqes = (0x4 << 4) | 0x4;
4850 id->nn = cpu_to_le32(n->num_namespaces);
4851 id->oncs = cpu_to_le16(NVME_ONCS_WRITE_ZEROES | NVME_ONCS_TIMESTAMP |
4852 NVME_ONCS_FEATURES | NVME_ONCS_DSM |
4853 NVME_ONCS_COMPARE | NVME_ONCS_COPY);
4856 * NOTE: If this device ever supports a command set that does NOT use 0x0
4857 * as a Flush-equivalent operation, support for the broadcast NSID in Flush
4858 * should probably be removed.
4860 * See comment in nvme_io_cmd.
4862 id->vwc = NVME_VWC_NSID_BROADCAST_SUPPORT | NVME_VWC_PRESENT;
4864 id->ocfs = cpu_to_le16(NVME_OCFS_COPY_FORMAT_0);
4865 id->sgls = cpu_to_le32(NVME_CTRL_SGLS_SUPPORT_NO_ALIGN |
4866 NVME_CTRL_SGLS_BITBUCKET);
4868 nvme_init_subnqn(n);
4870 id->psd[0].mp = cpu_to_le16(0x9c4);
4871 id->psd[0].enlat = cpu_to_le32(0x10);
4872 id->psd[0].exlat = cpu_to_le32(0x4);
4874 if (n->subsys) {
4875 id->cmic |= NVME_CMIC_MULTI_CTRL;
4878 NVME_CAP_SET_MQES(n->bar.cap, 0x7ff);
4879 NVME_CAP_SET_CQR(n->bar.cap, 1);
4880 NVME_CAP_SET_TO(n->bar.cap, 0xf);
4881 NVME_CAP_SET_CSS(n->bar.cap, NVME_CAP_CSS_NVM);
4882 NVME_CAP_SET_CSS(n->bar.cap, NVME_CAP_CSS_CSI_SUPP);
4883 NVME_CAP_SET_CSS(n->bar.cap, NVME_CAP_CSS_ADMIN_ONLY);
4884 NVME_CAP_SET_MPSMAX(n->bar.cap, 4);
4885 NVME_CAP_SET_CMBS(n->bar.cap, n->params.cmb_size_mb ? 1 : 0);
4886 NVME_CAP_SET_PMRS(n->bar.cap, n->pmr.dev ? 1 : 0);
4888 n->bar.vs = NVME_SPEC_VER;
4889 n->bar.intmc = n->bar.intms = 0;
4892 static int nvme_init_subsys(NvmeCtrl *n, Error **errp)
4894 int cntlid;
4896 if (!n->subsys) {
4897 return 0;
4900 cntlid = nvme_subsys_register_ctrl(n, errp);
4901 if (cntlid < 0) {
4902 return -1;
4905 n->cntlid = cntlid;
4907 return 0;
4910 static void nvme_realize(PCIDevice *pci_dev, Error **errp)
4912 NvmeCtrl *n = NVME(pci_dev);
4913 NvmeNamespace *ns;
4914 Error *local_err = NULL;
4916 nvme_check_constraints(n, &local_err);
4917 if (local_err) {
4918 error_propagate(errp, local_err);
4919 return;
4922 qbus_create_inplace(&n->bus, sizeof(NvmeBus), TYPE_NVME_BUS,
4923 &pci_dev->qdev, n->parent_obj.qdev.id);
4925 nvme_init_state(n);
4926 if (nvme_init_pci(n, pci_dev, errp)) {
4927 return;
4930 if (nvme_init_subsys(n, errp)) {
4931 error_propagate(errp, local_err);
4932 return;
4934 nvme_init_ctrl(n, pci_dev);
4936 /* setup a namespace if the controller drive property was given */
4937 if (n->namespace.blkconf.blk) {
4938 ns = &n->namespace;
4939 ns->params.nsid = 1;
4941 if (nvme_ns_setup(ns, errp)) {
4942 return;
4945 if (nvme_register_namespace(n, ns, errp)) {
4946 return;
4951 static void nvme_exit(PCIDevice *pci_dev)
4953 NvmeCtrl *n = NVME(pci_dev);
4954 NvmeNamespace *ns;
4955 int i;
4957 nvme_ctrl_reset(n);
4959 for (i = 1; i <= n->num_namespaces; i++) {
4960 ns = nvme_ns(n, i);
4961 if (!ns) {
4962 continue;
4965 nvme_ns_cleanup(ns);
4968 g_free(n->cq);
4969 g_free(n->sq);
4970 g_free(n->aer_reqs);
4972 if (n->params.cmb_size_mb) {
4973 g_free(n->cmb.buf);
4976 if (n->pmr.dev) {
4977 host_memory_backend_set_mapped(n->pmr.dev, false);
4979 msix_uninit_exclusive_bar(pci_dev);
4982 static Property nvme_props[] = {
4983 DEFINE_BLOCK_PROPERTIES(NvmeCtrl, namespace.blkconf),
4984 DEFINE_PROP_LINK("pmrdev", NvmeCtrl, pmr.dev, TYPE_MEMORY_BACKEND,
4985 HostMemoryBackend *),
4986 DEFINE_PROP_LINK("subsys", NvmeCtrl, subsys, TYPE_NVME_SUBSYS,
4987 NvmeSubsystem *),
4988 DEFINE_PROP_STRING("serial", NvmeCtrl, params.serial),
4989 DEFINE_PROP_UINT32("cmb_size_mb", NvmeCtrl, params.cmb_size_mb, 0),
4990 DEFINE_PROP_UINT32("num_queues", NvmeCtrl, params.num_queues, 0),
4991 DEFINE_PROP_UINT32("max_ioqpairs", NvmeCtrl, params.max_ioqpairs, 64),
4992 DEFINE_PROP_UINT16("msix_qsize", NvmeCtrl, params.msix_qsize, 65),
4993 DEFINE_PROP_UINT8("aerl", NvmeCtrl, params.aerl, 3),
4994 DEFINE_PROP_UINT32("aer_max_queued", NvmeCtrl, params.aer_max_queued, 64),
4995 DEFINE_PROP_UINT8("mdts", NvmeCtrl, params.mdts, 7),
4996 DEFINE_PROP_BOOL("use-intel-id", NvmeCtrl, params.use_intel_id, false),
4997 DEFINE_PROP_BOOL("legacy-cmb", NvmeCtrl, params.legacy_cmb, false),
4998 DEFINE_PROP_UINT8("zoned.zasl", NvmeCtrl, params.zasl, 0),
4999 DEFINE_PROP_END_OF_LIST(),
5002 static void nvme_get_smart_warning(Object *obj, Visitor *v, const char *name,
5003 void *opaque, Error **errp)
5005 NvmeCtrl *n = NVME(obj);
5006 uint8_t value = n->smart_critical_warning;
5008 visit_type_uint8(v, name, &value, errp);
5011 static void nvme_set_smart_warning(Object *obj, Visitor *v, const char *name,
5012 void *opaque, Error **errp)
5014 NvmeCtrl *n = NVME(obj);
5015 uint8_t value, old_value, cap = 0, index, event;
5017 if (!visit_type_uint8(v, name, &value, errp)) {
5018 return;
5021 cap = NVME_SMART_SPARE | NVME_SMART_TEMPERATURE | NVME_SMART_RELIABILITY
5022 | NVME_SMART_MEDIA_READ_ONLY | NVME_SMART_FAILED_VOLATILE_MEDIA;
5023 if (NVME_CAP_PMRS(n->bar.cap)) {
5024 cap |= NVME_SMART_PMR_UNRELIABLE;
5027 if ((value & cap) != value) {
5028 error_setg(errp, "unsupported smart critical warning bits: 0x%x",
5029 value & ~cap);
5030 return;
5033 old_value = n->smart_critical_warning;
5034 n->smart_critical_warning = value;
5036 /* only inject new bits of smart critical warning */
5037 for (index = 0; index < NVME_SMART_WARN_MAX; index++) {
5038 event = 1 << index;
5039 if (value & ~old_value & event)
5040 nvme_smart_event(n, event);
5044 static const VMStateDescription nvme_vmstate = {
5045 .name = "nvme",
5046 .unmigratable = 1,
5049 static void nvme_class_init(ObjectClass *oc, void *data)
5051 DeviceClass *dc = DEVICE_CLASS(oc);
5052 PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc);
5054 pc->realize = nvme_realize;
5055 pc->exit = nvme_exit;
5056 pc->class_id = PCI_CLASS_STORAGE_EXPRESS;
5057 pc->revision = 2;
5059 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
5060 dc->desc = "Non-Volatile Memory Express";
5061 device_class_set_props(dc, nvme_props);
5062 dc->vmsd = &nvme_vmstate;
5065 static void nvme_instance_init(Object *obj)
5067 NvmeCtrl *n = NVME(obj);
5069 if (n->namespace.blkconf.blk) {
5070 device_add_bootindex_property(obj, &n->namespace.blkconf.bootindex,
5071 "bootindex", "/namespace@1,0",
5072 DEVICE(obj));
5075 object_property_add(obj, "smart_critical_warning", "uint8",
5076 nvme_get_smart_warning,
5077 nvme_set_smart_warning, NULL, NULL);
5080 static const TypeInfo nvme_info = {
5081 .name = TYPE_NVME,
5082 .parent = TYPE_PCI_DEVICE,
5083 .instance_size = sizeof(NvmeCtrl),
5084 .instance_init = nvme_instance_init,
5085 .class_init = nvme_class_init,
5086 .interfaces = (InterfaceInfo[]) {
5087 { INTERFACE_PCIE_DEVICE },
5092 static const TypeInfo nvme_bus_info = {
5093 .name = TYPE_NVME_BUS,
5094 .parent = TYPE_BUS,
5095 .instance_size = sizeof(NvmeBus),
5098 static void nvme_register_types(void)
5100 type_register_static(&nvme_info);
5101 type_register_static(&nvme_bus_info);
5104 type_init(nvme_register_types)