Merge remote-tracking branch 'remotes/dgilbert-gitlab/tags/pull-migration-20210726a...
[qemu/armbru.git] / hw / nvme / ctrl.c
blob629b0d38c2a2e5807a7144d3ed7a8ecfed7e98a5
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 * Notes on coding style
18 * ---------------------
19 * While QEMU coding style prefers lowercase hexadecimals in constants, the
20 * NVMe subsystem use thes format from the NVMe specifications in the comments
21 * (i.e. 'h' suffix instead of '0x' prefix).
23 * Usage
24 * -----
25 * See docs/system/nvme.rst for extensive documentation.
27 * Add options:
28 * -drive file=<file>,if=none,id=<drive_id>
29 * -device nvme-subsys,id=<subsys_id>,nqn=<nqn_id>
30 * -device nvme,serial=<serial>,id=<bus_name>, \
31 * cmb_size_mb=<cmb_size_mb[optional]>, \
32 * [pmrdev=<mem_backend_file_id>,] \
33 * max_ioqpairs=<N[optional]>, \
34 * aerl=<N[optional]>,aer_max_queued=<N[optional]>, \
35 * mdts=<N[optional]>,vsl=<N[optional]>, \
36 * zoned.zasl=<N[optional]>, \
37 * zoned.auto_transition=<on|off[optional]>, \
38 * subsys=<subsys_id>
39 * -device nvme-ns,drive=<drive_id>,bus=<bus_name>,nsid=<nsid>,\
40 * zoned=<true|false[optional]>, \
41 * subsys=<subsys_id>,detached=<true|false[optional]>
43 * Note cmb_size_mb denotes size of CMB in MB. CMB is assumed to be at
44 * offset 0 in BAR2 and supports only WDS, RDS and SQS for now. By default, the
45 * device will use the "v1.4 CMB scheme" - use the `legacy-cmb` parameter to
46 * always enable the CMBLOC and CMBSZ registers (v1.3 behavior).
48 * Enabling pmr emulation can be achieved by pointing to memory-backend-file.
49 * For example:
50 * -object memory-backend-file,id=<mem_id>,share=on,mem-path=<file_path>, \
51 * size=<size> .... -device nvme,...,pmrdev=<mem_id>
53 * The PMR will use BAR 4/5 exclusively.
55 * To place controller(s) and namespace(s) to a subsystem, then provide
56 * nvme-subsys device as above.
58 * nvme subsystem device parameters
59 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
60 * - `nqn`
61 * This parameter provides the `<nqn_id>` part of the string
62 * `nqn.2019-08.org.qemu:<nqn_id>` which will be reported in the SUBNQN field
63 * of subsystem controllers. Note that `<nqn_id>` should be unique per
64 * subsystem, but this is not enforced by QEMU. If not specified, it will
65 * default to the value of the `id` parameter (`<subsys_id>`).
67 * nvme device parameters
68 * ~~~~~~~~~~~~~~~~~~~~~~
69 * - `subsys`
70 * Specifying this parameter attaches the controller to the subsystem and
71 * the SUBNQN field in the controller will report the NQN of the subsystem
72 * device. This also enables multi controller capability represented in
73 * Identify Controller data structure in CMIC (Controller Multi-path I/O and
74 * Namesapce Sharing Capabilities).
76 * - `aerl`
77 * The Asynchronous Event Request Limit (AERL). Indicates the maximum number
78 * of concurrently outstanding Asynchronous Event Request commands support
79 * by the controller. This is a 0's based value.
81 * - `aer_max_queued`
82 * This is the maximum number of events that the device will enqueue for
83 * completion when there are no outstanding AERs. When the maximum number of
84 * enqueued events are reached, subsequent events will be dropped.
86 * - `mdts`
87 * Indicates the maximum data transfer size for a command that transfers data
88 * between host-accessible memory and the controller. The value is specified
89 * as a power of two (2^n) and is in units of the minimum memory page size
90 * (CAP.MPSMIN). The default value is 7 (i.e. 512 KiB).
92 * - `vsl`
93 * Indicates the maximum data size limit for the Verify command. Like `mdts`,
94 * this value is specified as a power of two (2^n) and is in units of the
95 * minimum memory page size (CAP.MPSMIN). The default value is 7 (i.e. 512
96 * KiB).
98 * - `zoned.zasl`
99 * Indicates the maximum data transfer size for the Zone Append command. Like
100 * `mdts`, the value is specified as a power of two (2^n) and is in units of
101 * the minimum memory page size (CAP.MPSMIN). The default value is 0 (i.e.
102 * defaulting to the value of `mdts`).
104 * - `zoned.auto_transition`
105 * Indicates if zones in zone state implicitly opened can be automatically
106 * transitioned to zone state closed for resource management purposes.
107 * Defaults to 'on'.
109 * nvme namespace device parameters
110 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
111 * - `shared`
112 * When the parent nvme device (as defined explicitly by the 'bus' parameter
113 * or implicitly by the most recently defined NvmeBus) is linked to an
114 * nvme-subsys device, the namespace will be attached to all controllers in
115 * the subsystem. If set to 'off' (the default), the namespace will remain a
116 * private namespace and may only be attached to a single controller at a
117 * time.
119 * - `detached`
120 * This parameter is only valid together with the `subsys` parameter. If left
121 * at the default value (`false/off`), the namespace will be attached to all
122 * controllers in the NVMe subsystem at boot-up. If set to `true/on`, the
123 * namespace will be available in the subsystem but not attached to any
124 * controllers.
126 * Setting `zoned` to true selects Zoned Command Set at the namespace.
127 * In this case, the following namespace properties are available to configure
128 * zoned operation:
129 * zoned.zone_size=<zone size in bytes, default: 128MiB>
130 * The number may be followed by K, M, G as in kilo-, mega- or giga-.
132 * zoned.zone_capacity=<zone capacity in bytes, default: zone size>
133 * The value 0 (default) forces zone capacity to be the same as zone
134 * size. The value of this property may not exceed zone size.
136 * zoned.descr_ext_size=<zone descriptor extension size, default 0>
137 * This value needs to be specified in 64B units. If it is zero,
138 * namespace(s) will not support zone descriptor extensions.
140 * zoned.max_active=<Maximum Active Resources (zones), default: 0>
141 * The default value means there is no limit to the number of
142 * concurrently active zones.
144 * zoned.max_open=<Maximum Open Resources (zones), default: 0>
145 * The default value means there is no limit to the number of
146 * concurrently open zones.
148 * zoned.cross_read=<enable RAZB, default: false>
149 * Setting this property to true enables Read Across Zone Boundaries.
152 #include "qemu/osdep.h"
153 #include "qemu/cutils.h"
154 #include "qemu/error-report.h"
155 #include "qemu/log.h"
156 #include "qemu/units.h"
157 #include "qapi/error.h"
158 #include "qapi/visitor.h"
159 #include "sysemu/sysemu.h"
160 #include "sysemu/block-backend.h"
161 #include "sysemu/hostmem.h"
162 #include "hw/pci/msix.h"
163 #include "migration/vmstate.h"
165 #include "nvme.h"
166 #include "trace.h"
168 #define NVME_MAX_IOQPAIRS 0xffff
169 #define NVME_DB_SIZE 4
170 #define NVME_SPEC_VER 0x00010400
171 #define NVME_CMB_BIR 2
172 #define NVME_PMR_BIR 4
173 #define NVME_TEMPERATURE 0x143
174 #define NVME_TEMPERATURE_WARNING 0x157
175 #define NVME_TEMPERATURE_CRITICAL 0x175
176 #define NVME_NUM_FW_SLOTS 1
177 #define NVME_DEFAULT_MAX_ZA_SIZE (128 * KiB)
179 #define NVME_GUEST_ERR(trace, fmt, ...) \
180 do { \
181 (trace_##trace)(__VA_ARGS__); \
182 qemu_log_mask(LOG_GUEST_ERROR, #trace \
183 " in %s: " fmt "\n", __func__, ## __VA_ARGS__); \
184 } while (0)
186 static const bool nvme_feature_support[NVME_FID_MAX] = {
187 [NVME_ARBITRATION] = true,
188 [NVME_POWER_MANAGEMENT] = true,
189 [NVME_TEMPERATURE_THRESHOLD] = true,
190 [NVME_ERROR_RECOVERY] = true,
191 [NVME_VOLATILE_WRITE_CACHE] = true,
192 [NVME_NUMBER_OF_QUEUES] = true,
193 [NVME_INTERRUPT_COALESCING] = true,
194 [NVME_INTERRUPT_VECTOR_CONF] = true,
195 [NVME_WRITE_ATOMICITY] = true,
196 [NVME_ASYNCHRONOUS_EVENT_CONF] = true,
197 [NVME_TIMESTAMP] = true,
198 [NVME_COMMAND_SET_PROFILE] = true,
201 static const uint32_t nvme_feature_cap[NVME_FID_MAX] = {
202 [NVME_TEMPERATURE_THRESHOLD] = NVME_FEAT_CAP_CHANGE,
203 [NVME_ERROR_RECOVERY] = NVME_FEAT_CAP_CHANGE | NVME_FEAT_CAP_NS,
204 [NVME_VOLATILE_WRITE_CACHE] = NVME_FEAT_CAP_CHANGE,
205 [NVME_NUMBER_OF_QUEUES] = NVME_FEAT_CAP_CHANGE,
206 [NVME_ASYNCHRONOUS_EVENT_CONF] = NVME_FEAT_CAP_CHANGE,
207 [NVME_TIMESTAMP] = NVME_FEAT_CAP_CHANGE,
208 [NVME_COMMAND_SET_PROFILE] = NVME_FEAT_CAP_CHANGE,
211 static const uint32_t nvme_cse_acs[256] = {
212 [NVME_ADM_CMD_DELETE_SQ] = NVME_CMD_EFF_CSUPP,
213 [NVME_ADM_CMD_CREATE_SQ] = NVME_CMD_EFF_CSUPP,
214 [NVME_ADM_CMD_GET_LOG_PAGE] = NVME_CMD_EFF_CSUPP,
215 [NVME_ADM_CMD_DELETE_CQ] = NVME_CMD_EFF_CSUPP,
216 [NVME_ADM_CMD_CREATE_CQ] = NVME_CMD_EFF_CSUPP,
217 [NVME_ADM_CMD_IDENTIFY] = NVME_CMD_EFF_CSUPP,
218 [NVME_ADM_CMD_ABORT] = NVME_CMD_EFF_CSUPP,
219 [NVME_ADM_CMD_SET_FEATURES] = NVME_CMD_EFF_CSUPP,
220 [NVME_ADM_CMD_GET_FEATURES] = NVME_CMD_EFF_CSUPP,
221 [NVME_ADM_CMD_ASYNC_EV_REQ] = NVME_CMD_EFF_CSUPP,
222 [NVME_ADM_CMD_NS_ATTACHMENT] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_NIC,
223 [NVME_ADM_CMD_FORMAT_NVM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
226 static const uint32_t nvme_cse_iocs_none[256];
228 static const uint32_t nvme_cse_iocs_nvm[256] = {
229 [NVME_CMD_FLUSH] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
230 [NVME_CMD_WRITE_ZEROES] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
231 [NVME_CMD_WRITE] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
232 [NVME_CMD_READ] = NVME_CMD_EFF_CSUPP,
233 [NVME_CMD_DSM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
234 [NVME_CMD_VERIFY] = NVME_CMD_EFF_CSUPP,
235 [NVME_CMD_COPY] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
236 [NVME_CMD_COMPARE] = NVME_CMD_EFF_CSUPP,
239 static const uint32_t nvme_cse_iocs_zoned[256] = {
240 [NVME_CMD_FLUSH] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
241 [NVME_CMD_WRITE_ZEROES] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
242 [NVME_CMD_WRITE] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
243 [NVME_CMD_READ] = NVME_CMD_EFF_CSUPP,
244 [NVME_CMD_DSM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
245 [NVME_CMD_VERIFY] = NVME_CMD_EFF_CSUPP,
246 [NVME_CMD_COPY] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
247 [NVME_CMD_COMPARE] = NVME_CMD_EFF_CSUPP,
248 [NVME_CMD_ZONE_APPEND] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
249 [NVME_CMD_ZONE_MGMT_SEND] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
250 [NVME_CMD_ZONE_MGMT_RECV] = NVME_CMD_EFF_CSUPP,
253 static void nvme_process_sq(void *opaque);
255 static uint16_t nvme_sqid(NvmeRequest *req)
257 return le16_to_cpu(req->sq->sqid);
260 static void nvme_assign_zone_state(NvmeNamespace *ns, NvmeZone *zone,
261 NvmeZoneState state)
263 if (QTAILQ_IN_USE(zone, entry)) {
264 switch (nvme_get_zone_state(zone)) {
265 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
266 QTAILQ_REMOVE(&ns->exp_open_zones, zone, entry);
267 break;
268 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
269 QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
270 break;
271 case NVME_ZONE_STATE_CLOSED:
272 QTAILQ_REMOVE(&ns->closed_zones, zone, entry);
273 break;
274 case NVME_ZONE_STATE_FULL:
275 QTAILQ_REMOVE(&ns->full_zones, zone, entry);
276 default:
281 nvme_set_zone_state(zone, state);
283 switch (state) {
284 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
285 QTAILQ_INSERT_TAIL(&ns->exp_open_zones, zone, entry);
286 break;
287 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
288 QTAILQ_INSERT_TAIL(&ns->imp_open_zones, zone, entry);
289 break;
290 case NVME_ZONE_STATE_CLOSED:
291 QTAILQ_INSERT_TAIL(&ns->closed_zones, zone, entry);
292 break;
293 case NVME_ZONE_STATE_FULL:
294 QTAILQ_INSERT_TAIL(&ns->full_zones, zone, entry);
295 case NVME_ZONE_STATE_READ_ONLY:
296 break;
297 default:
298 zone->d.za = 0;
303 * Check if we can open a zone without exceeding open/active limits.
304 * AOR stands for "Active and Open Resources" (see TP 4053 section 2.5).
306 static int nvme_aor_check(NvmeNamespace *ns, uint32_t act, uint32_t opn)
308 if (ns->params.max_active_zones != 0 &&
309 ns->nr_active_zones + act > ns->params.max_active_zones) {
310 trace_pci_nvme_err_insuff_active_res(ns->params.max_active_zones);
311 return NVME_ZONE_TOO_MANY_ACTIVE | NVME_DNR;
313 if (ns->params.max_open_zones != 0 &&
314 ns->nr_open_zones + opn > ns->params.max_open_zones) {
315 trace_pci_nvme_err_insuff_open_res(ns->params.max_open_zones);
316 return NVME_ZONE_TOO_MANY_OPEN | NVME_DNR;
319 return NVME_SUCCESS;
322 static bool nvme_addr_is_cmb(NvmeCtrl *n, hwaddr addr)
324 hwaddr hi, lo;
326 if (!n->cmb.cmse) {
327 return false;
330 lo = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
331 hi = lo + int128_get64(n->cmb.mem.size);
333 return addr >= lo && addr < hi;
336 static inline void *nvme_addr_to_cmb(NvmeCtrl *n, hwaddr addr)
338 hwaddr base = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
339 return &n->cmb.buf[addr - base];
342 static bool nvme_addr_is_pmr(NvmeCtrl *n, hwaddr addr)
344 hwaddr hi;
346 if (!n->pmr.cmse) {
347 return false;
350 hi = n->pmr.cba + int128_get64(n->pmr.dev->mr.size);
352 return addr >= n->pmr.cba && addr < hi;
355 static inline void *nvme_addr_to_pmr(NvmeCtrl *n, hwaddr addr)
357 return memory_region_get_ram_ptr(&n->pmr.dev->mr) + (addr - n->pmr.cba);
360 static int nvme_addr_read(NvmeCtrl *n, hwaddr addr, void *buf, int size)
362 hwaddr hi = addr + size - 1;
363 if (hi < addr) {
364 return 1;
367 if (n->bar.cmbsz && nvme_addr_is_cmb(n, addr) && nvme_addr_is_cmb(n, hi)) {
368 memcpy(buf, nvme_addr_to_cmb(n, addr), size);
369 return 0;
372 if (nvme_addr_is_pmr(n, addr) && nvme_addr_is_pmr(n, hi)) {
373 memcpy(buf, nvme_addr_to_pmr(n, addr), size);
374 return 0;
377 return pci_dma_read(&n->parent_obj, addr, buf, size);
380 static int nvme_addr_write(NvmeCtrl *n, hwaddr addr, void *buf, int size)
382 hwaddr hi = addr + size - 1;
383 if (hi < addr) {
384 return 1;
387 if (n->bar.cmbsz && nvme_addr_is_cmb(n, addr) && nvme_addr_is_cmb(n, hi)) {
388 memcpy(nvme_addr_to_cmb(n, addr), buf, size);
389 return 0;
392 if (nvme_addr_is_pmr(n, addr) && nvme_addr_is_pmr(n, hi)) {
393 memcpy(nvme_addr_to_pmr(n, addr), buf, size);
394 return 0;
397 return pci_dma_write(&n->parent_obj, addr, buf, size);
400 static bool nvme_nsid_valid(NvmeCtrl *n, uint32_t nsid)
402 return nsid &&
403 (nsid == NVME_NSID_BROADCAST || nsid <= NVME_MAX_NAMESPACES);
406 static int nvme_check_sqid(NvmeCtrl *n, uint16_t sqid)
408 return sqid < n->params.max_ioqpairs + 1 && n->sq[sqid] != NULL ? 0 : -1;
411 static int nvme_check_cqid(NvmeCtrl *n, uint16_t cqid)
413 return cqid < n->params.max_ioqpairs + 1 && n->cq[cqid] != NULL ? 0 : -1;
416 static void nvme_inc_cq_tail(NvmeCQueue *cq)
418 cq->tail++;
419 if (cq->tail >= cq->size) {
420 cq->tail = 0;
421 cq->phase = !cq->phase;
425 static void nvme_inc_sq_head(NvmeSQueue *sq)
427 sq->head = (sq->head + 1) % sq->size;
430 static uint8_t nvme_cq_full(NvmeCQueue *cq)
432 return (cq->tail + 1) % cq->size == cq->head;
435 static uint8_t nvme_sq_empty(NvmeSQueue *sq)
437 return sq->head == sq->tail;
440 static void nvme_irq_check(NvmeCtrl *n)
442 if (msix_enabled(&(n->parent_obj))) {
443 return;
445 if (~n->bar.intms & n->irq_status) {
446 pci_irq_assert(&n->parent_obj);
447 } else {
448 pci_irq_deassert(&n->parent_obj);
452 static void nvme_irq_assert(NvmeCtrl *n, NvmeCQueue *cq)
454 if (cq->irq_enabled) {
455 if (msix_enabled(&(n->parent_obj))) {
456 trace_pci_nvme_irq_msix(cq->vector);
457 msix_notify(&(n->parent_obj), cq->vector);
458 } else {
459 trace_pci_nvme_irq_pin();
460 assert(cq->vector < 32);
461 n->irq_status |= 1 << cq->vector;
462 nvme_irq_check(n);
464 } else {
465 trace_pci_nvme_irq_masked();
469 static void nvme_irq_deassert(NvmeCtrl *n, NvmeCQueue *cq)
471 if (cq->irq_enabled) {
472 if (msix_enabled(&(n->parent_obj))) {
473 return;
474 } else {
475 assert(cq->vector < 32);
476 if (!n->cq_pending) {
477 n->irq_status &= ~(1 << cq->vector);
479 nvme_irq_check(n);
484 static void nvme_req_clear(NvmeRequest *req)
486 req->ns = NULL;
487 req->opaque = NULL;
488 req->aiocb = NULL;
489 memset(&req->cqe, 0x0, sizeof(req->cqe));
490 req->status = NVME_SUCCESS;
493 static inline void nvme_sg_init(NvmeCtrl *n, NvmeSg *sg, bool dma)
495 if (dma) {
496 pci_dma_sglist_init(&sg->qsg, &n->parent_obj, 0);
497 sg->flags = NVME_SG_DMA;
498 } else {
499 qemu_iovec_init(&sg->iov, 0);
502 sg->flags |= NVME_SG_ALLOC;
505 static inline void nvme_sg_unmap(NvmeSg *sg)
507 if (!(sg->flags & NVME_SG_ALLOC)) {
508 return;
511 if (sg->flags & NVME_SG_DMA) {
512 qemu_sglist_destroy(&sg->qsg);
513 } else {
514 qemu_iovec_destroy(&sg->iov);
517 memset(sg, 0x0, sizeof(*sg));
521 * When metadata is transfered as extended LBAs, the DPTR mapped into `sg`
522 * holds both data and metadata. This function splits the data and metadata
523 * into two separate QSG/IOVs.
525 static void nvme_sg_split(NvmeSg *sg, NvmeNamespace *ns, NvmeSg *data,
526 NvmeSg *mdata)
528 NvmeSg *dst = data;
529 uint32_t trans_len, count = ns->lbasz;
530 uint64_t offset = 0;
531 bool dma = sg->flags & NVME_SG_DMA;
532 size_t sge_len;
533 size_t sg_len = dma ? sg->qsg.size : sg->iov.size;
534 int sg_idx = 0;
536 assert(sg->flags & NVME_SG_ALLOC);
538 while (sg_len) {
539 sge_len = dma ? sg->qsg.sg[sg_idx].len : sg->iov.iov[sg_idx].iov_len;
541 trans_len = MIN(sg_len, count);
542 trans_len = MIN(trans_len, sge_len - offset);
544 if (dst) {
545 if (dma) {
546 qemu_sglist_add(&dst->qsg, sg->qsg.sg[sg_idx].base + offset,
547 trans_len);
548 } else {
549 qemu_iovec_add(&dst->iov,
550 sg->iov.iov[sg_idx].iov_base + offset,
551 trans_len);
555 sg_len -= trans_len;
556 count -= trans_len;
557 offset += trans_len;
559 if (count == 0) {
560 dst = (dst == data) ? mdata : data;
561 count = (dst == data) ? ns->lbasz : ns->lbaf.ms;
564 if (sge_len == offset) {
565 offset = 0;
566 sg_idx++;
571 static uint16_t nvme_map_addr_cmb(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
572 size_t len)
574 if (!len) {
575 return NVME_SUCCESS;
578 trace_pci_nvme_map_addr_cmb(addr, len);
580 if (!nvme_addr_is_cmb(n, addr) || !nvme_addr_is_cmb(n, addr + len - 1)) {
581 return NVME_DATA_TRAS_ERROR;
584 qemu_iovec_add(iov, nvme_addr_to_cmb(n, addr), len);
586 return NVME_SUCCESS;
589 static uint16_t nvme_map_addr_pmr(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
590 size_t len)
592 if (!len) {
593 return NVME_SUCCESS;
596 if (!nvme_addr_is_pmr(n, addr) || !nvme_addr_is_pmr(n, addr + len - 1)) {
597 return NVME_DATA_TRAS_ERROR;
600 qemu_iovec_add(iov, nvme_addr_to_pmr(n, addr), len);
602 return NVME_SUCCESS;
605 static uint16_t nvme_map_addr(NvmeCtrl *n, NvmeSg *sg, hwaddr addr, size_t len)
607 bool cmb = false, pmr = false;
609 if (!len) {
610 return NVME_SUCCESS;
613 trace_pci_nvme_map_addr(addr, len);
615 if (nvme_addr_is_cmb(n, addr)) {
616 cmb = true;
617 } else if (nvme_addr_is_pmr(n, addr)) {
618 pmr = true;
621 if (cmb || pmr) {
622 if (sg->flags & NVME_SG_DMA) {
623 return NVME_INVALID_USE_OF_CMB | NVME_DNR;
626 if (cmb) {
627 return nvme_map_addr_cmb(n, &sg->iov, addr, len);
628 } else {
629 return nvme_map_addr_pmr(n, &sg->iov, addr, len);
633 if (!(sg->flags & NVME_SG_DMA)) {
634 return NVME_INVALID_USE_OF_CMB | NVME_DNR;
637 qemu_sglist_add(&sg->qsg, addr, len);
639 return NVME_SUCCESS;
642 static inline bool nvme_addr_is_dma(NvmeCtrl *n, hwaddr addr)
644 return !(nvme_addr_is_cmb(n, addr) || nvme_addr_is_pmr(n, addr));
647 static uint16_t nvme_map_prp(NvmeCtrl *n, NvmeSg *sg, uint64_t prp1,
648 uint64_t prp2, uint32_t len)
650 hwaddr trans_len = n->page_size - (prp1 % n->page_size);
651 trans_len = MIN(len, trans_len);
652 int num_prps = (len >> n->page_bits) + 1;
653 uint16_t status;
654 int ret;
656 trace_pci_nvme_map_prp(trans_len, len, prp1, prp2, num_prps);
658 nvme_sg_init(n, sg, nvme_addr_is_dma(n, prp1));
660 status = nvme_map_addr(n, sg, prp1, trans_len);
661 if (status) {
662 goto unmap;
665 len -= trans_len;
666 if (len) {
667 if (len > n->page_size) {
668 uint64_t prp_list[n->max_prp_ents];
669 uint32_t nents, prp_trans;
670 int i = 0;
673 * The first PRP list entry, pointed to by PRP2 may contain offset.
674 * Hence, we need to calculate the number of entries in based on
675 * that offset.
677 nents = (n->page_size - (prp2 & (n->page_size - 1))) >> 3;
678 prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);
679 ret = nvme_addr_read(n, prp2, (void *)prp_list, prp_trans);
680 if (ret) {
681 trace_pci_nvme_err_addr_read(prp2);
682 status = NVME_DATA_TRAS_ERROR;
683 goto unmap;
685 while (len != 0) {
686 uint64_t prp_ent = le64_to_cpu(prp_list[i]);
688 if (i == nents - 1 && len > n->page_size) {
689 if (unlikely(prp_ent & (n->page_size - 1))) {
690 trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
691 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
692 goto unmap;
695 i = 0;
696 nents = (len + n->page_size - 1) >> n->page_bits;
697 nents = MIN(nents, n->max_prp_ents);
698 prp_trans = nents * sizeof(uint64_t);
699 ret = nvme_addr_read(n, prp_ent, (void *)prp_list,
700 prp_trans);
701 if (ret) {
702 trace_pci_nvme_err_addr_read(prp_ent);
703 status = NVME_DATA_TRAS_ERROR;
704 goto unmap;
706 prp_ent = le64_to_cpu(prp_list[i]);
709 if (unlikely(prp_ent & (n->page_size - 1))) {
710 trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
711 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
712 goto unmap;
715 trans_len = MIN(len, n->page_size);
716 status = nvme_map_addr(n, sg, prp_ent, trans_len);
717 if (status) {
718 goto unmap;
721 len -= trans_len;
722 i++;
724 } else {
725 if (unlikely(prp2 & (n->page_size - 1))) {
726 trace_pci_nvme_err_invalid_prp2_align(prp2);
727 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
728 goto unmap;
730 status = nvme_map_addr(n, sg, prp2, len);
731 if (status) {
732 goto unmap;
737 return NVME_SUCCESS;
739 unmap:
740 nvme_sg_unmap(sg);
741 return status;
745 * Map 'nsgld' data descriptors from 'segment'. The function will subtract the
746 * number of bytes mapped in len.
748 static uint16_t nvme_map_sgl_data(NvmeCtrl *n, NvmeSg *sg,
749 NvmeSglDescriptor *segment, uint64_t nsgld,
750 size_t *len, NvmeCmd *cmd)
752 dma_addr_t addr, trans_len;
753 uint32_t dlen;
754 uint16_t status;
756 for (int i = 0; i < nsgld; i++) {
757 uint8_t type = NVME_SGL_TYPE(segment[i].type);
759 switch (type) {
760 case NVME_SGL_DESCR_TYPE_BIT_BUCKET:
761 if (cmd->opcode == NVME_CMD_WRITE) {
762 continue;
764 case NVME_SGL_DESCR_TYPE_DATA_BLOCK:
765 break;
766 case NVME_SGL_DESCR_TYPE_SEGMENT:
767 case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
768 return NVME_INVALID_NUM_SGL_DESCRS | NVME_DNR;
769 default:
770 return NVME_SGL_DESCR_TYPE_INVALID | NVME_DNR;
773 dlen = le32_to_cpu(segment[i].len);
775 if (!dlen) {
776 continue;
779 if (*len == 0) {
781 * All data has been mapped, but the SGL contains additional
782 * segments and/or descriptors. The controller might accept
783 * ignoring the rest of the SGL.
785 uint32_t sgls = le32_to_cpu(n->id_ctrl.sgls);
786 if (sgls & NVME_CTRL_SGLS_EXCESS_LENGTH) {
787 break;
790 trace_pci_nvme_err_invalid_sgl_excess_length(dlen);
791 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
794 trans_len = MIN(*len, dlen);
796 if (type == NVME_SGL_DESCR_TYPE_BIT_BUCKET) {
797 goto next;
800 addr = le64_to_cpu(segment[i].addr);
802 if (UINT64_MAX - addr < dlen) {
803 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
806 status = nvme_map_addr(n, sg, addr, trans_len);
807 if (status) {
808 return status;
811 next:
812 *len -= trans_len;
815 return NVME_SUCCESS;
818 static uint16_t nvme_map_sgl(NvmeCtrl *n, NvmeSg *sg, NvmeSglDescriptor sgl,
819 size_t len, NvmeCmd *cmd)
822 * Read the segment in chunks of 256 descriptors (one 4k page) to avoid
823 * dynamically allocating a potentially huge SGL. The spec allows the SGL
824 * to be larger (as in number of bytes required to describe the SGL
825 * descriptors and segment chain) than the command transfer size, so it is
826 * not bounded by MDTS.
828 const int SEG_CHUNK_SIZE = 256;
830 NvmeSglDescriptor segment[SEG_CHUNK_SIZE], *sgld, *last_sgld;
831 uint64_t nsgld;
832 uint32_t seg_len;
833 uint16_t status;
834 hwaddr addr;
835 int ret;
837 sgld = &sgl;
838 addr = le64_to_cpu(sgl.addr);
840 trace_pci_nvme_map_sgl(NVME_SGL_TYPE(sgl.type), len);
842 nvme_sg_init(n, sg, nvme_addr_is_dma(n, addr));
845 * If the entire transfer can be described with a single data block it can
846 * be mapped directly.
848 if (NVME_SGL_TYPE(sgl.type) == NVME_SGL_DESCR_TYPE_DATA_BLOCK) {
849 status = nvme_map_sgl_data(n, sg, sgld, 1, &len, cmd);
850 if (status) {
851 goto unmap;
854 goto out;
857 for (;;) {
858 switch (NVME_SGL_TYPE(sgld->type)) {
859 case NVME_SGL_DESCR_TYPE_SEGMENT:
860 case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
861 break;
862 default:
863 return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
866 seg_len = le32_to_cpu(sgld->len);
868 /* check the length of the (Last) Segment descriptor */
869 if ((!seg_len || seg_len & 0xf) &&
870 (NVME_SGL_TYPE(sgld->type) != NVME_SGL_DESCR_TYPE_BIT_BUCKET)) {
871 return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
874 if (UINT64_MAX - addr < seg_len) {
875 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
878 nsgld = seg_len / sizeof(NvmeSglDescriptor);
880 while (nsgld > SEG_CHUNK_SIZE) {
881 if (nvme_addr_read(n, addr, segment, sizeof(segment))) {
882 trace_pci_nvme_err_addr_read(addr);
883 status = NVME_DATA_TRAS_ERROR;
884 goto unmap;
887 status = nvme_map_sgl_data(n, sg, segment, SEG_CHUNK_SIZE,
888 &len, cmd);
889 if (status) {
890 goto unmap;
893 nsgld -= SEG_CHUNK_SIZE;
894 addr += SEG_CHUNK_SIZE * sizeof(NvmeSglDescriptor);
897 ret = nvme_addr_read(n, addr, segment, nsgld *
898 sizeof(NvmeSglDescriptor));
899 if (ret) {
900 trace_pci_nvme_err_addr_read(addr);
901 status = NVME_DATA_TRAS_ERROR;
902 goto unmap;
905 last_sgld = &segment[nsgld - 1];
908 * If the segment ends with a Data Block or Bit Bucket Descriptor Type,
909 * then we are done.
911 switch (NVME_SGL_TYPE(last_sgld->type)) {
912 case NVME_SGL_DESCR_TYPE_DATA_BLOCK:
913 case NVME_SGL_DESCR_TYPE_BIT_BUCKET:
914 status = nvme_map_sgl_data(n, sg, segment, nsgld, &len, cmd);
915 if (status) {
916 goto unmap;
919 goto out;
921 default:
922 break;
926 * If the last descriptor was not a Data Block or Bit Bucket, then the
927 * current segment must not be a Last Segment.
929 if (NVME_SGL_TYPE(sgld->type) == NVME_SGL_DESCR_TYPE_LAST_SEGMENT) {
930 status = NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
931 goto unmap;
934 sgld = last_sgld;
935 addr = le64_to_cpu(sgld->addr);
938 * Do not map the last descriptor; it will be a Segment or Last Segment
939 * descriptor and is handled by the next iteration.
941 status = nvme_map_sgl_data(n, sg, segment, nsgld - 1, &len, cmd);
942 if (status) {
943 goto unmap;
947 out:
948 /* if there is any residual left in len, the SGL was too short */
949 if (len) {
950 status = NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
951 goto unmap;
954 return NVME_SUCCESS;
956 unmap:
957 nvme_sg_unmap(sg);
958 return status;
961 uint16_t nvme_map_dptr(NvmeCtrl *n, NvmeSg *sg, size_t len,
962 NvmeCmd *cmd)
964 uint64_t prp1, prp2;
966 switch (NVME_CMD_FLAGS_PSDT(cmd->flags)) {
967 case NVME_PSDT_PRP:
968 prp1 = le64_to_cpu(cmd->dptr.prp1);
969 prp2 = le64_to_cpu(cmd->dptr.prp2);
971 return nvme_map_prp(n, sg, prp1, prp2, len);
972 case NVME_PSDT_SGL_MPTR_CONTIGUOUS:
973 case NVME_PSDT_SGL_MPTR_SGL:
974 return nvme_map_sgl(n, sg, cmd->dptr.sgl, len, cmd);
975 default:
976 return NVME_INVALID_FIELD;
980 static uint16_t nvme_map_mptr(NvmeCtrl *n, NvmeSg *sg, size_t len,
981 NvmeCmd *cmd)
983 int psdt = NVME_CMD_FLAGS_PSDT(cmd->flags);
984 hwaddr mptr = le64_to_cpu(cmd->mptr);
985 uint16_t status;
987 if (psdt == NVME_PSDT_SGL_MPTR_SGL) {
988 NvmeSglDescriptor sgl;
990 if (nvme_addr_read(n, mptr, &sgl, sizeof(sgl))) {
991 return NVME_DATA_TRAS_ERROR;
994 status = nvme_map_sgl(n, sg, sgl, len, cmd);
995 if (status && (status & 0x7ff) == NVME_DATA_SGL_LEN_INVALID) {
996 status = NVME_MD_SGL_LEN_INVALID | NVME_DNR;
999 return status;
1002 nvme_sg_init(n, sg, nvme_addr_is_dma(n, mptr));
1003 status = nvme_map_addr(n, sg, mptr, len);
1004 if (status) {
1005 nvme_sg_unmap(sg);
1008 return status;
1011 static uint16_t nvme_map_data(NvmeCtrl *n, uint32_t nlb, NvmeRequest *req)
1013 NvmeNamespace *ns = req->ns;
1014 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1015 bool pi = !!NVME_ID_NS_DPS_TYPE(ns->id_ns.dps);
1016 bool pract = !!(le16_to_cpu(rw->control) & NVME_RW_PRINFO_PRACT);
1017 size_t len = nvme_l2b(ns, nlb);
1018 uint16_t status;
1020 if (nvme_ns_ext(ns) && !(pi && pract && ns->lbaf.ms == 8)) {
1021 NvmeSg sg;
1023 len += nvme_m2b(ns, nlb);
1025 status = nvme_map_dptr(n, &sg, len, &req->cmd);
1026 if (status) {
1027 return status;
1030 nvme_sg_init(n, &req->sg, sg.flags & NVME_SG_DMA);
1031 nvme_sg_split(&sg, ns, &req->sg, NULL);
1032 nvme_sg_unmap(&sg);
1034 return NVME_SUCCESS;
1037 return nvme_map_dptr(n, &req->sg, len, &req->cmd);
1040 static uint16_t nvme_map_mdata(NvmeCtrl *n, uint32_t nlb, NvmeRequest *req)
1042 NvmeNamespace *ns = req->ns;
1043 size_t len = nvme_m2b(ns, nlb);
1044 uint16_t status;
1046 if (nvme_ns_ext(ns)) {
1047 NvmeSg sg;
1049 len += nvme_l2b(ns, nlb);
1051 status = nvme_map_dptr(n, &sg, len, &req->cmd);
1052 if (status) {
1053 return status;
1056 nvme_sg_init(n, &req->sg, sg.flags & NVME_SG_DMA);
1057 nvme_sg_split(&sg, ns, NULL, &req->sg);
1058 nvme_sg_unmap(&sg);
1060 return NVME_SUCCESS;
1063 return nvme_map_mptr(n, &req->sg, len, &req->cmd);
1066 static uint16_t nvme_tx_interleaved(NvmeCtrl *n, NvmeSg *sg, uint8_t *ptr,
1067 uint32_t len, uint32_t bytes,
1068 int32_t skip_bytes, int64_t offset,
1069 NvmeTxDirection dir)
1071 hwaddr addr;
1072 uint32_t trans_len, count = bytes;
1073 bool dma = sg->flags & NVME_SG_DMA;
1074 int64_t sge_len;
1075 int sg_idx = 0;
1076 int ret;
1078 assert(sg->flags & NVME_SG_ALLOC);
1080 while (len) {
1081 sge_len = dma ? sg->qsg.sg[sg_idx].len : sg->iov.iov[sg_idx].iov_len;
1083 if (sge_len - offset < 0) {
1084 offset -= sge_len;
1085 sg_idx++;
1086 continue;
1089 if (sge_len == offset) {
1090 offset = 0;
1091 sg_idx++;
1092 continue;
1095 trans_len = MIN(len, count);
1096 trans_len = MIN(trans_len, sge_len - offset);
1098 if (dma) {
1099 addr = sg->qsg.sg[sg_idx].base + offset;
1100 } else {
1101 addr = (hwaddr)(uintptr_t)sg->iov.iov[sg_idx].iov_base + offset;
1104 if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1105 ret = nvme_addr_read(n, addr, ptr, trans_len);
1106 } else {
1107 ret = nvme_addr_write(n, addr, ptr, trans_len);
1110 if (ret) {
1111 return NVME_DATA_TRAS_ERROR;
1114 ptr += trans_len;
1115 len -= trans_len;
1116 count -= trans_len;
1117 offset += trans_len;
1119 if (count == 0) {
1120 count = bytes;
1121 offset += skip_bytes;
1125 return NVME_SUCCESS;
1128 static uint16_t nvme_tx(NvmeCtrl *n, NvmeSg *sg, uint8_t *ptr, uint32_t len,
1129 NvmeTxDirection dir)
1131 assert(sg->flags & NVME_SG_ALLOC);
1133 if (sg->flags & NVME_SG_DMA) {
1134 uint64_t residual;
1136 if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1137 residual = dma_buf_write(ptr, len, &sg->qsg);
1138 } else {
1139 residual = dma_buf_read(ptr, len, &sg->qsg);
1142 if (unlikely(residual)) {
1143 trace_pci_nvme_err_invalid_dma();
1144 return NVME_INVALID_FIELD | NVME_DNR;
1146 } else {
1147 size_t bytes;
1149 if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1150 bytes = qemu_iovec_to_buf(&sg->iov, 0, ptr, len);
1151 } else {
1152 bytes = qemu_iovec_from_buf(&sg->iov, 0, ptr, len);
1155 if (unlikely(bytes != len)) {
1156 trace_pci_nvme_err_invalid_dma();
1157 return NVME_INVALID_FIELD | NVME_DNR;
1161 return NVME_SUCCESS;
1164 static inline uint16_t nvme_c2h(NvmeCtrl *n, uint8_t *ptr, uint32_t len,
1165 NvmeRequest *req)
1167 uint16_t status;
1169 status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
1170 if (status) {
1171 return status;
1174 return nvme_tx(n, &req->sg, ptr, len, NVME_TX_DIRECTION_FROM_DEVICE);
1177 static inline uint16_t nvme_h2c(NvmeCtrl *n, uint8_t *ptr, uint32_t len,
1178 NvmeRequest *req)
1180 uint16_t status;
1182 status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
1183 if (status) {
1184 return status;
1187 return nvme_tx(n, &req->sg, ptr, len, NVME_TX_DIRECTION_TO_DEVICE);
1190 uint16_t nvme_bounce_data(NvmeCtrl *n, uint8_t *ptr, uint32_t len,
1191 NvmeTxDirection dir, NvmeRequest *req)
1193 NvmeNamespace *ns = req->ns;
1194 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1195 bool pi = !!NVME_ID_NS_DPS_TYPE(ns->id_ns.dps);
1196 bool pract = !!(le16_to_cpu(rw->control) & NVME_RW_PRINFO_PRACT);
1198 if (nvme_ns_ext(ns) && !(pi && pract && ns->lbaf.ms == 8)) {
1199 return nvme_tx_interleaved(n, &req->sg, ptr, len, ns->lbasz,
1200 ns->lbaf.ms, 0, dir);
1203 return nvme_tx(n, &req->sg, ptr, len, dir);
1206 uint16_t nvme_bounce_mdata(NvmeCtrl *n, uint8_t *ptr, uint32_t len,
1207 NvmeTxDirection dir, NvmeRequest *req)
1209 NvmeNamespace *ns = req->ns;
1210 uint16_t status;
1212 if (nvme_ns_ext(ns)) {
1213 return nvme_tx_interleaved(n, &req->sg, ptr, len, ns->lbaf.ms,
1214 ns->lbasz, ns->lbasz, dir);
1217 nvme_sg_unmap(&req->sg);
1219 status = nvme_map_mptr(n, &req->sg, len, &req->cmd);
1220 if (status) {
1221 return status;
1224 return nvme_tx(n, &req->sg, ptr, len, dir);
1227 static inline void nvme_blk_read(BlockBackend *blk, int64_t offset,
1228 BlockCompletionFunc *cb, NvmeRequest *req)
1230 assert(req->sg.flags & NVME_SG_ALLOC);
1232 if (req->sg.flags & NVME_SG_DMA) {
1233 req->aiocb = dma_blk_read(blk, &req->sg.qsg, offset, BDRV_SECTOR_SIZE,
1234 cb, req);
1235 } else {
1236 req->aiocb = blk_aio_preadv(blk, offset, &req->sg.iov, 0, cb, req);
1240 static inline void nvme_blk_write(BlockBackend *blk, int64_t offset,
1241 BlockCompletionFunc *cb, NvmeRequest *req)
1243 assert(req->sg.flags & NVME_SG_ALLOC);
1245 if (req->sg.flags & NVME_SG_DMA) {
1246 req->aiocb = dma_blk_write(blk, &req->sg.qsg, offset, BDRV_SECTOR_SIZE,
1247 cb, req);
1248 } else {
1249 req->aiocb = blk_aio_pwritev(blk, offset, &req->sg.iov, 0, cb, req);
1253 static void nvme_post_cqes(void *opaque)
1255 NvmeCQueue *cq = opaque;
1256 NvmeCtrl *n = cq->ctrl;
1257 NvmeRequest *req, *next;
1258 bool pending = cq->head != cq->tail;
1259 int ret;
1261 QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {
1262 NvmeSQueue *sq;
1263 hwaddr addr;
1265 if (nvme_cq_full(cq)) {
1266 break;
1269 sq = req->sq;
1270 req->cqe.status = cpu_to_le16((req->status << 1) | cq->phase);
1271 req->cqe.sq_id = cpu_to_le16(sq->sqid);
1272 req->cqe.sq_head = cpu_to_le16(sq->head);
1273 addr = cq->dma_addr + cq->tail * n->cqe_size;
1274 ret = pci_dma_write(&n->parent_obj, addr, (void *)&req->cqe,
1275 sizeof(req->cqe));
1276 if (ret) {
1277 trace_pci_nvme_err_addr_write(addr);
1278 trace_pci_nvme_err_cfs();
1279 n->bar.csts = NVME_CSTS_FAILED;
1280 break;
1282 QTAILQ_REMOVE(&cq->req_list, req, entry);
1283 nvme_inc_cq_tail(cq);
1284 nvme_sg_unmap(&req->sg);
1285 QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);
1287 if (cq->tail != cq->head) {
1288 if (cq->irq_enabled && !pending) {
1289 n->cq_pending++;
1292 nvme_irq_assert(n, cq);
1296 static void nvme_enqueue_req_completion(NvmeCQueue *cq, NvmeRequest *req)
1298 assert(cq->cqid == req->sq->cqid);
1299 trace_pci_nvme_enqueue_req_completion(nvme_cid(req), cq->cqid,
1300 le32_to_cpu(req->cqe.result),
1301 le32_to_cpu(req->cqe.dw1),
1302 req->status);
1304 if (req->status) {
1305 trace_pci_nvme_err_req_status(nvme_cid(req), nvme_nsid(req->ns),
1306 req->status, req->cmd.opcode);
1309 QTAILQ_REMOVE(&req->sq->out_req_list, req, entry);
1310 QTAILQ_INSERT_TAIL(&cq->req_list, req, entry);
1311 timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
1314 static void nvme_process_aers(void *opaque)
1316 NvmeCtrl *n = opaque;
1317 NvmeAsyncEvent *event, *next;
1319 trace_pci_nvme_process_aers(n->aer_queued);
1321 QTAILQ_FOREACH_SAFE(event, &n->aer_queue, entry, next) {
1322 NvmeRequest *req;
1323 NvmeAerResult *result;
1325 /* can't post cqe if there is nothing to complete */
1326 if (!n->outstanding_aers) {
1327 trace_pci_nvme_no_outstanding_aers();
1328 break;
1331 /* ignore if masked (cqe posted, but event not cleared) */
1332 if (n->aer_mask & (1 << event->result.event_type)) {
1333 trace_pci_nvme_aer_masked(event->result.event_type, n->aer_mask);
1334 continue;
1337 QTAILQ_REMOVE(&n->aer_queue, event, entry);
1338 n->aer_queued--;
1340 n->aer_mask |= 1 << event->result.event_type;
1341 n->outstanding_aers--;
1343 req = n->aer_reqs[n->outstanding_aers];
1345 result = (NvmeAerResult *) &req->cqe.result;
1346 result->event_type = event->result.event_type;
1347 result->event_info = event->result.event_info;
1348 result->log_page = event->result.log_page;
1349 g_free(event);
1351 trace_pci_nvme_aer_post_cqe(result->event_type, result->event_info,
1352 result->log_page);
1354 nvme_enqueue_req_completion(&n->admin_cq, req);
1358 static void nvme_enqueue_event(NvmeCtrl *n, uint8_t event_type,
1359 uint8_t event_info, uint8_t log_page)
1361 NvmeAsyncEvent *event;
1363 trace_pci_nvme_enqueue_event(event_type, event_info, log_page);
1365 if (n->aer_queued == n->params.aer_max_queued) {
1366 trace_pci_nvme_enqueue_event_noqueue(n->aer_queued);
1367 return;
1370 event = g_new(NvmeAsyncEvent, 1);
1371 event->result = (NvmeAerResult) {
1372 .event_type = event_type,
1373 .event_info = event_info,
1374 .log_page = log_page,
1377 QTAILQ_INSERT_TAIL(&n->aer_queue, event, entry);
1378 n->aer_queued++;
1380 nvme_process_aers(n);
1383 static void nvme_smart_event(NvmeCtrl *n, uint8_t event)
1385 uint8_t aer_info;
1387 /* Ref SPEC <Asynchronous Event Information 0x2013 SMART / Health Status> */
1388 if (!(NVME_AEC_SMART(n->features.async_config) & event)) {
1389 return;
1392 switch (event) {
1393 case NVME_SMART_SPARE:
1394 aer_info = NVME_AER_INFO_SMART_SPARE_THRESH;
1395 break;
1396 case NVME_SMART_TEMPERATURE:
1397 aer_info = NVME_AER_INFO_SMART_TEMP_THRESH;
1398 break;
1399 case NVME_SMART_RELIABILITY:
1400 case NVME_SMART_MEDIA_READ_ONLY:
1401 case NVME_SMART_FAILED_VOLATILE_MEDIA:
1402 case NVME_SMART_PMR_UNRELIABLE:
1403 aer_info = NVME_AER_INFO_SMART_RELIABILITY;
1404 break;
1405 default:
1406 return;
1409 nvme_enqueue_event(n, NVME_AER_TYPE_SMART, aer_info, NVME_LOG_SMART_INFO);
1412 static void nvme_clear_events(NvmeCtrl *n, uint8_t event_type)
1414 n->aer_mask &= ~(1 << event_type);
1415 if (!QTAILQ_EMPTY(&n->aer_queue)) {
1416 nvme_process_aers(n);
1420 static inline uint16_t nvme_check_mdts(NvmeCtrl *n, size_t len)
1422 uint8_t mdts = n->params.mdts;
1424 if (mdts && len > n->page_size << mdts) {
1425 trace_pci_nvme_err_mdts(len);
1426 return NVME_INVALID_FIELD | NVME_DNR;
1429 return NVME_SUCCESS;
1432 static inline uint16_t nvme_check_bounds(NvmeNamespace *ns, uint64_t slba,
1433 uint32_t nlb)
1435 uint64_t nsze = le64_to_cpu(ns->id_ns.nsze);
1437 if (unlikely(UINT64_MAX - slba < nlb || slba + nlb > nsze)) {
1438 trace_pci_nvme_err_invalid_lba_range(slba, nlb, nsze);
1439 return NVME_LBA_RANGE | NVME_DNR;
1442 return NVME_SUCCESS;
1445 static int nvme_block_status_all(NvmeNamespace *ns, uint64_t slba,
1446 uint32_t nlb, int flags)
1448 BlockDriverState *bs = blk_bs(ns->blkconf.blk);
1450 int64_t pnum = 0, bytes = nvme_l2b(ns, nlb);
1451 int64_t offset = nvme_l2b(ns, slba);
1452 int ret;
1455 * `pnum` holds the number of bytes after offset that shares the same
1456 * allocation status as the byte at offset. If `pnum` is different from
1457 * `bytes`, we should check the allocation status of the next range and
1458 * continue this until all bytes have been checked.
1460 do {
1461 bytes -= pnum;
1463 ret = bdrv_block_status(bs, offset, bytes, &pnum, NULL, NULL);
1464 if (ret < 0) {
1465 return ret;
1469 trace_pci_nvme_block_status(offset, bytes, pnum, ret,
1470 !!(ret & BDRV_BLOCK_ZERO));
1472 if (!(ret & flags)) {
1473 return 1;
1476 offset += pnum;
1477 } while (pnum != bytes);
1479 return 0;
1482 static uint16_t nvme_check_dulbe(NvmeNamespace *ns, uint64_t slba,
1483 uint32_t nlb)
1485 int ret;
1486 Error *err = NULL;
1488 ret = nvme_block_status_all(ns, slba, nlb, BDRV_BLOCK_DATA);
1489 if (ret) {
1490 if (ret < 0) {
1491 error_setg_errno(&err, -ret, "unable to get block status");
1492 error_report_err(err);
1494 return NVME_INTERNAL_DEV_ERROR;
1497 return NVME_DULB;
1500 return NVME_SUCCESS;
1503 static void nvme_aio_err(NvmeRequest *req, int ret)
1505 uint16_t status = NVME_SUCCESS;
1506 Error *local_err = NULL;
1508 switch (req->cmd.opcode) {
1509 case NVME_CMD_READ:
1510 status = NVME_UNRECOVERED_READ;
1511 break;
1512 case NVME_CMD_FLUSH:
1513 case NVME_CMD_WRITE:
1514 case NVME_CMD_WRITE_ZEROES:
1515 case NVME_CMD_ZONE_APPEND:
1516 status = NVME_WRITE_FAULT;
1517 break;
1518 default:
1519 status = NVME_INTERNAL_DEV_ERROR;
1520 break;
1523 trace_pci_nvme_err_aio(nvme_cid(req), strerror(-ret), status);
1525 error_setg_errno(&local_err, -ret, "aio failed");
1526 error_report_err(local_err);
1529 * Set the command status code to the first encountered error but allow a
1530 * subsequent Internal Device Error to trump it.
1532 if (req->status && status != NVME_INTERNAL_DEV_ERROR) {
1533 return;
1536 req->status = status;
1539 static inline uint32_t nvme_zone_idx(NvmeNamespace *ns, uint64_t slba)
1541 return ns->zone_size_log2 > 0 ? slba >> ns->zone_size_log2 :
1542 slba / ns->zone_size;
1545 static inline NvmeZone *nvme_get_zone_by_slba(NvmeNamespace *ns, uint64_t slba)
1547 uint32_t zone_idx = nvme_zone_idx(ns, slba);
1549 if (zone_idx >= ns->num_zones) {
1550 return NULL;
1553 return &ns->zone_array[zone_idx];
1556 static uint16_t nvme_check_zone_state_for_write(NvmeZone *zone)
1558 uint64_t zslba = zone->d.zslba;
1560 switch (nvme_get_zone_state(zone)) {
1561 case NVME_ZONE_STATE_EMPTY:
1562 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1563 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1564 case NVME_ZONE_STATE_CLOSED:
1565 return NVME_SUCCESS;
1566 case NVME_ZONE_STATE_FULL:
1567 trace_pci_nvme_err_zone_is_full(zslba);
1568 return NVME_ZONE_FULL;
1569 case NVME_ZONE_STATE_OFFLINE:
1570 trace_pci_nvme_err_zone_is_offline(zslba);
1571 return NVME_ZONE_OFFLINE;
1572 case NVME_ZONE_STATE_READ_ONLY:
1573 trace_pci_nvme_err_zone_is_read_only(zslba);
1574 return NVME_ZONE_READ_ONLY;
1575 default:
1576 assert(false);
1579 return NVME_INTERNAL_DEV_ERROR;
1582 static uint16_t nvme_check_zone_write(NvmeNamespace *ns, NvmeZone *zone,
1583 uint64_t slba, uint32_t nlb)
1585 uint64_t zcap = nvme_zone_wr_boundary(zone);
1586 uint16_t status;
1588 status = nvme_check_zone_state_for_write(zone);
1589 if (status) {
1590 return status;
1593 if (unlikely(slba != zone->w_ptr)) {
1594 trace_pci_nvme_err_write_not_at_wp(slba, zone->d.zslba, zone->w_ptr);
1595 return NVME_ZONE_INVALID_WRITE;
1598 if (unlikely((slba + nlb) > zcap)) {
1599 trace_pci_nvme_err_zone_boundary(slba, nlb, zcap);
1600 return NVME_ZONE_BOUNDARY_ERROR;
1603 return NVME_SUCCESS;
1606 static uint16_t nvme_check_zone_state_for_read(NvmeZone *zone)
1608 switch (nvme_get_zone_state(zone)) {
1609 case NVME_ZONE_STATE_EMPTY:
1610 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1611 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1612 case NVME_ZONE_STATE_FULL:
1613 case NVME_ZONE_STATE_CLOSED:
1614 case NVME_ZONE_STATE_READ_ONLY:
1615 return NVME_SUCCESS;
1616 case NVME_ZONE_STATE_OFFLINE:
1617 trace_pci_nvme_err_zone_is_offline(zone->d.zslba);
1618 return NVME_ZONE_OFFLINE;
1619 default:
1620 assert(false);
1623 return NVME_INTERNAL_DEV_ERROR;
1626 static uint16_t nvme_check_zone_read(NvmeNamespace *ns, uint64_t slba,
1627 uint32_t nlb)
1629 NvmeZone *zone;
1630 uint64_t bndry, end;
1631 uint16_t status;
1633 zone = nvme_get_zone_by_slba(ns, slba);
1634 assert(zone);
1636 bndry = nvme_zone_rd_boundary(ns, zone);
1637 end = slba + nlb;
1639 status = nvme_check_zone_state_for_read(zone);
1640 if (status) {
1642 } else if (unlikely(end > bndry)) {
1643 if (!ns->params.cross_zone_read) {
1644 status = NVME_ZONE_BOUNDARY_ERROR;
1645 } else {
1647 * Read across zone boundary - check that all subsequent
1648 * zones that are being read have an appropriate state.
1650 do {
1651 zone++;
1652 status = nvme_check_zone_state_for_read(zone);
1653 if (status) {
1654 break;
1656 } while (end > nvme_zone_rd_boundary(ns, zone));
1660 return status;
1663 static uint16_t nvme_zrm_finish(NvmeNamespace *ns, NvmeZone *zone)
1665 switch (nvme_get_zone_state(zone)) {
1666 case NVME_ZONE_STATE_FULL:
1667 return NVME_SUCCESS;
1669 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1670 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1671 nvme_aor_dec_open(ns);
1672 /* fallthrough */
1673 case NVME_ZONE_STATE_CLOSED:
1674 nvme_aor_dec_active(ns);
1675 /* fallthrough */
1676 case NVME_ZONE_STATE_EMPTY:
1677 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_FULL);
1678 return NVME_SUCCESS;
1680 default:
1681 return NVME_ZONE_INVAL_TRANSITION;
1685 static uint16_t nvme_zrm_close(NvmeNamespace *ns, NvmeZone *zone)
1687 switch (nvme_get_zone_state(zone)) {
1688 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1689 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1690 nvme_aor_dec_open(ns);
1691 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
1692 /* fall through */
1693 case NVME_ZONE_STATE_CLOSED:
1694 return NVME_SUCCESS;
1696 default:
1697 return NVME_ZONE_INVAL_TRANSITION;
1701 static uint16_t nvme_zrm_reset(NvmeNamespace *ns, NvmeZone *zone)
1703 switch (nvme_get_zone_state(zone)) {
1704 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1705 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1706 nvme_aor_dec_open(ns);
1707 /* fallthrough */
1708 case NVME_ZONE_STATE_CLOSED:
1709 nvme_aor_dec_active(ns);
1710 /* fallthrough */
1711 case NVME_ZONE_STATE_FULL:
1712 zone->w_ptr = zone->d.zslba;
1713 zone->d.wp = zone->w_ptr;
1714 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EMPTY);
1715 /* fallthrough */
1716 case NVME_ZONE_STATE_EMPTY:
1717 return NVME_SUCCESS;
1719 default:
1720 return NVME_ZONE_INVAL_TRANSITION;
1724 static void nvme_zrm_auto_transition_zone(NvmeNamespace *ns)
1726 NvmeZone *zone;
1728 if (ns->params.max_open_zones &&
1729 ns->nr_open_zones == ns->params.max_open_zones) {
1730 zone = QTAILQ_FIRST(&ns->imp_open_zones);
1731 if (zone) {
1733 * Automatically close this implicitly open zone.
1735 QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
1736 nvme_zrm_close(ns, zone);
1741 enum {
1742 NVME_ZRM_AUTO = 1 << 0,
1745 static uint16_t nvme_zrm_open_flags(NvmeCtrl *n, NvmeNamespace *ns,
1746 NvmeZone *zone, int flags)
1748 int act = 0;
1749 uint16_t status;
1751 switch (nvme_get_zone_state(zone)) {
1752 case NVME_ZONE_STATE_EMPTY:
1753 act = 1;
1755 /* fallthrough */
1757 case NVME_ZONE_STATE_CLOSED:
1758 if (n->params.auto_transition_zones) {
1759 nvme_zrm_auto_transition_zone(ns);
1761 status = nvme_aor_check(ns, act, 1);
1762 if (status) {
1763 return status;
1766 if (act) {
1767 nvme_aor_inc_active(ns);
1770 nvme_aor_inc_open(ns);
1772 if (flags & NVME_ZRM_AUTO) {
1773 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_IMPLICITLY_OPEN);
1774 return NVME_SUCCESS;
1777 /* fallthrough */
1779 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1780 if (flags & NVME_ZRM_AUTO) {
1781 return NVME_SUCCESS;
1784 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EXPLICITLY_OPEN);
1786 /* fallthrough */
1788 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1789 return NVME_SUCCESS;
1791 default:
1792 return NVME_ZONE_INVAL_TRANSITION;
1796 static inline uint16_t nvme_zrm_auto(NvmeCtrl *n, NvmeNamespace *ns,
1797 NvmeZone *zone)
1799 return nvme_zrm_open_flags(n, ns, zone, NVME_ZRM_AUTO);
1802 static inline uint16_t nvme_zrm_open(NvmeCtrl *n, NvmeNamespace *ns,
1803 NvmeZone *zone)
1805 return nvme_zrm_open_flags(n, ns, zone, 0);
1808 static void nvme_advance_zone_wp(NvmeNamespace *ns, NvmeZone *zone,
1809 uint32_t nlb)
1811 zone->d.wp += nlb;
1813 if (zone->d.wp == nvme_zone_wr_boundary(zone)) {
1814 nvme_zrm_finish(ns, zone);
1818 static void nvme_finalize_zoned_write(NvmeNamespace *ns, NvmeRequest *req)
1820 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1821 NvmeZone *zone;
1822 uint64_t slba;
1823 uint32_t nlb;
1825 slba = le64_to_cpu(rw->slba);
1826 nlb = le16_to_cpu(rw->nlb) + 1;
1827 zone = nvme_get_zone_by_slba(ns, slba);
1828 assert(zone);
1830 nvme_advance_zone_wp(ns, zone, nlb);
1833 static inline bool nvme_is_write(NvmeRequest *req)
1835 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1837 return rw->opcode == NVME_CMD_WRITE ||
1838 rw->opcode == NVME_CMD_ZONE_APPEND ||
1839 rw->opcode == NVME_CMD_WRITE_ZEROES;
1842 static AioContext *nvme_get_aio_context(BlockAIOCB *acb)
1844 return qemu_get_aio_context();
1847 static void nvme_misc_cb(void *opaque, int ret)
1849 NvmeRequest *req = opaque;
1851 trace_pci_nvme_misc_cb(nvme_cid(req));
1853 if (ret) {
1854 nvme_aio_err(req, ret);
1857 nvme_enqueue_req_completion(nvme_cq(req), req);
1860 void nvme_rw_complete_cb(void *opaque, int ret)
1862 NvmeRequest *req = opaque;
1863 NvmeNamespace *ns = req->ns;
1864 BlockBackend *blk = ns->blkconf.blk;
1865 BlockAcctCookie *acct = &req->acct;
1866 BlockAcctStats *stats = blk_get_stats(blk);
1868 trace_pci_nvme_rw_complete_cb(nvme_cid(req), blk_name(blk));
1870 if (ret) {
1871 block_acct_failed(stats, acct);
1872 nvme_aio_err(req, ret);
1873 } else {
1874 block_acct_done(stats, acct);
1877 if (ns->params.zoned && nvme_is_write(req)) {
1878 nvme_finalize_zoned_write(ns, req);
1881 nvme_enqueue_req_completion(nvme_cq(req), req);
1884 static void nvme_rw_cb(void *opaque, int ret)
1886 NvmeRequest *req = opaque;
1887 NvmeNamespace *ns = req->ns;
1889 BlockBackend *blk = ns->blkconf.blk;
1891 trace_pci_nvme_rw_cb(nvme_cid(req), blk_name(blk));
1893 if (ret) {
1894 goto out;
1897 if (ns->lbaf.ms) {
1898 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1899 uint64_t slba = le64_to_cpu(rw->slba);
1900 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
1901 uint64_t offset = nvme_moff(ns, slba);
1903 if (req->cmd.opcode == NVME_CMD_WRITE_ZEROES) {
1904 size_t mlen = nvme_m2b(ns, nlb);
1906 req->aiocb = blk_aio_pwrite_zeroes(blk, offset, mlen,
1907 BDRV_REQ_MAY_UNMAP,
1908 nvme_rw_complete_cb, req);
1909 return;
1912 if (nvme_ns_ext(ns) || req->cmd.mptr) {
1913 uint16_t status;
1915 nvme_sg_unmap(&req->sg);
1916 status = nvme_map_mdata(nvme_ctrl(req), nlb, req);
1917 if (status) {
1918 ret = -EFAULT;
1919 goto out;
1922 if (req->cmd.opcode == NVME_CMD_READ) {
1923 return nvme_blk_read(blk, offset, nvme_rw_complete_cb, req);
1926 return nvme_blk_write(blk, offset, nvme_rw_complete_cb, req);
1930 out:
1931 nvme_rw_complete_cb(req, ret);
1934 static void nvme_verify_cb(void *opaque, int ret)
1936 NvmeBounceContext *ctx = opaque;
1937 NvmeRequest *req = ctx->req;
1938 NvmeNamespace *ns = req->ns;
1939 BlockBackend *blk = ns->blkconf.blk;
1940 BlockAcctCookie *acct = &req->acct;
1941 BlockAcctStats *stats = blk_get_stats(blk);
1942 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1943 uint64_t slba = le64_to_cpu(rw->slba);
1944 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
1945 uint16_t apptag = le16_to_cpu(rw->apptag);
1946 uint16_t appmask = le16_to_cpu(rw->appmask);
1947 uint32_t reftag = le32_to_cpu(rw->reftag);
1948 uint16_t status;
1950 trace_pci_nvme_verify_cb(nvme_cid(req), prinfo, apptag, appmask, reftag);
1952 if (ret) {
1953 block_acct_failed(stats, acct);
1954 nvme_aio_err(req, ret);
1955 goto out;
1958 block_acct_done(stats, acct);
1960 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
1961 status = nvme_dif_mangle_mdata(ns, ctx->mdata.bounce,
1962 ctx->mdata.iov.size, slba);
1963 if (status) {
1964 req->status = status;
1965 goto out;
1968 req->status = nvme_dif_check(ns, ctx->data.bounce, ctx->data.iov.size,
1969 ctx->mdata.bounce, ctx->mdata.iov.size,
1970 prinfo, slba, apptag, appmask, &reftag);
1973 out:
1974 qemu_iovec_destroy(&ctx->data.iov);
1975 g_free(ctx->data.bounce);
1977 qemu_iovec_destroy(&ctx->mdata.iov);
1978 g_free(ctx->mdata.bounce);
1980 g_free(ctx);
1982 nvme_enqueue_req_completion(nvme_cq(req), req);
1986 static void nvme_verify_mdata_in_cb(void *opaque, int ret)
1988 NvmeBounceContext *ctx = opaque;
1989 NvmeRequest *req = ctx->req;
1990 NvmeNamespace *ns = req->ns;
1991 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1992 uint64_t slba = le64_to_cpu(rw->slba);
1993 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
1994 size_t mlen = nvme_m2b(ns, nlb);
1995 uint64_t offset = nvme_moff(ns, slba);
1996 BlockBackend *blk = ns->blkconf.blk;
1998 trace_pci_nvme_verify_mdata_in_cb(nvme_cid(req), blk_name(blk));
2000 if (ret) {
2001 goto out;
2004 ctx->mdata.bounce = g_malloc(mlen);
2006 qemu_iovec_reset(&ctx->mdata.iov);
2007 qemu_iovec_add(&ctx->mdata.iov, ctx->mdata.bounce, mlen);
2009 req->aiocb = blk_aio_preadv(blk, offset, &ctx->mdata.iov, 0,
2010 nvme_verify_cb, ctx);
2011 return;
2013 out:
2014 nvme_verify_cb(ctx, ret);
2017 struct nvme_compare_ctx {
2018 struct {
2019 QEMUIOVector iov;
2020 uint8_t *bounce;
2021 } data;
2023 struct {
2024 QEMUIOVector iov;
2025 uint8_t *bounce;
2026 } mdata;
2029 static void nvme_compare_mdata_cb(void *opaque, int ret)
2031 NvmeRequest *req = opaque;
2032 NvmeNamespace *ns = req->ns;
2033 NvmeCtrl *n = nvme_ctrl(req);
2034 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2035 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2036 uint16_t apptag = le16_to_cpu(rw->apptag);
2037 uint16_t appmask = le16_to_cpu(rw->appmask);
2038 uint32_t reftag = le32_to_cpu(rw->reftag);
2039 struct nvme_compare_ctx *ctx = req->opaque;
2040 g_autofree uint8_t *buf = NULL;
2041 BlockBackend *blk = ns->blkconf.blk;
2042 BlockAcctCookie *acct = &req->acct;
2043 BlockAcctStats *stats = blk_get_stats(blk);
2044 uint16_t status = NVME_SUCCESS;
2046 trace_pci_nvme_compare_mdata_cb(nvme_cid(req));
2048 if (ret) {
2049 block_acct_failed(stats, acct);
2050 nvme_aio_err(req, ret);
2051 goto out;
2054 buf = g_malloc(ctx->mdata.iov.size);
2056 status = nvme_bounce_mdata(n, buf, ctx->mdata.iov.size,
2057 NVME_TX_DIRECTION_TO_DEVICE, req);
2058 if (status) {
2059 req->status = status;
2060 goto out;
2063 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2064 uint64_t slba = le64_to_cpu(rw->slba);
2065 uint8_t *bufp;
2066 uint8_t *mbufp = ctx->mdata.bounce;
2067 uint8_t *end = mbufp + ctx->mdata.iov.size;
2068 int16_t pil = 0;
2070 status = nvme_dif_check(ns, ctx->data.bounce, ctx->data.iov.size,
2071 ctx->mdata.bounce, ctx->mdata.iov.size, prinfo,
2072 slba, apptag, appmask, &reftag);
2073 if (status) {
2074 req->status = status;
2075 goto out;
2079 * When formatted with protection information, do not compare the DIF
2080 * tuple.
2082 if (!(ns->id_ns.dps & NVME_ID_NS_DPS_FIRST_EIGHT)) {
2083 pil = ns->lbaf.ms - sizeof(NvmeDifTuple);
2086 for (bufp = buf; mbufp < end; bufp += ns->lbaf.ms, mbufp += ns->lbaf.ms) {
2087 if (memcmp(bufp + pil, mbufp + pil, ns->lbaf.ms - pil)) {
2088 req->status = NVME_CMP_FAILURE;
2089 goto out;
2093 goto out;
2096 if (memcmp(buf, ctx->mdata.bounce, ctx->mdata.iov.size)) {
2097 req->status = NVME_CMP_FAILURE;
2098 goto out;
2101 block_acct_done(stats, acct);
2103 out:
2104 qemu_iovec_destroy(&ctx->data.iov);
2105 g_free(ctx->data.bounce);
2107 qemu_iovec_destroy(&ctx->mdata.iov);
2108 g_free(ctx->mdata.bounce);
2110 g_free(ctx);
2112 nvme_enqueue_req_completion(nvme_cq(req), req);
2115 static void nvme_compare_data_cb(void *opaque, int ret)
2117 NvmeRequest *req = opaque;
2118 NvmeCtrl *n = nvme_ctrl(req);
2119 NvmeNamespace *ns = req->ns;
2120 BlockBackend *blk = ns->blkconf.blk;
2121 BlockAcctCookie *acct = &req->acct;
2122 BlockAcctStats *stats = blk_get_stats(blk);
2124 struct nvme_compare_ctx *ctx = req->opaque;
2125 g_autofree uint8_t *buf = NULL;
2126 uint16_t status;
2128 trace_pci_nvme_compare_data_cb(nvme_cid(req));
2130 if (ret) {
2131 block_acct_failed(stats, acct);
2132 nvme_aio_err(req, ret);
2133 goto out;
2136 buf = g_malloc(ctx->data.iov.size);
2138 status = nvme_bounce_data(n, buf, ctx->data.iov.size,
2139 NVME_TX_DIRECTION_TO_DEVICE, req);
2140 if (status) {
2141 req->status = status;
2142 goto out;
2145 if (memcmp(buf, ctx->data.bounce, ctx->data.iov.size)) {
2146 req->status = NVME_CMP_FAILURE;
2147 goto out;
2150 if (ns->lbaf.ms) {
2151 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2152 uint64_t slba = le64_to_cpu(rw->slba);
2153 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2154 size_t mlen = nvme_m2b(ns, nlb);
2155 uint64_t offset = nvme_moff(ns, slba);
2157 ctx->mdata.bounce = g_malloc(mlen);
2159 qemu_iovec_init(&ctx->mdata.iov, 1);
2160 qemu_iovec_add(&ctx->mdata.iov, ctx->mdata.bounce, mlen);
2162 req->aiocb = blk_aio_preadv(blk, offset, &ctx->mdata.iov, 0,
2163 nvme_compare_mdata_cb, req);
2164 return;
2167 block_acct_done(stats, acct);
2169 out:
2170 qemu_iovec_destroy(&ctx->data.iov);
2171 g_free(ctx->data.bounce);
2172 g_free(ctx);
2174 nvme_enqueue_req_completion(nvme_cq(req), req);
2177 typedef struct NvmeDSMAIOCB {
2178 BlockAIOCB common;
2179 BlockAIOCB *aiocb;
2180 NvmeRequest *req;
2181 QEMUBH *bh;
2182 int ret;
2184 NvmeDsmRange *range;
2185 unsigned int nr;
2186 unsigned int idx;
2187 } NvmeDSMAIOCB;
2189 static void nvme_dsm_cancel(BlockAIOCB *aiocb)
2191 NvmeDSMAIOCB *iocb = container_of(aiocb, NvmeDSMAIOCB, common);
2193 /* break nvme_dsm_cb loop */
2194 iocb->idx = iocb->nr;
2195 iocb->ret = -ECANCELED;
2197 if (iocb->aiocb) {
2198 blk_aio_cancel_async(iocb->aiocb);
2199 iocb->aiocb = NULL;
2200 } else {
2202 * We only reach this if nvme_dsm_cancel() has already been called or
2203 * the command ran to completion and nvme_dsm_bh is scheduled to run.
2205 assert(iocb->idx == iocb->nr);
2209 static const AIOCBInfo nvme_dsm_aiocb_info = {
2210 .aiocb_size = sizeof(NvmeDSMAIOCB),
2211 .cancel_async = nvme_dsm_cancel,
2214 static void nvme_dsm_bh(void *opaque)
2216 NvmeDSMAIOCB *iocb = opaque;
2218 iocb->common.cb(iocb->common.opaque, iocb->ret);
2220 qemu_bh_delete(iocb->bh);
2221 iocb->bh = NULL;
2222 qemu_aio_unref(iocb);
2225 static void nvme_dsm_cb(void *opaque, int ret);
2227 static void nvme_dsm_md_cb(void *opaque, int ret)
2229 NvmeDSMAIOCB *iocb = opaque;
2230 NvmeRequest *req = iocb->req;
2231 NvmeNamespace *ns = req->ns;
2232 NvmeDsmRange *range;
2233 uint64_t slba;
2234 uint32_t nlb;
2236 if (ret < 0) {
2237 iocb->ret = ret;
2238 goto done;
2241 if (!ns->lbaf.ms) {
2242 nvme_dsm_cb(iocb, 0);
2243 return;
2246 range = &iocb->range[iocb->idx - 1];
2247 slba = le64_to_cpu(range->slba);
2248 nlb = le32_to_cpu(range->nlb);
2251 * Check that all block were discarded (zeroed); otherwise we do not zero
2252 * the metadata.
2255 ret = nvme_block_status_all(ns, slba, nlb, BDRV_BLOCK_ZERO);
2256 if (ret) {
2257 if (ret < 0) {
2258 iocb->ret = ret;
2259 goto done;
2262 nvme_dsm_cb(iocb, 0);
2265 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, nvme_moff(ns, slba),
2266 nvme_m2b(ns, nlb), BDRV_REQ_MAY_UNMAP,
2267 nvme_dsm_cb, iocb);
2268 return;
2270 done:
2271 iocb->aiocb = NULL;
2272 qemu_bh_schedule(iocb->bh);
2275 static void nvme_dsm_cb(void *opaque, int ret)
2277 NvmeDSMAIOCB *iocb = opaque;
2278 NvmeRequest *req = iocb->req;
2279 NvmeCtrl *n = nvme_ctrl(req);
2280 NvmeNamespace *ns = req->ns;
2281 NvmeDsmRange *range;
2282 uint64_t slba;
2283 uint32_t nlb;
2285 if (ret < 0) {
2286 iocb->ret = ret;
2287 goto done;
2290 next:
2291 if (iocb->idx == iocb->nr) {
2292 goto done;
2295 range = &iocb->range[iocb->idx++];
2296 slba = le64_to_cpu(range->slba);
2297 nlb = le32_to_cpu(range->nlb);
2299 trace_pci_nvme_dsm_deallocate(slba, nlb);
2301 if (nlb > n->dmrsl) {
2302 trace_pci_nvme_dsm_single_range_limit_exceeded(nlb, n->dmrsl);
2303 goto next;
2306 if (nvme_check_bounds(ns, slba, nlb)) {
2307 trace_pci_nvme_err_invalid_lba_range(slba, nlb,
2308 ns->id_ns.nsze);
2309 goto next;
2312 iocb->aiocb = blk_aio_pdiscard(ns->blkconf.blk, nvme_l2b(ns, slba),
2313 nvme_l2b(ns, nlb),
2314 nvme_dsm_md_cb, iocb);
2315 return;
2317 done:
2318 iocb->aiocb = NULL;
2319 qemu_bh_schedule(iocb->bh);
2322 static uint16_t nvme_dsm(NvmeCtrl *n, NvmeRequest *req)
2324 NvmeNamespace *ns = req->ns;
2325 NvmeDsmCmd *dsm = (NvmeDsmCmd *) &req->cmd;
2326 uint32_t attr = le32_to_cpu(dsm->attributes);
2327 uint32_t nr = (le32_to_cpu(dsm->nr) & 0xff) + 1;
2328 uint16_t status = NVME_SUCCESS;
2330 trace_pci_nvme_dsm(nr, attr);
2332 if (attr & NVME_DSMGMT_AD) {
2333 NvmeDSMAIOCB *iocb = blk_aio_get(&nvme_dsm_aiocb_info, ns->blkconf.blk,
2334 nvme_misc_cb, req);
2336 iocb->req = req;
2337 iocb->bh = qemu_bh_new(nvme_dsm_bh, iocb);
2338 iocb->ret = 0;
2339 iocb->range = g_new(NvmeDsmRange, nr);
2340 iocb->nr = nr;
2341 iocb->idx = 0;
2343 status = nvme_h2c(n, (uint8_t *)iocb->range, sizeof(NvmeDsmRange) * nr,
2344 req);
2345 if (status) {
2346 return status;
2349 req->aiocb = &iocb->common;
2350 nvme_dsm_cb(iocb, 0);
2352 return NVME_NO_COMPLETE;
2355 return status;
2358 static uint16_t nvme_verify(NvmeCtrl *n, NvmeRequest *req)
2360 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2361 NvmeNamespace *ns = req->ns;
2362 BlockBackend *blk = ns->blkconf.blk;
2363 uint64_t slba = le64_to_cpu(rw->slba);
2364 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2365 size_t len = nvme_l2b(ns, nlb);
2366 int64_t offset = nvme_l2b(ns, slba);
2367 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2368 uint32_t reftag = le32_to_cpu(rw->reftag);
2369 NvmeBounceContext *ctx = NULL;
2370 uint16_t status;
2372 trace_pci_nvme_verify(nvme_cid(req), nvme_nsid(ns), slba, nlb);
2374 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2375 status = nvme_check_prinfo(ns, prinfo, slba, reftag);
2376 if (status) {
2377 return status;
2380 if (prinfo & NVME_PRINFO_PRACT) {
2381 return NVME_INVALID_PROT_INFO | NVME_DNR;
2385 if (len > n->page_size << n->params.vsl) {
2386 return NVME_INVALID_FIELD | NVME_DNR;
2389 status = nvme_check_bounds(ns, slba, nlb);
2390 if (status) {
2391 return status;
2394 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
2395 status = nvme_check_dulbe(ns, slba, nlb);
2396 if (status) {
2397 return status;
2401 ctx = g_new0(NvmeBounceContext, 1);
2402 ctx->req = req;
2404 ctx->data.bounce = g_malloc(len);
2406 qemu_iovec_init(&ctx->data.iov, 1);
2407 qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, len);
2409 block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
2410 BLOCK_ACCT_READ);
2412 req->aiocb = blk_aio_preadv(ns->blkconf.blk, offset, &ctx->data.iov, 0,
2413 nvme_verify_mdata_in_cb, ctx);
2414 return NVME_NO_COMPLETE;
2417 typedef struct NvmeCopyAIOCB {
2418 BlockAIOCB common;
2419 BlockAIOCB *aiocb;
2420 NvmeRequest *req;
2421 QEMUBH *bh;
2422 int ret;
2424 NvmeCopySourceRange *ranges;
2425 int nr;
2426 int idx;
2428 uint8_t *bounce;
2429 QEMUIOVector iov;
2430 struct {
2431 BlockAcctCookie read;
2432 BlockAcctCookie write;
2433 } acct;
2435 uint32_t reftag;
2436 uint64_t slba;
2438 NvmeZone *zone;
2439 } NvmeCopyAIOCB;
2441 static void nvme_copy_cancel(BlockAIOCB *aiocb)
2443 NvmeCopyAIOCB *iocb = container_of(aiocb, NvmeCopyAIOCB, common);
2445 iocb->ret = -ECANCELED;
2447 if (iocb->aiocb) {
2448 blk_aio_cancel_async(iocb->aiocb);
2449 iocb->aiocb = NULL;
2453 static const AIOCBInfo nvme_copy_aiocb_info = {
2454 .aiocb_size = sizeof(NvmeCopyAIOCB),
2455 .cancel_async = nvme_copy_cancel,
2458 static void nvme_copy_bh(void *opaque)
2460 NvmeCopyAIOCB *iocb = opaque;
2461 NvmeRequest *req = iocb->req;
2462 NvmeNamespace *ns = req->ns;
2463 BlockAcctStats *stats = blk_get_stats(ns->blkconf.blk);
2465 if (iocb->idx != iocb->nr) {
2466 req->cqe.result = cpu_to_le32(iocb->idx);
2469 qemu_iovec_destroy(&iocb->iov);
2470 g_free(iocb->bounce);
2472 qemu_bh_delete(iocb->bh);
2473 iocb->bh = NULL;
2475 if (iocb->ret < 0) {
2476 block_acct_failed(stats, &iocb->acct.read);
2477 block_acct_failed(stats, &iocb->acct.write);
2478 } else {
2479 block_acct_done(stats, &iocb->acct.read);
2480 block_acct_done(stats, &iocb->acct.write);
2483 iocb->common.cb(iocb->common.opaque, iocb->ret);
2484 qemu_aio_unref(iocb);
2487 static void nvme_copy_cb(void *opaque, int ret);
2489 static void nvme_copy_out_completed_cb(void *opaque, int ret)
2491 NvmeCopyAIOCB *iocb = opaque;
2492 NvmeRequest *req = iocb->req;
2493 NvmeNamespace *ns = req->ns;
2494 NvmeCopySourceRange *range = &iocb->ranges[iocb->idx];
2495 uint32_t nlb = le32_to_cpu(range->nlb) + 1;
2497 if (ret < 0) {
2498 iocb->ret = ret;
2499 goto out;
2500 } else if (iocb->ret < 0) {
2501 goto out;
2504 if (ns->params.zoned) {
2505 nvme_advance_zone_wp(ns, iocb->zone, nlb);
2508 iocb->idx++;
2509 iocb->slba += nlb;
2510 out:
2511 nvme_copy_cb(iocb, iocb->ret);
2514 static void nvme_copy_out_cb(void *opaque, int ret)
2516 NvmeCopyAIOCB *iocb = opaque;
2517 NvmeRequest *req = iocb->req;
2518 NvmeNamespace *ns = req->ns;
2519 NvmeCopySourceRange *range;
2520 uint32_t nlb;
2521 size_t mlen;
2522 uint8_t *mbounce;
2524 if (ret < 0) {
2525 iocb->ret = ret;
2526 goto out;
2527 } else if (iocb->ret < 0) {
2528 goto out;
2531 if (!ns->lbaf.ms) {
2532 nvme_copy_out_completed_cb(iocb, 0);
2533 return;
2536 range = &iocb->ranges[iocb->idx];
2537 nlb = le32_to_cpu(range->nlb) + 1;
2539 mlen = nvme_m2b(ns, nlb);
2540 mbounce = iocb->bounce + nvme_l2b(ns, nlb);
2542 qemu_iovec_reset(&iocb->iov);
2543 qemu_iovec_add(&iocb->iov, mbounce, mlen);
2545 iocb->aiocb = blk_aio_pwritev(ns->blkconf.blk, nvme_moff(ns, iocb->slba),
2546 &iocb->iov, 0, nvme_copy_out_completed_cb,
2547 iocb);
2549 return;
2551 out:
2552 nvme_copy_cb(iocb, ret);
2555 static void nvme_copy_in_completed_cb(void *opaque, int ret)
2557 NvmeCopyAIOCB *iocb = opaque;
2558 NvmeRequest *req = iocb->req;
2559 NvmeNamespace *ns = req->ns;
2560 NvmeCopySourceRange *range;
2561 uint32_t nlb;
2562 size_t len;
2563 uint16_t status;
2565 if (ret < 0) {
2566 iocb->ret = ret;
2567 goto out;
2568 } else if (iocb->ret < 0) {
2569 goto out;
2572 range = &iocb->ranges[iocb->idx];
2573 nlb = le32_to_cpu(range->nlb) + 1;
2574 len = nvme_l2b(ns, nlb);
2576 trace_pci_nvme_copy_out(iocb->slba, nlb);
2578 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2579 NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
2581 uint16_t prinfor = ((copy->control[0] >> 4) & 0xf);
2582 uint16_t prinfow = ((copy->control[2] >> 2) & 0xf);
2584 uint16_t apptag = le16_to_cpu(range->apptag);
2585 uint16_t appmask = le16_to_cpu(range->appmask);
2586 uint32_t reftag = le32_to_cpu(range->reftag);
2588 uint64_t slba = le64_to_cpu(range->slba);
2589 size_t mlen = nvme_m2b(ns, nlb);
2590 uint8_t *mbounce = iocb->bounce + nvme_l2b(ns, nlb);
2592 status = nvme_dif_check(ns, iocb->bounce, len, mbounce, mlen, prinfor,
2593 slba, apptag, appmask, &reftag);
2594 if (status) {
2595 goto invalid;
2598 apptag = le16_to_cpu(copy->apptag);
2599 appmask = le16_to_cpu(copy->appmask);
2601 if (prinfow & NVME_PRINFO_PRACT) {
2602 status = nvme_check_prinfo(ns, prinfow, iocb->slba, iocb->reftag);
2603 if (status) {
2604 goto invalid;
2607 nvme_dif_pract_generate_dif(ns, iocb->bounce, len, mbounce, mlen,
2608 apptag, &iocb->reftag);
2609 } else {
2610 status = nvme_dif_check(ns, iocb->bounce, len, mbounce, mlen,
2611 prinfow, iocb->slba, apptag, appmask,
2612 &iocb->reftag);
2613 if (status) {
2614 goto invalid;
2619 status = nvme_check_bounds(ns, iocb->slba, nlb);
2620 if (status) {
2621 goto invalid;
2624 if (ns->params.zoned) {
2625 status = nvme_check_zone_write(ns, iocb->zone, iocb->slba, nlb);
2626 if (status) {
2627 goto invalid;
2630 iocb->zone->w_ptr += nlb;
2633 qemu_iovec_reset(&iocb->iov);
2634 qemu_iovec_add(&iocb->iov, iocb->bounce, len);
2636 iocb->aiocb = blk_aio_pwritev(ns->blkconf.blk, nvme_l2b(ns, iocb->slba),
2637 &iocb->iov, 0, nvme_copy_out_cb, iocb);
2639 return;
2641 invalid:
2642 req->status = status;
2643 iocb->aiocb = NULL;
2644 if (iocb->bh) {
2645 qemu_bh_schedule(iocb->bh);
2648 return;
2650 out:
2651 nvme_copy_cb(iocb, ret);
2654 static void nvme_copy_in_cb(void *opaque, int ret)
2656 NvmeCopyAIOCB *iocb = opaque;
2657 NvmeRequest *req = iocb->req;
2658 NvmeNamespace *ns = req->ns;
2659 NvmeCopySourceRange *range;
2660 uint64_t slba;
2661 uint32_t nlb;
2663 if (ret < 0) {
2664 iocb->ret = ret;
2665 goto out;
2666 } else if (iocb->ret < 0) {
2667 goto out;
2670 if (!ns->lbaf.ms) {
2671 nvme_copy_in_completed_cb(iocb, 0);
2672 return;
2675 range = &iocb->ranges[iocb->idx];
2676 slba = le64_to_cpu(range->slba);
2677 nlb = le32_to_cpu(range->nlb) + 1;
2679 qemu_iovec_reset(&iocb->iov);
2680 qemu_iovec_add(&iocb->iov, iocb->bounce + nvme_l2b(ns, nlb),
2681 nvme_m2b(ns, nlb));
2683 iocb->aiocb = blk_aio_preadv(ns->blkconf.blk, nvme_moff(ns, slba),
2684 &iocb->iov, 0, nvme_copy_in_completed_cb,
2685 iocb);
2686 return;
2688 out:
2689 nvme_copy_cb(iocb, iocb->ret);
2692 static void nvme_copy_cb(void *opaque, int ret)
2694 NvmeCopyAIOCB *iocb = opaque;
2695 NvmeRequest *req = iocb->req;
2696 NvmeNamespace *ns = req->ns;
2697 NvmeCopySourceRange *range;
2698 uint64_t slba;
2699 uint32_t nlb;
2700 size_t len;
2701 uint16_t status;
2703 if (ret < 0) {
2704 iocb->ret = ret;
2705 goto done;
2706 } else if (iocb->ret < 0) {
2707 goto done;
2710 if (iocb->idx == iocb->nr) {
2711 goto done;
2714 range = &iocb->ranges[iocb->idx];
2715 slba = le64_to_cpu(range->slba);
2716 nlb = le32_to_cpu(range->nlb) + 1;
2717 len = nvme_l2b(ns, nlb);
2719 trace_pci_nvme_copy_source_range(slba, nlb);
2721 if (nlb > le16_to_cpu(ns->id_ns.mssrl)) {
2722 status = NVME_CMD_SIZE_LIMIT | NVME_DNR;
2723 goto invalid;
2726 status = nvme_check_bounds(ns, slba, nlb);
2727 if (status) {
2728 goto invalid;
2731 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
2732 status = nvme_check_dulbe(ns, slba, nlb);
2733 if (status) {
2734 goto invalid;
2738 if (ns->params.zoned) {
2739 status = nvme_check_zone_read(ns, slba, nlb);
2740 if (status) {
2741 goto invalid;
2745 qemu_iovec_reset(&iocb->iov);
2746 qemu_iovec_add(&iocb->iov, iocb->bounce, len);
2748 iocb->aiocb = blk_aio_preadv(ns->blkconf.blk, nvme_l2b(ns, slba),
2749 &iocb->iov, 0, nvme_copy_in_cb, iocb);
2750 return;
2752 invalid:
2753 req->status = status;
2754 done:
2755 iocb->aiocb = NULL;
2756 if (iocb->bh) {
2757 qemu_bh_schedule(iocb->bh);
2762 static uint16_t nvme_copy(NvmeCtrl *n, NvmeRequest *req)
2764 NvmeNamespace *ns = req->ns;
2765 NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
2766 NvmeCopyAIOCB *iocb = blk_aio_get(&nvme_copy_aiocb_info, ns->blkconf.blk,
2767 nvme_misc_cb, req);
2768 uint16_t nr = copy->nr + 1;
2769 uint8_t format = copy->control[0] & 0xf;
2770 uint16_t prinfor = ((copy->control[0] >> 4) & 0xf);
2771 uint16_t prinfow = ((copy->control[2] >> 2) & 0xf);
2773 uint16_t status;
2775 trace_pci_nvme_copy(nvme_cid(req), nvme_nsid(ns), nr, format);
2777 iocb->ranges = NULL;
2778 iocb->zone = NULL;
2780 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps) &&
2781 ((prinfor & NVME_PRINFO_PRACT) != (prinfow & NVME_PRINFO_PRACT))) {
2782 status = NVME_INVALID_FIELD | NVME_DNR;
2783 goto invalid;
2786 if (!(n->id_ctrl.ocfs & (1 << format))) {
2787 trace_pci_nvme_err_copy_invalid_format(format);
2788 status = NVME_INVALID_FIELD | NVME_DNR;
2789 goto invalid;
2792 if (nr > ns->id_ns.msrc + 1) {
2793 status = NVME_CMD_SIZE_LIMIT | NVME_DNR;
2794 goto invalid;
2797 iocb->ranges = g_new(NvmeCopySourceRange, nr);
2799 status = nvme_h2c(n, (uint8_t *)iocb->ranges,
2800 sizeof(NvmeCopySourceRange) * nr, req);
2801 if (status) {
2802 goto invalid;
2805 iocb->slba = le64_to_cpu(copy->sdlba);
2807 if (ns->params.zoned) {
2808 iocb->zone = nvme_get_zone_by_slba(ns, iocb->slba);
2809 if (!iocb->zone) {
2810 status = NVME_LBA_RANGE | NVME_DNR;
2811 goto invalid;
2814 status = nvme_zrm_auto(n, ns, iocb->zone);
2815 if (status) {
2816 goto invalid;
2820 iocb->req = req;
2821 iocb->bh = qemu_bh_new(nvme_copy_bh, iocb);
2822 iocb->ret = 0;
2823 iocb->nr = nr;
2824 iocb->idx = 0;
2825 iocb->reftag = le32_to_cpu(copy->reftag);
2826 iocb->bounce = g_malloc_n(le16_to_cpu(ns->id_ns.mssrl),
2827 ns->lbasz + ns->lbaf.ms);
2829 qemu_iovec_init(&iocb->iov, 1);
2831 block_acct_start(blk_get_stats(ns->blkconf.blk), &iocb->acct.read, 0,
2832 BLOCK_ACCT_READ);
2833 block_acct_start(blk_get_stats(ns->blkconf.blk), &iocb->acct.write, 0,
2834 BLOCK_ACCT_WRITE);
2836 req->aiocb = &iocb->common;
2837 nvme_copy_cb(iocb, 0);
2839 return NVME_NO_COMPLETE;
2841 invalid:
2842 g_free(iocb->ranges);
2843 qemu_aio_unref(iocb);
2844 return status;
2847 static uint16_t nvme_compare(NvmeCtrl *n, NvmeRequest *req)
2849 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2850 NvmeNamespace *ns = req->ns;
2851 BlockBackend *blk = ns->blkconf.blk;
2852 uint64_t slba = le64_to_cpu(rw->slba);
2853 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2854 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2855 size_t data_len = nvme_l2b(ns, nlb);
2856 size_t len = data_len;
2857 int64_t offset = nvme_l2b(ns, slba);
2858 struct nvme_compare_ctx *ctx = NULL;
2859 uint16_t status;
2861 trace_pci_nvme_compare(nvme_cid(req), nvme_nsid(ns), slba, nlb);
2863 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps) && (prinfo & NVME_PRINFO_PRACT)) {
2864 return NVME_INVALID_PROT_INFO | NVME_DNR;
2867 if (nvme_ns_ext(ns)) {
2868 len += nvme_m2b(ns, nlb);
2871 status = nvme_check_mdts(n, len);
2872 if (status) {
2873 return status;
2876 status = nvme_check_bounds(ns, slba, nlb);
2877 if (status) {
2878 return status;
2881 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
2882 status = nvme_check_dulbe(ns, slba, nlb);
2883 if (status) {
2884 return status;
2888 status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
2889 if (status) {
2890 return status;
2893 ctx = g_new(struct nvme_compare_ctx, 1);
2894 ctx->data.bounce = g_malloc(data_len);
2896 req->opaque = ctx;
2898 qemu_iovec_init(&ctx->data.iov, 1);
2899 qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, data_len);
2901 block_acct_start(blk_get_stats(blk), &req->acct, data_len,
2902 BLOCK_ACCT_READ);
2903 req->aiocb = blk_aio_preadv(blk, offset, &ctx->data.iov, 0,
2904 nvme_compare_data_cb, req);
2906 return NVME_NO_COMPLETE;
2909 typedef struct NvmeFlushAIOCB {
2910 BlockAIOCB common;
2911 BlockAIOCB *aiocb;
2912 NvmeRequest *req;
2913 QEMUBH *bh;
2914 int ret;
2916 NvmeNamespace *ns;
2917 uint32_t nsid;
2918 bool broadcast;
2919 } NvmeFlushAIOCB;
2921 static void nvme_flush_cancel(BlockAIOCB *acb)
2923 NvmeFlushAIOCB *iocb = container_of(acb, NvmeFlushAIOCB, common);
2925 iocb->ret = -ECANCELED;
2927 if (iocb->aiocb) {
2928 blk_aio_cancel_async(iocb->aiocb);
2932 static const AIOCBInfo nvme_flush_aiocb_info = {
2933 .aiocb_size = sizeof(NvmeFlushAIOCB),
2934 .cancel_async = nvme_flush_cancel,
2935 .get_aio_context = nvme_get_aio_context,
2938 static void nvme_flush_ns_cb(void *opaque, int ret)
2940 NvmeFlushAIOCB *iocb = opaque;
2941 NvmeNamespace *ns = iocb->ns;
2943 if (ret < 0) {
2944 iocb->ret = ret;
2945 goto out;
2946 } else if (iocb->ret < 0) {
2947 goto out;
2950 if (ns) {
2951 trace_pci_nvme_flush_ns(iocb->nsid);
2953 iocb->ns = NULL;
2954 iocb->aiocb = blk_aio_flush(ns->blkconf.blk, nvme_flush_ns_cb, iocb);
2955 return;
2958 out:
2959 iocb->aiocb = NULL;
2960 qemu_bh_schedule(iocb->bh);
2963 static void nvme_flush_bh(void *opaque)
2965 NvmeFlushAIOCB *iocb = opaque;
2966 NvmeRequest *req = iocb->req;
2967 NvmeCtrl *n = nvme_ctrl(req);
2968 int i;
2970 if (iocb->ret < 0) {
2971 goto done;
2974 if (iocb->broadcast) {
2975 for (i = iocb->nsid + 1; i <= NVME_MAX_NAMESPACES; i++) {
2976 iocb->ns = nvme_ns(n, i);
2977 if (iocb->ns) {
2978 iocb->nsid = i;
2979 break;
2984 if (!iocb->ns) {
2985 goto done;
2988 nvme_flush_ns_cb(iocb, 0);
2989 return;
2991 done:
2992 qemu_bh_delete(iocb->bh);
2993 iocb->bh = NULL;
2995 iocb->common.cb(iocb->common.opaque, iocb->ret);
2997 qemu_aio_unref(iocb);
2999 return;
3002 static uint16_t nvme_flush(NvmeCtrl *n, NvmeRequest *req)
3004 NvmeFlushAIOCB *iocb;
3005 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
3006 uint16_t status;
3008 iocb = qemu_aio_get(&nvme_flush_aiocb_info, NULL, nvme_misc_cb, req);
3010 iocb->req = req;
3011 iocb->bh = qemu_bh_new(nvme_flush_bh, iocb);
3012 iocb->ret = 0;
3013 iocb->ns = NULL;
3014 iocb->nsid = 0;
3015 iocb->broadcast = (nsid == NVME_NSID_BROADCAST);
3017 if (!iocb->broadcast) {
3018 if (!nvme_nsid_valid(n, nsid)) {
3019 status = NVME_INVALID_NSID | NVME_DNR;
3020 goto out;
3023 iocb->ns = nvme_ns(n, nsid);
3024 if (!iocb->ns) {
3025 status = NVME_INVALID_FIELD | NVME_DNR;
3026 goto out;
3029 iocb->nsid = nsid;
3032 req->aiocb = &iocb->common;
3033 qemu_bh_schedule(iocb->bh);
3035 return NVME_NO_COMPLETE;
3037 out:
3038 qemu_bh_delete(iocb->bh);
3039 iocb->bh = NULL;
3040 qemu_aio_unref(iocb);
3042 return status;
3045 static uint16_t nvme_read(NvmeCtrl *n, NvmeRequest *req)
3047 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3048 NvmeNamespace *ns = req->ns;
3049 uint64_t slba = le64_to_cpu(rw->slba);
3050 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
3051 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
3052 uint64_t data_size = nvme_l2b(ns, nlb);
3053 uint64_t mapped_size = data_size;
3054 uint64_t data_offset;
3055 BlockBackend *blk = ns->blkconf.blk;
3056 uint16_t status;
3058 if (nvme_ns_ext(ns)) {
3059 mapped_size += nvme_m2b(ns, nlb);
3061 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3062 bool pract = prinfo & NVME_PRINFO_PRACT;
3064 if (pract && ns->lbaf.ms == 8) {
3065 mapped_size = data_size;
3070 trace_pci_nvme_read(nvme_cid(req), nvme_nsid(ns), nlb, mapped_size, slba);
3072 status = nvme_check_mdts(n, mapped_size);
3073 if (status) {
3074 goto invalid;
3077 status = nvme_check_bounds(ns, slba, nlb);
3078 if (status) {
3079 goto invalid;
3082 if (ns->params.zoned) {
3083 status = nvme_check_zone_read(ns, slba, nlb);
3084 if (status) {
3085 trace_pci_nvme_err_zone_read_not_ok(slba, nlb, status);
3086 goto invalid;
3090 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
3091 status = nvme_check_dulbe(ns, slba, nlb);
3092 if (status) {
3093 goto invalid;
3097 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3098 return nvme_dif_rw(n, req);
3101 status = nvme_map_data(n, nlb, req);
3102 if (status) {
3103 goto invalid;
3106 data_offset = nvme_l2b(ns, slba);
3108 block_acct_start(blk_get_stats(blk), &req->acct, data_size,
3109 BLOCK_ACCT_READ);
3110 nvme_blk_read(blk, data_offset, nvme_rw_cb, req);
3111 return NVME_NO_COMPLETE;
3113 invalid:
3114 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
3115 return status | NVME_DNR;
3118 static uint16_t nvme_do_write(NvmeCtrl *n, NvmeRequest *req, bool append,
3119 bool wrz)
3121 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3122 NvmeNamespace *ns = req->ns;
3123 uint64_t slba = le64_to_cpu(rw->slba);
3124 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
3125 uint16_t ctrl = le16_to_cpu(rw->control);
3126 uint8_t prinfo = NVME_RW_PRINFO(ctrl);
3127 uint64_t data_size = nvme_l2b(ns, nlb);
3128 uint64_t mapped_size = data_size;
3129 uint64_t data_offset;
3130 NvmeZone *zone;
3131 NvmeZonedResult *res = (NvmeZonedResult *)&req->cqe;
3132 BlockBackend *blk = ns->blkconf.blk;
3133 uint16_t status;
3135 if (nvme_ns_ext(ns)) {
3136 mapped_size += nvme_m2b(ns, nlb);
3138 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3139 bool pract = prinfo & NVME_PRINFO_PRACT;
3141 if (pract && ns->lbaf.ms == 8) {
3142 mapped_size -= nvme_m2b(ns, nlb);
3147 trace_pci_nvme_write(nvme_cid(req), nvme_io_opc_str(rw->opcode),
3148 nvme_nsid(ns), nlb, mapped_size, slba);
3150 if (!wrz) {
3151 status = nvme_check_mdts(n, mapped_size);
3152 if (status) {
3153 goto invalid;
3157 status = nvme_check_bounds(ns, slba, nlb);
3158 if (status) {
3159 goto invalid;
3162 if (ns->params.zoned) {
3163 zone = nvme_get_zone_by_slba(ns, slba);
3164 assert(zone);
3166 if (append) {
3167 bool piremap = !!(ctrl & NVME_RW_PIREMAP);
3169 if (unlikely(slba != zone->d.zslba)) {
3170 trace_pci_nvme_err_append_not_at_start(slba, zone->d.zslba);
3171 status = NVME_INVALID_FIELD;
3172 goto invalid;
3175 if (n->params.zasl &&
3176 data_size > (uint64_t)n->page_size << n->params.zasl) {
3177 trace_pci_nvme_err_zasl(data_size);
3178 return NVME_INVALID_FIELD | NVME_DNR;
3181 slba = zone->w_ptr;
3182 rw->slba = cpu_to_le64(slba);
3183 res->slba = cpu_to_le64(slba);
3185 switch (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3186 case NVME_ID_NS_DPS_TYPE_1:
3187 if (!piremap) {
3188 return NVME_INVALID_PROT_INFO | NVME_DNR;
3191 /* fallthrough */
3193 case NVME_ID_NS_DPS_TYPE_2:
3194 if (piremap) {
3195 uint32_t reftag = le32_to_cpu(rw->reftag);
3196 rw->reftag = cpu_to_le32(reftag + (slba - zone->d.zslba));
3199 break;
3201 case NVME_ID_NS_DPS_TYPE_3:
3202 if (piremap) {
3203 return NVME_INVALID_PROT_INFO | NVME_DNR;
3206 break;
3210 status = nvme_check_zone_write(ns, zone, slba, nlb);
3211 if (status) {
3212 goto invalid;
3215 status = nvme_zrm_auto(n, ns, zone);
3216 if (status) {
3217 goto invalid;
3220 zone->w_ptr += nlb;
3223 data_offset = nvme_l2b(ns, slba);
3225 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3226 return nvme_dif_rw(n, req);
3229 if (!wrz) {
3230 status = nvme_map_data(n, nlb, req);
3231 if (status) {
3232 goto invalid;
3235 block_acct_start(blk_get_stats(blk), &req->acct, data_size,
3236 BLOCK_ACCT_WRITE);
3237 nvme_blk_write(blk, data_offset, nvme_rw_cb, req);
3238 } else {
3239 req->aiocb = blk_aio_pwrite_zeroes(blk, data_offset, data_size,
3240 BDRV_REQ_MAY_UNMAP, nvme_rw_cb,
3241 req);
3244 return NVME_NO_COMPLETE;
3246 invalid:
3247 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
3248 return status | NVME_DNR;
3251 static inline uint16_t nvme_write(NvmeCtrl *n, NvmeRequest *req)
3253 return nvme_do_write(n, req, false, false);
3256 static inline uint16_t nvme_write_zeroes(NvmeCtrl *n, NvmeRequest *req)
3258 return nvme_do_write(n, req, false, true);
3261 static inline uint16_t nvme_zone_append(NvmeCtrl *n, NvmeRequest *req)
3263 return nvme_do_write(n, req, true, false);
3266 static uint16_t nvme_get_mgmt_zone_slba_idx(NvmeNamespace *ns, NvmeCmd *c,
3267 uint64_t *slba, uint32_t *zone_idx)
3269 uint32_t dw10 = le32_to_cpu(c->cdw10);
3270 uint32_t dw11 = le32_to_cpu(c->cdw11);
3272 if (!ns->params.zoned) {
3273 trace_pci_nvme_err_invalid_opc(c->opcode);
3274 return NVME_INVALID_OPCODE | NVME_DNR;
3277 *slba = ((uint64_t)dw11) << 32 | dw10;
3278 if (unlikely(*slba >= ns->id_ns.nsze)) {
3279 trace_pci_nvme_err_invalid_lba_range(*slba, 0, ns->id_ns.nsze);
3280 *slba = 0;
3281 return NVME_LBA_RANGE | NVME_DNR;
3284 *zone_idx = nvme_zone_idx(ns, *slba);
3285 assert(*zone_idx < ns->num_zones);
3287 return NVME_SUCCESS;
3290 typedef uint16_t (*op_handler_t)(NvmeNamespace *, NvmeZone *, NvmeZoneState,
3291 NvmeRequest *);
3293 enum NvmeZoneProcessingMask {
3294 NVME_PROC_CURRENT_ZONE = 0,
3295 NVME_PROC_OPENED_ZONES = 1 << 0,
3296 NVME_PROC_CLOSED_ZONES = 1 << 1,
3297 NVME_PROC_READ_ONLY_ZONES = 1 << 2,
3298 NVME_PROC_FULL_ZONES = 1 << 3,
3301 static uint16_t nvme_open_zone(NvmeNamespace *ns, NvmeZone *zone,
3302 NvmeZoneState state, NvmeRequest *req)
3304 return nvme_zrm_open(nvme_ctrl(req), ns, zone);
3307 static uint16_t nvme_close_zone(NvmeNamespace *ns, NvmeZone *zone,
3308 NvmeZoneState state, NvmeRequest *req)
3310 return nvme_zrm_close(ns, zone);
3313 static uint16_t nvme_finish_zone(NvmeNamespace *ns, NvmeZone *zone,
3314 NvmeZoneState state, NvmeRequest *req)
3316 return nvme_zrm_finish(ns, zone);
3319 static uint16_t nvme_offline_zone(NvmeNamespace *ns, NvmeZone *zone,
3320 NvmeZoneState state, NvmeRequest *req)
3322 switch (state) {
3323 case NVME_ZONE_STATE_READ_ONLY:
3324 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_OFFLINE);
3325 /* fall through */
3326 case NVME_ZONE_STATE_OFFLINE:
3327 return NVME_SUCCESS;
3328 default:
3329 return NVME_ZONE_INVAL_TRANSITION;
3333 static uint16_t nvme_set_zd_ext(NvmeNamespace *ns, NvmeZone *zone)
3335 uint16_t status;
3336 uint8_t state = nvme_get_zone_state(zone);
3338 if (state == NVME_ZONE_STATE_EMPTY) {
3339 status = nvme_aor_check(ns, 1, 0);
3340 if (status) {
3341 return status;
3343 nvme_aor_inc_active(ns);
3344 zone->d.za |= NVME_ZA_ZD_EXT_VALID;
3345 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
3346 return NVME_SUCCESS;
3349 return NVME_ZONE_INVAL_TRANSITION;
3352 static uint16_t nvme_bulk_proc_zone(NvmeNamespace *ns, NvmeZone *zone,
3353 enum NvmeZoneProcessingMask proc_mask,
3354 op_handler_t op_hndlr, NvmeRequest *req)
3356 uint16_t status = NVME_SUCCESS;
3357 NvmeZoneState zs = nvme_get_zone_state(zone);
3358 bool proc_zone;
3360 switch (zs) {
3361 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
3362 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
3363 proc_zone = proc_mask & NVME_PROC_OPENED_ZONES;
3364 break;
3365 case NVME_ZONE_STATE_CLOSED:
3366 proc_zone = proc_mask & NVME_PROC_CLOSED_ZONES;
3367 break;
3368 case NVME_ZONE_STATE_READ_ONLY:
3369 proc_zone = proc_mask & NVME_PROC_READ_ONLY_ZONES;
3370 break;
3371 case NVME_ZONE_STATE_FULL:
3372 proc_zone = proc_mask & NVME_PROC_FULL_ZONES;
3373 break;
3374 default:
3375 proc_zone = false;
3378 if (proc_zone) {
3379 status = op_hndlr(ns, zone, zs, req);
3382 return status;
3385 static uint16_t nvme_do_zone_op(NvmeNamespace *ns, NvmeZone *zone,
3386 enum NvmeZoneProcessingMask proc_mask,
3387 op_handler_t op_hndlr, NvmeRequest *req)
3389 NvmeZone *next;
3390 uint16_t status = NVME_SUCCESS;
3391 int i;
3393 if (!proc_mask) {
3394 status = op_hndlr(ns, zone, nvme_get_zone_state(zone), req);
3395 } else {
3396 if (proc_mask & NVME_PROC_CLOSED_ZONES) {
3397 QTAILQ_FOREACH_SAFE(zone, &ns->closed_zones, entry, next) {
3398 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3399 req);
3400 if (status && status != NVME_NO_COMPLETE) {
3401 goto out;
3405 if (proc_mask & NVME_PROC_OPENED_ZONES) {
3406 QTAILQ_FOREACH_SAFE(zone, &ns->imp_open_zones, entry, next) {
3407 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3408 req);
3409 if (status && status != NVME_NO_COMPLETE) {
3410 goto out;
3414 QTAILQ_FOREACH_SAFE(zone, &ns->exp_open_zones, entry, next) {
3415 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3416 req);
3417 if (status && status != NVME_NO_COMPLETE) {
3418 goto out;
3422 if (proc_mask & NVME_PROC_FULL_ZONES) {
3423 QTAILQ_FOREACH_SAFE(zone, &ns->full_zones, entry, next) {
3424 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3425 req);
3426 if (status && status != NVME_NO_COMPLETE) {
3427 goto out;
3432 if (proc_mask & NVME_PROC_READ_ONLY_ZONES) {
3433 for (i = 0; i < ns->num_zones; i++, zone++) {
3434 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3435 req);
3436 if (status && status != NVME_NO_COMPLETE) {
3437 goto out;
3443 out:
3444 return status;
3447 typedef struct NvmeZoneResetAIOCB {
3448 BlockAIOCB common;
3449 BlockAIOCB *aiocb;
3450 NvmeRequest *req;
3451 QEMUBH *bh;
3452 int ret;
3454 bool all;
3455 int idx;
3456 NvmeZone *zone;
3457 } NvmeZoneResetAIOCB;
3459 static void nvme_zone_reset_cancel(BlockAIOCB *aiocb)
3461 NvmeZoneResetAIOCB *iocb = container_of(aiocb, NvmeZoneResetAIOCB, common);
3462 NvmeRequest *req = iocb->req;
3463 NvmeNamespace *ns = req->ns;
3465 iocb->idx = ns->num_zones;
3467 iocb->ret = -ECANCELED;
3469 if (iocb->aiocb) {
3470 blk_aio_cancel_async(iocb->aiocb);
3471 iocb->aiocb = NULL;
3475 static const AIOCBInfo nvme_zone_reset_aiocb_info = {
3476 .aiocb_size = sizeof(NvmeZoneResetAIOCB),
3477 .cancel_async = nvme_zone_reset_cancel,
3480 static void nvme_zone_reset_bh(void *opaque)
3482 NvmeZoneResetAIOCB *iocb = opaque;
3484 iocb->common.cb(iocb->common.opaque, iocb->ret);
3486 qemu_bh_delete(iocb->bh);
3487 iocb->bh = NULL;
3488 qemu_aio_unref(iocb);
3491 static void nvme_zone_reset_cb(void *opaque, int ret);
3493 static void nvme_zone_reset_epilogue_cb(void *opaque, int ret)
3495 NvmeZoneResetAIOCB *iocb = opaque;
3496 NvmeRequest *req = iocb->req;
3497 NvmeNamespace *ns = req->ns;
3498 int64_t moff;
3499 int count;
3501 if (ret < 0) {
3502 nvme_zone_reset_cb(iocb, ret);
3503 return;
3506 if (!ns->lbaf.ms) {
3507 nvme_zone_reset_cb(iocb, 0);
3508 return;
3511 moff = nvme_moff(ns, iocb->zone->d.zslba);
3512 count = nvme_m2b(ns, ns->zone_size);
3514 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, moff, count,
3515 BDRV_REQ_MAY_UNMAP,
3516 nvme_zone_reset_cb, iocb);
3517 return;
3520 static void nvme_zone_reset_cb(void *opaque, int ret)
3522 NvmeZoneResetAIOCB *iocb = opaque;
3523 NvmeRequest *req = iocb->req;
3524 NvmeNamespace *ns = req->ns;
3526 if (ret < 0) {
3527 iocb->ret = ret;
3528 goto done;
3531 if (iocb->zone) {
3532 nvme_zrm_reset(ns, iocb->zone);
3534 if (!iocb->all) {
3535 goto done;
3539 while (iocb->idx < ns->num_zones) {
3540 NvmeZone *zone = &ns->zone_array[iocb->idx++];
3542 switch (nvme_get_zone_state(zone)) {
3543 case NVME_ZONE_STATE_EMPTY:
3544 if (!iocb->all) {
3545 goto done;
3548 continue;
3550 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
3551 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
3552 case NVME_ZONE_STATE_CLOSED:
3553 case NVME_ZONE_STATE_FULL:
3554 iocb->zone = zone;
3555 break;
3557 default:
3558 continue;
3561 trace_pci_nvme_zns_zone_reset(zone->d.zslba);
3563 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk,
3564 nvme_l2b(ns, zone->d.zslba),
3565 nvme_l2b(ns, ns->zone_size),
3566 BDRV_REQ_MAY_UNMAP,
3567 nvme_zone_reset_epilogue_cb,
3568 iocb);
3569 return;
3572 done:
3573 iocb->aiocb = NULL;
3574 if (iocb->bh) {
3575 qemu_bh_schedule(iocb->bh);
3579 static uint16_t nvme_zone_mgmt_send(NvmeCtrl *n, NvmeRequest *req)
3581 NvmeCmd *cmd = (NvmeCmd *)&req->cmd;
3582 NvmeNamespace *ns = req->ns;
3583 NvmeZone *zone;
3584 NvmeZoneResetAIOCB *iocb;
3585 uint8_t *zd_ext;
3586 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
3587 uint64_t slba = 0;
3588 uint32_t zone_idx = 0;
3589 uint16_t status;
3590 uint8_t action;
3591 bool all;
3592 enum NvmeZoneProcessingMask proc_mask = NVME_PROC_CURRENT_ZONE;
3594 action = dw13 & 0xff;
3595 all = !!(dw13 & 0x100);
3597 req->status = NVME_SUCCESS;
3599 if (!all) {
3600 status = nvme_get_mgmt_zone_slba_idx(ns, cmd, &slba, &zone_idx);
3601 if (status) {
3602 return status;
3606 zone = &ns->zone_array[zone_idx];
3607 if (slba != zone->d.zslba) {
3608 trace_pci_nvme_err_unaligned_zone_cmd(action, slba, zone->d.zslba);
3609 return NVME_INVALID_FIELD | NVME_DNR;
3612 switch (action) {
3614 case NVME_ZONE_ACTION_OPEN:
3615 if (all) {
3616 proc_mask = NVME_PROC_CLOSED_ZONES;
3618 trace_pci_nvme_open_zone(slba, zone_idx, all);
3619 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_open_zone, req);
3620 break;
3622 case NVME_ZONE_ACTION_CLOSE:
3623 if (all) {
3624 proc_mask = NVME_PROC_OPENED_ZONES;
3626 trace_pci_nvme_close_zone(slba, zone_idx, all);
3627 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_close_zone, req);
3628 break;
3630 case NVME_ZONE_ACTION_FINISH:
3631 if (all) {
3632 proc_mask = NVME_PROC_OPENED_ZONES | NVME_PROC_CLOSED_ZONES;
3634 trace_pci_nvme_finish_zone(slba, zone_idx, all);
3635 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_finish_zone, req);
3636 break;
3638 case NVME_ZONE_ACTION_RESET:
3639 trace_pci_nvme_reset_zone(slba, zone_idx, all);
3641 iocb = blk_aio_get(&nvme_zone_reset_aiocb_info, ns->blkconf.blk,
3642 nvme_misc_cb, req);
3644 iocb->req = req;
3645 iocb->bh = qemu_bh_new(nvme_zone_reset_bh, iocb);
3646 iocb->ret = 0;
3647 iocb->all = all;
3648 iocb->idx = zone_idx;
3649 iocb->zone = NULL;
3651 req->aiocb = &iocb->common;
3652 nvme_zone_reset_cb(iocb, 0);
3654 return NVME_NO_COMPLETE;
3656 case NVME_ZONE_ACTION_OFFLINE:
3657 if (all) {
3658 proc_mask = NVME_PROC_READ_ONLY_ZONES;
3660 trace_pci_nvme_offline_zone(slba, zone_idx, all);
3661 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_offline_zone, req);
3662 break;
3664 case NVME_ZONE_ACTION_SET_ZD_EXT:
3665 trace_pci_nvme_set_descriptor_extension(slba, zone_idx);
3666 if (all || !ns->params.zd_extension_size) {
3667 return NVME_INVALID_FIELD | NVME_DNR;
3669 zd_ext = nvme_get_zd_extension(ns, zone_idx);
3670 status = nvme_h2c(n, zd_ext, ns->params.zd_extension_size, req);
3671 if (status) {
3672 trace_pci_nvme_err_zd_extension_map_error(zone_idx);
3673 return status;
3676 status = nvme_set_zd_ext(ns, zone);
3677 if (status == NVME_SUCCESS) {
3678 trace_pci_nvme_zd_extension_set(zone_idx);
3679 return status;
3681 break;
3683 default:
3684 trace_pci_nvme_err_invalid_mgmt_action(action);
3685 status = NVME_INVALID_FIELD;
3688 if (status == NVME_ZONE_INVAL_TRANSITION) {
3689 trace_pci_nvme_err_invalid_zone_state_transition(action, slba,
3690 zone->d.za);
3692 if (status) {
3693 status |= NVME_DNR;
3696 return status;
3699 static bool nvme_zone_matches_filter(uint32_t zafs, NvmeZone *zl)
3701 NvmeZoneState zs = nvme_get_zone_state(zl);
3703 switch (zafs) {
3704 case NVME_ZONE_REPORT_ALL:
3705 return true;
3706 case NVME_ZONE_REPORT_EMPTY:
3707 return zs == NVME_ZONE_STATE_EMPTY;
3708 case NVME_ZONE_REPORT_IMPLICITLY_OPEN:
3709 return zs == NVME_ZONE_STATE_IMPLICITLY_OPEN;
3710 case NVME_ZONE_REPORT_EXPLICITLY_OPEN:
3711 return zs == NVME_ZONE_STATE_EXPLICITLY_OPEN;
3712 case NVME_ZONE_REPORT_CLOSED:
3713 return zs == NVME_ZONE_STATE_CLOSED;
3714 case NVME_ZONE_REPORT_FULL:
3715 return zs == NVME_ZONE_STATE_FULL;
3716 case NVME_ZONE_REPORT_READ_ONLY:
3717 return zs == NVME_ZONE_STATE_READ_ONLY;
3718 case NVME_ZONE_REPORT_OFFLINE:
3719 return zs == NVME_ZONE_STATE_OFFLINE;
3720 default:
3721 return false;
3725 static uint16_t nvme_zone_mgmt_recv(NvmeCtrl *n, NvmeRequest *req)
3727 NvmeCmd *cmd = (NvmeCmd *)&req->cmd;
3728 NvmeNamespace *ns = req->ns;
3729 /* cdw12 is zero-based number of dwords to return. Convert to bytes */
3730 uint32_t data_size = (le32_to_cpu(cmd->cdw12) + 1) << 2;
3731 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
3732 uint32_t zone_idx, zra, zrasf, partial;
3733 uint64_t max_zones, nr_zones = 0;
3734 uint16_t status;
3735 uint64_t slba;
3736 NvmeZoneDescr *z;
3737 NvmeZone *zone;
3738 NvmeZoneReportHeader *header;
3739 void *buf, *buf_p;
3740 size_t zone_entry_sz;
3741 int i;
3743 req->status = NVME_SUCCESS;
3745 status = nvme_get_mgmt_zone_slba_idx(ns, cmd, &slba, &zone_idx);
3746 if (status) {
3747 return status;
3750 zra = dw13 & 0xff;
3751 if (zra != NVME_ZONE_REPORT && zra != NVME_ZONE_REPORT_EXTENDED) {
3752 return NVME_INVALID_FIELD | NVME_DNR;
3754 if (zra == NVME_ZONE_REPORT_EXTENDED && !ns->params.zd_extension_size) {
3755 return NVME_INVALID_FIELD | NVME_DNR;
3758 zrasf = (dw13 >> 8) & 0xff;
3759 if (zrasf > NVME_ZONE_REPORT_OFFLINE) {
3760 return NVME_INVALID_FIELD | NVME_DNR;
3763 if (data_size < sizeof(NvmeZoneReportHeader)) {
3764 return NVME_INVALID_FIELD | NVME_DNR;
3767 status = nvme_check_mdts(n, data_size);
3768 if (status) {
3769 return status;
3772 partial = (dw13 >> 16) & 0x01;
3774 zone_entry_sz = sizeof(NvmeZoneDescr);
3775 if (zra == NVME_ZONE_REPORT_EXTENDED) {
3776 zone_entry_sz += ns->params.zd_extension_size;
3779 max_zones = (data_size - sizeof(NvmeZoneReportHeader)) / zone_entry_sz;
3780 buf = g_malloc0(data_size);
3782 zone = &ns->zone_array[zone_idx];
3783 for (i = zone_idx; i < ns->num_zones; i++) {
3784 if (partial && nr_zones >= max_zones) {
3785 break;
3787 if (nvme_zone_matches_filter(zrasf, zone++)) {
3788 nr_zones++;
3791 header = (NvmeZoneReportHeader *)buf;
3792 header->nr_zones = cpu_to_le64(nr_zones);
3794 buf_p = buf + sizeof(NvmeZoneReportHeader);
3795 for (; zone_idx < ns->num_zones && max_zones > 0; zone_idx++) {
3796 zone = &ns->zone_array[zone_idx];
3797 if (nvme_zone_matches_filter(zrasf, zone)) {
3798 z = (NvmeZoneDescr *)buf_p;
3799 buf_p += sizeof(NvmeZoneDescr);
3801 z->zt = zone->d.zt;
3802 z->zs = zone->d.zs;
3803 z->zcap = cpu_to_le64(zone->d.zcap);
3804 z->zslba = cpu_to_le64(zone->d.zslba);
3805 z->za = zone->d.za;
3807 if (nvme_wp_is_valid(zone)) {
3808 z->wp = cpu_to_le64(zone->d.wp);
3809 } else {
3810 z->wp = cpu_to_le64(~0ULL);
3813 if (zra == NVME_ZONE_REPORT_EXTENDED) {
3814 if (zone->d.za & NVME_ZA_ZD_EXT_VALID) {
3815 memcpy(buf_p, nvme_get_zd_extension(ns, zone_idx),
3816 ns->params.zd_extension_size);
3818 buf_p += ns->params.zd_extension_size;
3821 max_zones--;
3825 status = nvme_c2h(n, (uint8_t *)buf, data_size, req);
3827 g_free(buf);
3829 return status;
3832 static uint16_t nvme_io_cmd(NvmeCtrl *n, NvmeRequest *req)
3834 NvmeNamespace *ns;
3835 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
3837 trace_pci_nvme_io_cmd(nvme_cid(req), nsid, nvme_sqid(req),
3838 req->cmd.opcode, nvme_io_opc_str(req->cmd.opcode));
3840 if (!nvme_nsid_valid(n, nsid)) {
3841 return NVME_INVALID_NSID | NVME_DNR;
3845 * In the base NVM command set, Flush may apply to all namespaces
3846 * (indicated by NSID being set to FFFFFFFFh). But if that feature is used
3847 * along with TP 4056 (Namespace Types), it may be pretty screwed up.
3849 * If NSID is indeed set to FFFFFFFFh, we simply cannot associate the
3850 * opcode with a specific command since we cannot determine a unique I/O
3851 * command set. Opcode 0h could have any other meaning than something
3852 * equivalent to flushing and say it DOES have completely different
3853 * semantics in some other command set - does an NSID of FFFFFFFFh then
3854 * mean "for all namespaces, apply whatever command set specific command
3855 * that uses the 0h opcode?" Or does it mean "for all namespaces, apply
3856 * whatever command that uses the 0h opcode if, and only if, it allows NSID
3857 * to be FFFFFFFFh"?
3859 * Anyway (and luckily), for now, we do not care about this since the
3860 * device only supports namespace types that includes the NVM Flush command
3861 * (NVM and Zoned), so always do an NVM Flush.
3863 if (req->cmd.opcode == NVME_CMD_FLUSH) {
3864 return nvme_flush(n, req);
3867 ns = nvme_ns(n, nsid);
3868 if (unlikely(!ns)) {
3869 return NVME_INVALID_FIELD | NVME_DNR;
3872 if (!(ns->iocs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
3873 trace_pci_nvme_err_invalid_opc(req->cmd.opcode);
3874 return NVME_INVALID_OPCODE | NVME_DNR;
3877 if (ns->status) {
3878 return ns->status;
3881 req->ns = ns;
3883 switch (req->cmd.opcode) {
3884 case NVME_CMD_WRITE_ZEROES:
3885 return nvme_write_zeroes(n, req);
3886 case NVME_CMD_ZONE_APPEND:
3887 return nvme_zone_append(n, req);
3888 case NVME_CMD_WRITE:
3889 return nvme_write(n, req);
3890 case NVME_CMD_READ:
3891 return nvme_read(n, req);
3892 case NVME_CMD_COMPARE:
3893 return nvme_compare(n, req);
3894 case NVME_CMD_DSM:
3895 return nvme_dsm(n, req);
3896 case NVME_CMD_VERIFY:
3897 return nvme_verify(n, req);
3898 case NVME_CMD_COPY:
3899 return nvme_copy(n, req);
3900 case NVME_CMD_ZONE_MGMT_SEND:
3901 return nvme_zone_mgmt_send(n, req);
3902 case NVME_CMD_ZONE_MGMT_RECV:
3903 return nvme_zone_mgmt_recv(n, req);
3904 default:
3905 assert(false);
3908 return NVME_INVALID_OPCODE | NVME_DNR;
3911 static void nvme_free_sq(NvmeSQueue *sq, NvmeCtrl *n)
3913 n->sq[sq->sqid] = NULL;
3914 timer_free(sq->timer);
3915 g_free(sq->io_req);
3916 if (sq->sqid) {
3917 g_free(sq);
3921 static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeRequest *req)
3923 NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
3924 NvmeRequest *r, *next;
3925 NvmeSQueue *sq;
3926 NvmeCQueue *cq;
3927 uint16_t qid = le16_to_cpu(c->qid);
3929 if (unlikely(!qid || nvme_check_sqid(n, qid))) {
3930 trace_pci_nvme_err_invalid_del_sq(qid);
3931 return NVME_INVALID_QID | NVME_DNR;
3934 trace_pci_nvme_del_sq(qid);
3936 sq = n->sq[qid];
3937 while (!QTAILQ_EMPTY(&sq->out_req_list)) {
3938 r = QTAILQ_FIRST(&sq->out_req_list);
3939 assert(r->aiocb);
3940 blk_aio_cancel(r->aiocb);
3943 assert(QTAILQ_EMPTY(&sq->out_req_list));
3945 if (!nvme_check_cqid(n, sq->cqid)) {
3946 cq = n->cq[sq->cqid];
3947 QTAILQ_REMOVE(&cq->sq_list, sq, entry);
3949 nvme_post_cqes(cq);
3950 QTAILQ_FOREACH_SAFE(r, &cq->req_list, entry, next) {
3951 if (r->sq == sq) {
3952 QTAILQ_REMOVE(&cq->req_list, r, entry);
3953 QTAILQ_INSERT_TAIL(&sq->req_list, r, entry);
3958 nvme_free_sq(sq, n);
3959 return NVME_SUCCESS;
3962 static void nvme_init_sq(NvmeSQueue *sq, NvmeCtrl *n, uint64_t dma_addr,
3963 uint16_t sqid, uint16_t cqid, uint16_t size)
3965 int i;
3966 NvmeCQueue *cq;
3968 sq->ctrl = n;
3969 sq->dma_addr = dma_addr;
3970 sq->sqid = sqid;
3971 sq->size = size;
3972 sq->cqid = cqid;
3973 sq->head = sq->tail = 0;
3974 sq->io_req = g_new0(NvmeRequest, sq->size);
3976 QTAILQ_INIT(&sq->req_list);
3977 QTAILQ_INIT(&sq->out_req_list);
3978 for (i = 0; i < sq->size; i++) {
3979 sq->io_req[i].sq = sq;
3980 QTAILQ_INSERT_TAIL(&(sq->req_list), &sq->io_req[i], entry);
3982 sq->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, nvme_process_sq, sq);
3984 assert(n->cq[cqid]);
3985 cq = n->cq[cqid];
3986 QTAILQ_INSERT_TAIL(&(cq->sq_list), sq, entry);
3987 n->sq[sqid] = sq;
3990 static uint16_t nvme_create_sq(NvmeCtrl *n, NvmeRequest *req)
3992 NvmeSQueue *sq;
3993 NvmeCreateSq *c = (NvmeCreateSq *)&req->cmd;
3995 uint16_t cqid = le16_to_cpu(c->cqid);
3996 uint16_t sqid = le16_to_cpu(c->sqid);
3997 uint16_t qsize = le16_to_cpu(c->qsize);
3998 uint16_t qflags = le16_to_cpu(c->sq_flags);
3999 uint64_t prp1 = le64_to_cpu(c->prp1);
4001 trace_pci_nvme_create_sq(prp1, sqid, cqid, qsize, qflags);
4003 if (unlikely(!cqid || nvme_check_cqid(n, cqid))) {
4004 trace_pci_nvme_err_invalid_create_sq_cqid(cqid);
4005 return NVME_INVALID_CQID | NVME_DNR;
4007 if (unlikely(!sqid || sqid > n->params.max_ioqpairs ||
4008 n->sq[sqid] != NULL)) {
4009 trace_pci_nvme_err_invalid_create_sq_sqid(sqid);
4010 return NVME_INVALID_QID | NVME_DNR;
4012 if (unlikely(!qsize || qsize > NVME_CAP_MQES(n->bar.cap))) {
4013 trace_pci_nvme_err_invalid_create_sq_size(qsize);
4014 return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
4016 if (unlikely(prp1 & (n->page_size - 1))) {
4017 trace_pci_nvme_err_invalid_create_sq_addr(prp1);
4018 return NVME_INVALID_PRP_OFFSET | NVME_DNR;
4020 if (unlikely(!(NVME_SQ_FLAGS_PC(qflags)))) {
4021 trace_pci_nvme_err_invalid_create_sq_qflags(NVME_SQ_FLAGS_PC(qflags));
4022 return NVME_INVALID_FIELD | NVME_DNR;
4024 sq = g_malloc0(sizeof(*sq));
4025 nvme_init_sq(sq, n, prp1, sqid, cqid, qsize + 1);
4026 return NVME_SUCCESS;
4029 struct nvme_stats {
4030 uint64_t units_read;
4031 uint64_t units_written;
4032 uint64_t read_commands;
4033 uint64_t write_commands;
4036 static void nvme_set_blk_stats(NvmeNamespace *ns, struct nvme_stats *stats)
4038 BlockAcctStats *s = blk_get_stats(ns->blkconf.blk);
4040 stats->units_read += s->nr_bytes[BLOCK_ACCT_READ] >> BDRV_SECTOR_BITS;
4041 stats->units_written += s->nr_bytes[BLOCK_ACCT_WRITE] >> BDRV_SECTOR_BITS;
4042 stats->read_commands += s->nr_ops[BLOCK_ACCT_READ];
4043 stats->write_commands += s->nr_ops[BLOCK_ACCT_WRITE];
4046 static uint16_t nvme_smart_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4047 uint64_t off, NvmeRequest *req)
4049 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
4050 struct nvme_stats stats = { 0 };
4051 NvmeSmartLog smart = { 0 };
4052 uint32_t trans_len;
4053 NvmeNamespace *ns;
4054 time_t current_ms;
4056 if (off >= sizeof(smart)) {
4057 return NVME_INVALID_FIELD | NVME_DNR;
4060 if (nsid != 0xffffffff) {
4061 ns = nvme_ns(n, nsid);
4062 if (!ns) {
4063 return NVME_INVALID_NSID | NVME_DNR;
4065 nvme_set_blk_stats(ns, &stats);
4066 } else {
4067 int i;
4069 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4070 ns = nvme_ns(n, i);
4071 if (!ns) {
4072 continue;
4074 nvme_set_blk_stats(ns, &stats);
4078 trans_len = MIN(sizeof(smart) - off, buf_len);
4079 smart.critical_warning = n->smart_critical_warning;
4081 smart.data_units_read[0] = cpu_to_le64(DIV_ROUND_UP(stats.units_read,
4082 1000));
4083 smart.data_units_written[0] = cpu_to_le64(DIV_ROUND_UP(stats.units_written,
4084 1000));
4085 smart.host_read_commands[0] = cpu_to_le64(stats.read_commands);
4086 smart.host_write_commands[0] = cpu_to_le64(stats.write_commands);
4088 smart.temperature = cpu_to_le16(n->temperature);
4090 if ((n->temperature >= n->features.temp_thresh_hi) ||
4091 (n->temperature <= n->features.temp_thresh_low)) {
4092 smart.critical_warning |= NVME_SMART_TEMPERATURE;
4095 current_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
4096 smart.power_on_hours[0] =
4097 cpu_to_le64((((current_ms - n->starttime_ms) / 1000) / 60) / 60);
4099 if (!rae) {
4100 nvme_clear_events(n, NVME_AER_TYPE_SMART);
4103 return nvme_c2h(n, (uint8_t *) &smart + off, trans_len, req);
4106 static uint16_t nvme_fw_log_info(NvmeCtrl *n, uint32_t buf_len, uint64_t off,
4107 NvmeRequest *req)
4109 uint32_t trans_len;
4110 NvmeFwSlotInfoLog fw_log = {
4111 .afi = 0x1,
4114 if (off >= sizeof(fw_log)) {
4115 return NVME_INVALID_FIELD | NVME_DNR;
4118 strpadcpy((char *)&fw_log.frs1, sizeof(fw_log.frs1), "1.0", ' ');
4119 trans_len = MIN(sizeof(fw_log) - off, buf_len);
4121 return nvme_c2h(n, (uint8_t *) &fw_log + off, trans_len, req);
4124 static uint16_t nvme_error_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4125 uint64_t off, NvmeRequest *req)
4127 uint32_t trans_len;
4128 NvmeErrorLog errlog;
4130 if (off >= sizeof(errlog)) {
4131 return NVME_INVALID_FIELD | NVME_DNR;
4134 if (!rae) {
4135 nvme_clear_events(n, NVME_AER_TYPE_ERROR);
4138 memset(&errlog, 0x0, sizeof(errlog));
4139 trans_len = MIN(sizeof(errlog) - off, buf_len);
4141 return nvme_c2h(n, (uint8_t *)&errlog, trans_len, req);
4144 static uint16_t nvme_changed_nslist(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4145 uint64_t off, NvmeRequest *req)
4147 uint32_t nslist[1024];
4148 uint32_t trans_len;
4149 int i = 0;
4150 uint32_t nsid;
4152 memset(nslist, 0x0, sizeof(nslist));
4153 trans_len = MIN(sizeof(nslist) - off, buf_len);
4155 while ((nsid = find_first_bit(n->changed_nsids, NVME_CHANGED_NSID_SIZE)) !=
4156 NVME_CHANGED_NSID_SIZE) {
4158 * If more than 1024 namespaces, the first entry in the log page should
4159 * be set to FFFFFFFFh and the others to 0 as spec.
4161 if (i == ARRAY_SIZE(nslist)) {
4162 memset(nslist, 0x0, sizeof(nslist));
4163 nslist[0] = 0xffffffff;
4164 break;
4167 nslist[i++] = nsid;
4168 clear_bit(nsid, n->changed_nsids);
4172 * Remove all the remaining list entries in case returns directly due to
4173 * more than 1024 namespaces.
4175 if (nslist[0] == 0xffffffff) {
4176 bitmap_zero(n->changed_nsids, NVME_CHANGED_NSID_SIZE);
4179 if (!rae) {
4180 nvme_clear_events(n, NVME_AER_TYPE_NOTICE);
4183 return nvme_c2h(n, ((uint8_t *)nslist) + off, trans_len, req);
4186 static uint16_t nvme_cmd_effects(NvmeCtrl *n, uint8_t csi, uint32_t buf_len,
4187 uint64_t off, NvmeRequest *req)
4189 NvmeEffectsLog log = {};
4190 const uint32_t *src_iocs = NULL;
4191 uint32_t trans_len;
4193 if (off >= sizeof(log)) {
4194 trace_pci_nvme_err_invalid_log_page_offset(off, sizeof(log));
4195 return NVME_INVALID_FIELD | NVME_DNR;
4198 switch (NVME_CC_CSS(n->bar.cc)) {
4199 case NVME_CC_CSS_NVM:
4200 src_iocs = nvme_cse_iocs_nvm;
4201 /* fall through */
4202 case NVME_CC_CSS_ADMIN_ONLY:
4203 break;
4204 case NVME_CC_CSS_CSI:
4205 switch (csi) {
4206 case NVME_CSI_NVM:
4207 src_iocs = nvme_cse_iocs_nvm;
4208 break;
4209 case NVME_CSI_ZONED:
4210 src_iocs = nvme_cse_iocs_zoned;
4211 break;
4215 memcpy(log.acs, nvme_cse_acs, sizeof(nvme_cse_acs));
4217 if (src_iocs) {
4218 memcpy(log.iocs, src_iocs, sizeof(log.iocs));
4221 trans_len = MIN(sizeof(log) - off, buf_len);
4223 return nvme_c2h(n, ((uint8_t *)&log) + off, trans_len, req);
4226 static uint16_t nvme_get_log(NvmeCtrl *n, NvmeRequest *req)
4228 NvmeCmd *cmd = &req->cmd;
4230 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
4231 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
4232 uint32_t dw12 = le32_to_cpu(cmd->cdw12);
4233 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
4234 uint8_t lid = dw10 & 0xff;
4235 uint8_t lsp = (dw10 >> 8) & 0xf;
4236 uint8_t rae = (dw10 >> 15) & 0x1;
4237 uint8_t csi = le32_to_cpu(cmd->cdw14) >> 24;
4238 uint32_t numdl, numdu;
4239 uint64_t off, lpol, lpou;
4240 size_t len;
4241 uint16_t status;
4243 numdl = (dw10 >> 16);
4244 numdu = (dw11 & 0xffff);
4245 lpol = dw12;
4246 lpou = dw13;
4248 len = (((numdu << 16) | numdl) + 1) << 2;
4249 off = (lpou << 32ULL) | lpol;
4251 if (off & 0x3) {
4252 return NVME_INVALID_FIELD | NVME_DNR;
4255 trace_pci_nvme_get_log(nvme_cid(req), lid, lsp, rae, len, off);
4257 status = nvme_check_mdts(n, len);
4258 if (status) {
4259 return status;
4262 switch (lid) {
4263 case NVME_LOG_ERROR_INFO:
4264 return nvme_error_info(n, rae, len, off, req);
4265 case NVME_LOG_SMART_INFO:
4266 return nvme_smart_info(n, rae, len, off, req);
4267 case NVME_LOG_FW_SLOT_INFO:
4268 return nvme_fw_log_info(n, len, off, req);
4269 case NVME_LOG_CHANGED_NSLIST:
4270 return nvme_changed_nslist(n, rae, len, off, req);
4271 case NVME_LOG_CMD_EFFECTS:
4272 return nvme_cmd_effects(n, csi, len, off, req);
4273 default:
4274 trace_pci_nvme_err_invalid_log_page(nvme_cid(req), lid);
4275 return NVME_INVALID_FIELD | NVME_DNR;
4279 static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
4281 n->cq[cq->cqid] = NULL;
4282 timer_free(cq->timer);
4283 if (msix_enabled(&n->parent_obj)) {
4284 msix_vector_unuse(&n->parent_obj, cq->vector);
4286 if (cq->cqid) {
4287 g_free(cq);
4291 static uint16_t nvme_del_cq(NvmeCtrl *n, NvmeRequest *req)
4293 NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
4294 NvmeCQueue *cq;
4295 uint16_t qid = le16_to_cpu(c->qid);
4297 if (unlikely(!qid || nvme_check_cqid(n, qid))) {
4298 trace_pci_nvme_err_invalid_del_cq_cqid(qid);
4299 return NVME_INVALID_CQID | NVME_DNR;
4302 cq = n->cq[qid];
4303 if (unlikely(!QTAILQ_EMPTY(&cq->sq_list))) {
4304 trace_pci_nvme_err_invalid_del_cq_notempty(qid);
4305 return NVME_INVALID_QUEUE_DEL;
4308 if (cq->irq_enabled && cq->tail != cq->head) {
4309 n->cq_pending--;
4312 nvme_irq_deassert(n, cq);
4313 trace_pci_nvme_del_cq(qid);
4314 nvme_free_cq(cq, n);
4315 return NVME_SUCCESS;
4318 static void nvme_init_cq(NvmeCQueue *cq, NvmeCtrl *n, uint64_t dma_addr,
4319 uint16_t cqid, uint16_t vector, uint16_t size,
4320 uint16_t irq_enabled)
4322 int ret;
4324 if (msix_enabled(&n->parent_obj)) {
4325 ret = msix_vector_use(&n->parent_obj, vector);
4326 assert(ret == 0);
4328 cq->ctrl = n;
4329 cq->cqid = cqid;
4330 cq->size = size;
4331 cq->dma_addr = dma_addr;
4332 cq->phase = 1;
4333 cq->irq_enabled = irq_enabled;
4334 cq->vector = vector;
4335 cq->head = cq->tail = 0;
4336 QTAILQ_INIT(&cq->req_list);
4337 QTAILQ_INIT(&cq->sq_list);
4338 n->cq[cqid] = cq;
4339 cq->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, nvme_post_cqes, cq);
4342 static uint16_t nvme_create_cq(NvmeCtrl *n, NvmeRequest *req)
4344 NvmeCQueue *cq;
4345 NvmeCreateCq *c = (NvmeCreateCq *)&req->cmd;
4346 uint16_t cqid = le16_to_cpu(c->cqid);
4347 uint16_t vector = le16_to_cpu(c->irq_vector);
4348 uint16_t qsize = le16_to_cpu(c->qsize);
4349 uint16_t qflags = le16_to_cpu(c->cq_flags);
4350 uint64_t prp1 = le64_to_cpu(c->prp1);
4352 trace_pci_nvme_create_cq(prp1, cqid, vector, qsize, qflags,
4353 NVME_CQ_FLAGS_IEN(qflags) != 0);
4355 if (unlikely(!cqid || cqid > n->params.max_ioqpairs ||
4356 n->cq[cqid] != NULL)) {
4357 trace_pci_nvme_err_invalid_create_cq_cqid(cqid);
4358 return NVME_INVALID_QID | NVME_DNR;
4360 if (unlikely(!qsize || qsize > NVME_CAP_MQES(n->bar.cap))) {
4361 trace_pci_nvme_err_invalid_create_cq_size(qsize);
4362 return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
4364 if (unlikely(prp1 & (n->page_size - 1))) {
4365 trace_pci_nvme_err_invalid_create_cq_addr(prp1);
4366 return NVME_INVALID_PRP_OFFSET | NVME_DNR;
4368 if (unlikely(!msix_enabled(&n->parent_obj) && vector)) {
4369 trace_pci_nvme_err_invalid_create_cq_vector(vector);
4370 return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
4372 if (unlikely(vector >= n->params.msix_qsize)) {
4373 trace_pci_nvme_err_invalid_create_cq_vector(vector);
4374 return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
4376 if (unlikely(!(NVME_CQ_FLAGS_PC(qflags)))) {
4377 trace_pci_nvme_err_invalid_create_cq_qflags(NVME_CQ_FLAGS_PC(qflags));
4378 return NVME_INVALID_FIELD | NVME_DNR;
4381 cq = g_malloc0(sizeof(*cq));
4382 nvme_init_cq(cq, n, prp1, cqid, vector, qsize + 1,
4383 NVME_CQ_FLAGS_IEN(qflags));
4386 * It is only required to set qs_created when creating a completion queue;
4387 * creating a submission queue without a matching completion queue will
4388 * fail.
4390 n->qs_created = true;
4391 return NVME_SUCCESS;
4394 static uint16_t nvme_rpt_empty_id_struct(NvmeCtrl *n, NvmeRequest *req)
4396 uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
4398 return nvme_c2h(n, id, sizeof(id), req);
4401 static uint16_t nvme_identify_ctrl(NvmeCtrl *n, NvmeRequest *req)
4403 trace_pci_nvme_identify_ctrl();
4405 return nvme_c2h(n, (uint8_t *)&n->id_ctrl, sizeof(n->id_ctrl), req);
4408 static uint16_t nvme_identify_ctrl_csi(NvmeCtrl *n, NvmeRequest *req)
4410 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4411 uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
4412 NvmeIdCtrlNvm *id_nvm = (NvmeIdCtrlNvm *)&id;
4414 trace_pci_nvme_identify_ctrl_csi(c->csi);
4416 switch (c->csi) {
4417 case NVME_CSI_NVM:
4418 id_nvm->vsl = n->params.vsl;
4419 id_nvm->dmrsl = cpu_to_le32(n->dmrsl);
4420 break;
4422 case NVME_CSI_ZONED:
4423 ((NvmeIdCtrlZoned *)&id)->zasl = n->params.zasl;
4424 break;
4426 default:
4427 return NVME_INVALID_FIELD | NVME_DNR;
4430 return nvme_c2h(n, id, sizeof(id), req);
4433 static uint16_t nvme_identify_ns(NvmeCtrl *n, NvmeRequest *req, bool active)
4435 NvmeNamespace *ns;
4436 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4437 uint32_t nsid = le32_to_cpu(c->nsid);
4439 trace_pci_nvme_identify_ns(nsid);
4441 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
4442 return NVME_INVALID_NSID | NVME_DNR;
4445 ns = nvme_ns(n, nsid);
4446 if (unlikely(!ns)) {
4447 if (!active) {
4448 ns = nvme_subsys_ns(n->subsys, nsid);
4449 if (!ns) {
4450 return nvme_rpt_empty_id_struct(n, req);
4452 } else {
4453 return nvme_rpt_empty_id_struct(n, req);
4457 if (active || ns->csi == NVME_CSI_NVM) {
4458 return nvme_c2h(n, (uint8_t *)&ns->id_ns, sizeof(NvmeIdNs), req);
4461 return NVME_INVALID_CMD_SET | NVME_DNR;
4464 static uint16_t nvme_identify_ctrl_list(NvmeCtrl *n, NvmeRequest *req,
4465 bool attached)
4467 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4468 uint32_t nsid = le32_to_cpu(c->nsid);
4469 uint16_t min_id = le16_to_cpu(c->ctrlid);
4470 uint16_t list[NVME_CONTROLLER_LIST_SIZE] = {};
4471 uint16_t *ids = &list[1];
4472 NvmeNamespace *ns;
4473 NvmeCtrl *ctrl;
4474 int cntlid, nr_ids = 0;
4476 trace_pci_nvme_identify_ctrl_list(c->cns, min_id);
4478 if (!n->subsys) {
4479 return NVME_INVALID_FIELD | NVME_DNR;
4482 if (attached) {
4483 if (nsid == NVME_NSID_BROADCAST) {
4484 return NVME_INVALID_FIELD | NVME_DNR;
4487 ns = nvme_subsys_ns(n->subsys, nsid);
4488 if (!ns) {
4489 return NVME_INVALID_FIELD | NVME_DNR;
4493 for (cntlid = min_id; cntlid < ARRAY_SIZE(n->subsys->ctrls); cntlid++) {
4494 ctrl = nvme_subsys_ctrl(n->subsys, cntlid);
4495 if (!ctrl) {
4496 continue;
4499 if (attached && !nvme_ns(ctrl, nsid)) {
4500 continue;
4503 ids[nr_ids++] = cntlid;
4506 list[0] = nr_ids;
4508 return nvme_c2h(n, (uint8_t *)list, sizeof(list), req);
4511 static uint16_t nvme_identify_ns_csi(NvmeCtrl *n, NvmeRequest *req,
4512 bool active)
4514 NvmeNamespace *ns;
4515 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4516 uint32_t nsid = le32_to_cpu(c->nsid);
4518 trace_pci_nvme_identify_ns_csi(nsid, c->csi);
4520 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
4521 return NVME_INVALID_NSID | NVME_DNR;
4524 ns = nvme_ns(n, nsid);
4525 if (unlikely(!ns)) {
4526 if (!active) {
4527 ns = nvme_subsys_ns(n->subsys, nsid);
4528 if (!ns) {
4529 return nvme_rpt_empty_id_struct(n, req);
4531 } else {
4532 return nvme_rpt_empty_id_struct(n, req);
4536 if (c->csi == NVME_CSI_NVM) {
4537 return nvme_rpt_empty_id_struct(n, req);
4538 } else if (c->csi == NVME_CSI_ZONED && ns->csi == NVME_CSI_ZONED) {
4539 return nvme_c2h(n, (uint8_t *)ns->id_ns_zoned, sizeof(NvmeIdNsZoned),
4540 req);
4543 return NVME_INVALID_FIELD | NVME_DNR;
4546 static uint16_t nvme_identify_nslist(NvmeCtrl *n, NvmeRequest *req,
4547 bool active)
4549 NvmeNamespace *ns;
4550 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4551 uint32_t min_nsid = le32_to_cpu(c->nsid);
4552 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
4553 static const int data_len = sizeof(list);
4554 uint32_t *list_ptr = (uint32_t *)list;
4555 int i, j = 0;
4557 trace_pci_nvme_identify_nslist(min_nsid);
4560 * Both FFFFFFFFh (NVME_NSID_BROADCAST) and FFFFFFFFEh are invalid values
4561 * since the Active Namespace ID List should return namespaces with ids
4562 * *higher* than the NSID specified in the command. This is also specified
4563 * in the spec (NVM Express v1.3d, Section 5.15.4).
4565 if (min_nsid >= NVME_NSID_BROADCAST - 1) {
4566 return NVME_INVALID_NSID | NVME_DNR;
4569 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4570 ns = nvme_ns(n, i);
4571 if (!ns) {
4572 if (!active) {
4573 ns = nvme_subsys_ns(n->subsys, i);
4574 if (!ns) {
4575 continue;
4577 } else {
4578 continue;
4581 if (ns->params.nsid <= min_nsid) {
4582 continue;
4584 list_ptr[j++] = cpu_to_le32(ns->params.nsid);
4585 if (j == data_len / sizeof(uint32_t)) {
4586 break;
4590 return nvme_c2h(n, list, data_len, req);
4593 static uint16_t nvme_identify_nslist_csi(NvmeCtrl *n, NvmeRequest *req,
4594 bool active)
4596 NvmeNamespace *ns;
4597 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4598 uint32_t min_nsid = le32_to_cpu(c->nsid);
4599 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
4600 static const int data_len = sizeof(list);
4601 uint32_t *list_ptr = (uint32_t *)list;
4602 int i, j = 0;
4604 trace_pci_nvme_identify_nslist_csi(min_nsid, c->csi);
4607 * Same as in nvme_identify_nslist(), FFFFFFFFh/FFFFFFFFEh are invalid.
4609 if (min_nsid >= NVME_NSID_BROADCAST - 1) {
4610 return NVME_INVALID_NSID | NVME_DNR;
4613 if (c->csi != NVME_CSI_NVM && c->csi != NVME_CSI_ZONED) {
4614 return NVME_INVALID_FIELD | NVME_DNR;
4617 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4618 ns = nvme_ns(n, i);
4619 if (!ns) {
4620 if (!active) {
4621 ns = nvme_subsys_ns(n->subsys, i);
4622 if (!ns) {
4623 continue;
4625 } else {
4626 continue;
4629 if (ns->params.nsid <= min_nsid || c->csi != ns->csi) {
4630 continue;
4632 list_ptr[j++] = cpu_to_le32(ns->params.nsid);
4633 if (j == data_len / sizeof(uint32_t)) {
4634 break;
4638 return nvme_c2h(n, list, data_len, req);
4641 static uint16_t nvme_identify_ns_descr_list(NvmeCtrl *n, NvmeRequest *req)
4643 NvmeNamespace *ns;
4644 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4645 uint32_t nsid = le32_to_cpu(c->nsid);
4646 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
4647 uint8_t *pos = list;
4648 struct {
4649 NvmeIdNsDescr hdr;
4650 uint8_t v[NVME_NIDL_UUID];
4651 } QEMU_PACKED uuid;
4652 struct {
4653 NvmeIdNsDescr hdr;
4654 uint64_t v;
4655 } QEMU_PACKED eui64;
4656 struct {
4657 NvmeIdNsDescr hdr;
4658 uint8_t v;
4659 } QEMU_PACKED csi;
4661 trace_pci_nvme_identify_ns_descr_list(nsid);
4663 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
4664 return NVME_INVALID_NSID | NVME_DNR;
4667 ns = nvme_ns(n, nsid);
4668 if (unlikely(!ns)) {
4669 return NVME_INVALID_FIELD | NVME_DNR;
4673 * If the EUI-64 field is 0 and the NGUID field is 0, the namespace must
4674 * provide a valid Namespace UUID in the Namespace Identification Descriptor
4675 * data structure. QEMU does not yet support setting NGUID.
4677 uuid.hdr.nidt = NVME_NIDT_UUID;
4678 uuid.hdr.nidl = NVME_NIDL_UUID;
4679 memcpy(uuid.v, ns->params.uuid.data, NVME_NIDL_UUID);
4680 memcpy(pos, &uuid, sizeof(uuid));
4681 pos += sizeof(uuid);
4683 if (ns->params.eui64) {
4684 eui64.hdr.nidt = NVME_NIDT_EUI64;
4685 eui64.hdr.nidl = NVME_NIDL_EUI64;
4686 eui64.v = cpu_to_be64(ns->params.eui64);
4687 memcpy(pos, &eui64, sizeof(eui64));
4688 pos += sizeof(eui64);
4691 csi.hdr.nidt = NVME_NIDT_CSI;
4692 csi.hdr.nidl = NVME_NIDL_CSI;
4693 csi.v = ns->csi;
4694 memcpy(pos, &csi, sizeof(csi));
4695 pos += sizeof(csi);
4697 return nvme_c2h(n, list, sizeof(list), req);
4700 static uint16_t nvme_identify_cmd_set(NvmeCtrl *n, NvmeRequest *req)
4702 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
4703 static const int data_len = sizeof(list);
4705 trace_pci_nvme_identify_cmd_set();
4707 NVME_SET_CSI(*list, NVME_CSI_NVM);
4708 NVME_SET_CSI(*list, NVME_CSI_ZONED);
4710 return nvme_c2h(n, list, data_len, req);
4713 static uint16_t nvme_identify(NvmeCtrl *n, NvmeRequest *req)
4715 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
4717 trace_pci_nvme_identify(nvme_cid(req), c->cns, le16_to_cpu(c->ctrlid),
4718 c->csi);
4720 switch (c->cns) {
4721 case NVME_ID_CNS_NS:
4722 return nvme_identify_ns(n, req, true);
4723 case NVME_ID_CNS_NS_PRESENT:
4724 return nvme_identify_ns(n, req, false);
4725 case NVME_ID_CNS_NS_ATTACHED_CTRL_LIST:
4726 return nvme_identify_ctrl_list(n, req, true);
4727 case NVME_ID_CNS_CTRL_LIST:
4728 return nvme_identify_ctrl_list(n, req, false);
4729 case NVME_ID_CNS_CS_NS:
4730 return nvme_identify_ns_csi(n, req, true);
4731 case NVME_ID_CNS_CS_NS_PRESENT:
4732 return nvme_identify_ns_csi(n, req, false);
4733 case NVME_ID_CNS_CTRL:
4734 return nvme_identify_ctrl(n, req);
4735 case NVME_ID_CNS_CS_CTRL:
4736 return nvme_identify_ctrl_csi(n, req);
4737 case NVME_ID_CNS_NS_ACTIVE_LIST:
4738 return nvme_identify_nslist(n, req, true);
4739 case NVME_ID_CNS_NS_PRESENT_LIST:
4740 return nvme_identify_nslist(n, req, false);
4741 case NVME_ID_CNS_CS_NS_ACTIVE_LIST:
4742 return nvme_identify_nslist_csi(n, req, true);
4743 case NVME_ID_CNS_CS_NS_PRESENT_LIST:
4744 return nvme_identify_nslist_csi(n, req, false);
4745 case NVME_ID_CNS_NS_DESCR_LIST:
4746 return nvme_identify_ns_descr_list(n, req);
4747 case NVME_ID_CNS_IO_COMMAND_SET:
4748 return nvme_identify_cmd_set(n, req);
4749 default:
4750 trace_pci_nvme_err_invalid_identify_cns(le32_to_cpu(c->cns));
4751 return NVME_INVALID_FIELD | NVME_DNR;
4755 static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
4757 uint16_t sqid = le32_to_cpu(req->cmd.cdw10) & 0xffff;
4759 req->cqe.result = 1;
4760 if (nvme_check_sqid(n, sqid)) {
4761 return NVME_INVALID_FIELD | NVME_DNR;
4764 return NVME_SUCCESS;
4767 static inline void nvme_set_timestamp(NvmeCtrl *n, uint64_t ts)
4769 trace_pci_nvme_setfeat_timestamp(ts);
4771 n->host_timestamp = le64_to_cpu(ts);
4772 n->timestamp_set_qemu_clock_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
4775 static inline uint64_t nvme_get_timestamp(const NvmeCtrl *n)
4777 uint64_t current_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
4778 uint64_t elapsed_time = current_time - n->timestamp_set_qemu_clock_ms;
4780 union nvme_timestamp {
4781 struct {
4782 uint64_t timestamp:48;
4783 uint64_t sync:1;
4784 uint64_t origin:3;
4785 uint64_t rsvd1:12;
4787 uint64_t all;
4790 union nvme_timestamp ts;
4791 ts.all = 0;
4792 ts.timestamp = n->host_timestamp + elapsed_time;
4794 /* If the host timestamp is non-zero, set the timestamp origin */
4795 ts.origin = n->host_timestamp ? 0x01 : 0x00;
4797 trace_pci_nvme_getfeat_timestamp(ts.all);
4799 return cpu_to_le64(ts.all);
4802 static uint16_t nvme_get_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
4804 uint64_t timestamp = nvme_get_timestamp(n);
4806 return nvme_c2h(n, (uint8_t *)&timestamp, sizeof(timestamp), req);
4809 static uint16_t nvme_get_feature(NvmeCtrl *n, NvmeRequest *req)
4811 NvmeCmd *cmd = &req->cmd;
4812 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
4813 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
4814 uint32_t nsid = le32_to_cpu(cmd->nsid);
4815 uint32_t result;
4816 uint8_t fid = NVME_GETSETFEAT_FID(dw10);
4817 NvmeGetFeatureSelect sel = NVME_GETFEAT_SELECT(dw10);
4818 uint16_t iv;
4819 NvmeNamespace *ns;
4820 int i;
4822 static const uint32_t nvme_feature_default[NVME_FID_MAX] = {
4823 [NVME_ARBITRATION] = NVME_ARB_AB_NOLIMIT,
4826 trace_pci_nvme_getfeat(nvme_cid(req), nsid, fid, sel, dw11);
4828 if (!nvme_feature_support[fid]) {
4829 return NVME_INVALID_FIELD | NVME_DNR;
4832 if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
4833 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
4835 * The Reservation Notification Mask and Reservation Persistence
4836 * features require a status code of Invalid Field in Command when
4837 * NSID is FFFFFFFFh. Since the device does not support those
4838 * features we can always return Invalid Namespace or Format as we
4839 * should do for all other features.
4841 return NVME_INVALID_NSID | NVME_DNR;
4844 if (!nvme_ns(n, nsid)) {
4845 return NVME_INVALID_FIELD | NVME_DNR;
4849 switch (sel) {
4850 case NVME_GETFEAT_SELECT_CURRENT:
4851 break;
4852 case NVME_GETFEAT_SELECT_SAVED:
4853 /* no features are saveable by the controller; fallthrough */
4854 case NVME_GETFEAT_SELECT_DEFAULT:
4855 goto defaults;
4856 case NVME_GETFEAT_SELECT_CAP:
4857 result = nvme_feature_cap[fid];
4858 goto out;
4861 switch (fid) {
4862 case NVME_TEMPERATURE_THRESHOLD:
4863 result = 0;
4866 * The controller only implements the Composite Temperature sensor, so
4867 * return 0 for all other sensors.
4869 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
4870 goto out;
4873 switch (NVME_TEMP_THSEL(dw11)) {
4874 case NVME_TEMP_THSEL_OVER:
4875 result = n->features.temp_thresh_hi;
4876 goto out;
4877 case NVME_TEMP_THSEL_UNDER:
4878 result = n->features.temp_thresh_low;
4879 goto out;
4882 return NVME_INVALID_FIELD | NVME_DNR;
4883 case NVME_ERROR_RECOVERY:
4884 if (!nvme_nsid_valid(n, nsid)) {
4885 return NVME_INVALID_NSID | NVME_DNR;
4888 ns = nvme_ns(n, nsid);
4889 if (unlikely(!ns)) {
4890 return NVME_INVALID_FIELD | NVME_DNR;
4893 result = ns->features.err_rec;
4894 goto out;
4895 case NVME_VOLATILE_WRITE_CACHE:
4896 result = 0;
4897 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4898 ns = nvme_ns(n, i);
4899 if (!ns) {
4900 continue;
4903 result = blk_enable_write_cache(ns->blkconf.blk);
4904 if (result) {
4905 break;
4908 trace_pci_nvme_getfeat_vwcache(result ? "enabled" : "disabled");
4909 goto out;
4910 case NVME_ASYNCHRONOUS_EVENT_CONF:
4911 result = n->features.async_config;
4912 goto out;
4913 case NVME_TIMESTAMP:
4914 return nvme_get_feature_timestamp(n, req);
4915 default:
4916 break;
4919 defaults:
4920 switch (fid) {
4921 case NVME_TEMPERATURE_THRESHOLD:
4922 result = 0;
4924 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
4925 break;
4928 if (NVME_TEMP_THSEL(dw11) == NVME_TEMP_THSEL_OVER) {
4929 result = NVME_TEMPERATURE_WARNING;
4932 break;
4933 case NVME_NUMBER_OF_QUEUES:
4934 result = (n->params.max_ioqpairs - 1) |
4935 ((n->params.max_ioqpairs - 1) << 16);
4936 trace_pci_nvme_getfeat_numq(result);
4937 break;
4938 case NVME_INTERRUPT_VECTOR_CONF:
4939 iv = dw11 & 0xffff;
4940 if (iv >= n->params.max_ioqpairs + 1) {
4941 return NVME_INVALID_FIELD | NVME_DNR;
4944 result = iv;
4945 if (iv == n->admin_cq.vector) {
4946 result |= NVME_INTVC_NOCOALESCING;
4948 break;
4949 default:
4950 result = nvme_feature_default[fid];
4951 break;
4954 out:
4955 req->cqe.result = cpu_to_le32(result);
4956 return NVME_SUCCESS;
4959 static uint16_t nvme_set_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
4961 uint16_t ret;
4962 uint64_t timestamp;
4964 ret = nvme_h2c(n, (uint8_t *)&timestamp, sizeof(timestamp), req);
4965 if (ret) {
4966 return ret;
4969 nvme_set_timestamp(n, timestamp);
4971 return NVME_SUCCESS;
4974 static uint16_t nvme_set_feature(NvmeCtrl *n, NvmeRequest *req)
4976 NvmeNamespace *ns = NULL;
4978 NvmeCmd *cmd = &req->cmd;
4979 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
4980 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
4981 uint32_t nsid = le32_to_cpu(cmd->nsid);
4982 uint8_t fid = NVME_GETSETFEAT_FID(dw10);
4983 uint8_t save = NVME_SETFEAT_SAVE(dw10);
4984 int i;
4986 trace_pci_nvme_setfeat(nvme_cid(req), nsid, fid, save, dw11);
4988 if (save && !(nvme_feature_cap[fid] & NVME_FEAT_CAP_SAVE)) {
4989 return NVME_FID_NOT_SAVEABLE | NVME_DNR;
4992 if (!nvme_feature_support[fid]) {
4993 return NVME_INVALID_FIELD | NVME_DNR;
4996 if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
4997 if (nsid != NVME_NSID_BROADCAST) {
4998 if (!nvme_nsid_valid(n, nsid)) {
4999 return NVME_INVALID_NSID | NVME_DNR;
5002 ns = nvme_ns(n, nsid);
5003 if (unlikely(!ns)) {
5004 return NVME_INVALID_FIELD | NVME_DNR;
5007 } else if (nsid && nsid != NVME_NSID_BROADCAST) {
5008 if (!nvme_nsid_valid(n, nsid)) {
5009 return NVME_INVALID_NSID | NVME_DNR;
5012 return NVME_FEAT_NOT_NS_SPEC | NVME_DNR;
5015 if (!(nvme_feature_cap[fid] & NVME_FEAT_CAP_CHANGE)) {
5016 return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
5019 switch (fid) {
5020 case NVME_TEMPERATURE_THRESHOLD:
5021 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
5022 break;
5025 switch (NVME_TEMP_THSEL(dw11)) {
5026 case NVME_TEMP_THSEL_OVER:
5027 n->features.temp_thresh_hi = NVME_TEMP_TMPTH(dw11);
5028 break;
5029 case NVME_TEMP_THSEL_UNDER:
5030 n->features.temp_thresh_low = NVME_TEMP_TMPTH(dw11);
5031 break;
5032 default:
5033 return NVME_INVALID_FIELD | NVME_DNR;
5036 if ((n->temperature >= n->features.temp_thresh_hi) ||
5037 (n->temperature <= n->features.temp_thresh_low)) {
5038 nvme_smart_event(n, NVME_AER_INFO_SMART_TEMP_THRESH);
5041 break;
5042 case NVME_ERROR_RECOVERY:
5043 if (nsid == NVME_NSID_BROADCAST) {
5044 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5045 ns = nvme_ns(n, i);
5047 if (!ns) {
5048 continue;
5051 if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat)) {
5052 ns->features.err_rec = dw11;
5056 break;
5059 assert(ns);
5060 if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat)) {
5061 ns->features.err_rec = dw11;
5063 break;
5064 case NVME_VOLATILE_WRITE_CACHE:
5065 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5066 ns = nvme_ns(n, i);
5067 if (!ns) {
5068 continue;
5071 if (!(dw11 & 0x1) && blk_enable_write_cache(ns->blkconf.blk)) {
5072 blk_flush(ns->blkconf.blk);
5075 blk_set_enable_write_cache(ns->blkconf.blk, dw11 & 1);
5078 break;
5080 case NVME_NUMBER_OF_QUEUES:
5081 if (n->qs_created) {
5082 return NVME_CMD_SEQ_ERROR | NVME_DNR;
5086 * NVMe v1.3, Section 5.21.1.7: FFFFh is not an allowed value for NCQR
5087 * and NSQR.
5089 if ((dw11 & 0xffff) == 0xffff || ((dw11 >> 16) & 0xffff) == 0xffff) {
5090 return NVME_INVALID_FIELD | NVME_DNR;
5093 trace_pci_nvme_setfeat_numq((dw11 & 0xffff) + 1,
5094 ((dw11 >> 16) & 0xffff) + 1,
5095 n->params.max_ioqpairs,
5096 n->params.max_ioqpairs);
5097 req->cqe.result = cpu_to_le32((n->params.max_ioqpairs - 1) |
5098 ((n->params.max_ioqpairs - 1) << 16));
5099 break;
5100 case NVME_ASYNCHRONOUS_EVENT_CONF:
5101 n->features.async_config = dw11;
5102 break;
5103 case NVME_TIMESTAMP:
5104 return nvme_set_feature_timestamp(n, req);
5105 case NVME_COMMAND_SET_PROFILE:
5106 if (dw11 & 0x1ff) {
5107 trace_pci_nvme_err_invalid_iocsci(dw11 & 0x1ff);
5108 return NVME_CMD_SET_CMB_REJECTED | NVME_DNR;
5110 break;
5111 default:
5112 return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
5114 return NVME_SUCCESS;
5117 static uint16_t nvme_aer(NvmeCtrl *n, NvmeRequest *req)
5119 trace_pci_nvme_aer(nvme_cid(req));
5121 if (n->outstanding_aers > n->params.aerl) {
5122 trace_pci_nvme_aer_aerl_exceeded();
5123 return NVME_AER_LIMIT_EXCEEDED;
5126 n->aer_reqs[n->outstanding_aers] = req;
5127 n->outstanding_aers++;
5129 if (!QTAILQ_EMPTY(&n->aer_queue)) {
5130 nvme_process_aers(n);
5133 return NVME_NO_COMPLETE;
5136 static void nvme_update_dmrsl(NvmeCtrl *n)
5138 int nsid;
5140 for (nsid = 1; nsid <= NVME_MAX_NAMESPACES; nsid++) {
5141 NvmeNamespace *ns = nvme_ns(n, nsid);
5142 if (!ns) {
5143 continue;
5146 n->dmrsl = MIN_NON_ZERO(n->dmrsl,
5147 BDRV_REQUEST_MAX_BYTES / nvme_l2b(ns, 1));
5151 static void nvme_select_iocs_ns(NvmeCtrl *n, NvmeNamespace *ns)
5153 ns->iocs = nvme_cse_iocs_none;
5154 switch (ns->csi) {
5155 case NVME_CSI_NVM:
5156 if (NVME_CC_CSS(n->bar.cc) != NVME_CC_CSS_ADMIN_ONLY) {
5157 ns->iocs = nvme_cse_iocs_nvm;
5159 break;
5160 case NVME_CSI_ZONED:
5161 if (NVME_CC_CSS(n->bar.cc) == NVME_CC_CSS_CSI) {
5162 ns->iocs = nvme_cse_iocs_zoned;
5163 } else if (NVME_CC_CSS(n->bar.cc) == NVME_CC_CSS_NVM) {
5164 ns->iocs = nvme_cse_iocs_nvm;
5166 break;
5170 static uint16_t nvme_ns_attachment(NvmeCtrl *n, NvmeRequest *req)
5172 NvmeNamespace *ns;
5173 NvmeCtrl *ctrl;
5174 uint16_t list[NVME_CONTROLLER_LIST_SIZE] = {};
5175 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
5176 uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
5177 bool attach = !(dw10 & 0xf);
5178 uint16_t *nr_ids = &list[0];
5179 uint16_t *ids = &list[1];
5180 uint16_t ret;
5181 int i;
5183 trace_pci_nvme_ns_attachment(nvme_cid(req), dw10 & 0xf);
5185 if (!nvme_nsid_valid(n, nsid)) {
5186 return NVME_INVALID_NSID | NVME_DNR;
5189 ns = nvme_subsys_ns(n->subsys, nsid);
5190 if (!ns) {
5191 return NVME_INVALID_FIELD | NVME_DNR;
5194 ret = nvme_h2c(n, (uint8_t *)list, 4096, req);
5195 if (ret) {
5196 return ret;
5199 if (!*nr_ids) {
5200 return NVME_NS_CTRL_LIST_INVALID | NVME_DNR;
5203 *nr_ids = MIN(*nr_ids, NVME_CONTROLLER_LIST_SIZE - 1);
5204 for (i = 0; i < *nr_ids; i++) {
5205 ctrl = nvme_subsys_ctrl(n->subsys, ids[i]);
5206 if (!ctrl) {
5207 return NVME_NS_CTRL_LIST_INVALID | NVME_DNR;
5210 if (attach) {
5211 if (nvme_ns(ctrl, nsid)) {
5212 return NVME_NS_ALREADY_ATTACHED | NVME_DNR;
5215 if (ns->attached && !ns->params.shared) {
5216 return NVME_NS_PRIVATE | NVME_DNR;
5219 nvme_attach_ns(ctrl, ns);
5220 nvme_select_iocs_ns(ctrl, ns);
5221 } else {
5222 if (!nvme_ns(ctrl, nsid)) {
5223 return NVME_NS_NOT_ATTACHED | NVME_DNR;
5226 ctrl->namespaces[nsid] = NULL;
5227 ns->attached--;
5229 nvme_update_dmrsl(ctrl);
5233 * Add namespace id to the changed namespace id list for event clearing
5234 * via Get Log Page command.
5236 if (!test_and_set_bit(nsid, ctrl->changed_nsids)) {
5237 nvme_enqueue_event(ctrl, NVME_AER_TYPE_NOTICE,
5238 NVME_AER_INFO_NOTICE_NS_ATTR_CHANGED,
5239 NVME_LOG_CHANGED_NSLIST);
5243 return NVME_SUCCESS;
5246 typedef struct NvmeFormatAIOCB {
5247 BlockAIOCB common;
5248 BlockAIOCB *aiocb;
5249 QEMUBH *bh;
5250 NvmeRequest *req;
5251 int ret;
5253 NvmeNamespace *ns;
5254 uint32_t nsid;
5255 bool broadcast;
5256 int64_t offset;
5257 } NvmeFormatAIOCB;
5259 static void nvme_format_bh(void *opaque);
5261 static void nvme_format_cancel(BlockAIOCB *aiocb)
5263 NvmeFormatAIOCB *iocb = container_of(aiocb, NvmeFormatAIOCB, common);
5265 if (iocb->aiocb) {
5266 blk_aio_cancel_async(iocb->aiocb);
5270 static const AIOCBInfo nvme_format_aiocb_info = {
5271 .aiocb_size = sizeof(NvmeFormatAIOCB),
5272 .cancel_async = nvme_format_cancel,
5273 .get_aio_context = nvme_get_aio_context,
5276 static void nvme_format_set(NvmeNamespace *ns, NvmeCmd *cmd)
5278 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
5279 uint8_t lbaf = dw10 & 0xf;
5280 uint8_t pi = (dw10 >> 5) & 0x7;
5281 uint8_t mset = (dw10 >> 4) & 0x1;
5282 uint8_t pil = (dw10 >> 8) & 0x1;
5284 trace_pci_nvme_format_set(ns->params.nsid, lbaf, mset, pi, pil);
5286 ns->id_ns.dps = (pil << 3) | pi;
5287 ns->id_ns.flbas = lbaf | (mset << 4);
5289 nvme_ns_init_format(ns);
5292 static void nvme_format_ns_cb(void *opaque, int ret)
5294 NvmeFormatAIOCB *iocb = opaque;
5295 NvmeRequest *req = iocb->req;
5296 NvmeNamespace *ns = iocb->ns;
5297 int bytes;
5299 if (ret < 0) {
5300 iocb->ret = ret;
5301 goto done;
5304 assert(ns);
5306 if (iocb->offset < ns->size) {
5307 bytes = MIN(BDRV_REQUEST_MAX_BYTES, ns->size - iocb->offset);
5309 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, iocb->offset,
5310 bytes, BDRV_REQ_MAY_UNMAP,
5311 nvme_format_ns_cb, iocb);
5313 iocb->offset += bytes;
5314 return;
5317 nvme_format_set(ns, &req->cmd);
5318 ns->status = 0x0;
5319 iocb->ns = NULL;
5320 iocb->offset = 0;
5322 done:
5323 iocb->aiocb = NULL;
5324 qemu_bh_schedule(iocb->bh);
5327 static uint16_t nvme_format_check(NvmeNamespace *ns, uint8_t lbaf, uint8_t pi)
5329 if (ns->params.zoned) {
5330 return NVME_INVALID_FORMAT | NVME_DNR;
5333 if (lbaf > ns->id_ns.nlbaf) {
5334 return NVME_INVALID_FORMAT | NVME_DNR;
5337 if (pi && (ns->id_ns.lbaf[lbaf].ms < sizeof(NvmeDifTuple))) {
5338 return NVME_INVALID_FORMAT | NVME_DNR;
5341 if (pi && pi > NVME_ID_NS_DPS_TYPE_3) {
5342 return NVME_INVALID_FIELD | NVME_DNR;
5345 return NVME_SUCCESS;
5348 static void nvme_format_bh(void *opaque)
5350 NvmeFormatAIOCB *iocb = opaque;
5351 NvmeRequest *req = iocb->req;
5352 NvmeCtrl *n = nvme_ctrl(req);
5353 uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
5354 uint8_t lbaf = dw10 & 0xf;
5355 uint8_t pi = (dw10 >> 5) & 0x7;
5356 uint16_t status;
5357 int i;
5359 if (iocb->ret < 0) {
5360 goto done;
5363 if (iocb->broadcast) {
5364 for (i = iocb->nsid + 1; i <= NVME_MAX_NAMESPACES; i++) {
5365 iocb->ns = nvme_ns(n, i);
5366 if (iocb->ns) {
5367 iocb->nsid = i;
5368 break;
5373 if (!iocb->ns) {
5374 goto done;
5377 status = nvme_format_check(iocb->ns, lbaf, pi);
5378 if (status) {
5379 req->status = status;
5380 goto done;
5383 iocb->ns->status = NVME_FORMAT_IN_PROGRESS;
5384 nvme_format_ns_cb(iocb, 0);
5385 return;
5387 done:
5388 qemu_bh_delete(iocb->bh);
5389 iocb->bh = NULL;
5391 iocb->common.cb(iocb->common.opaque, iocb->ret);
5393 qemu_aio_unref(iocb);
5396 static uint16_t nvme_format(NvmeCtrl *n, NvmeRequest *req)
5398 NvmeFormatAIOCB *iocb;
5399 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
5400 uint16_t status;
5402 iocb = qemu_aio_get(&nvme_format_aiocb_info, NULL, nvme_misc_cb, req);
5404 iocb->req = req;
5405 iocb->bh = qemu_bh_new(nvme_format_bh, iocb);
5406 iocb->ret = 0;
5407 iocb->ns = NULL;
5408 iocb->nsid = 0;
5409 iocb->broadcast = (nsid == NVME_NSID_BROADCAST);
5410 iocb->offset = 0;
5412 if (!iocb->broadcast) {
5413 if (!nvme_nsid_valid(n, nsid)) {
5414 status = NVME_INVALID_NSID | NVME_DNR;
5415 goto out;
5418 iocb->ns = nvme_ns(n, nsid);
5419 if (!iocb->ns) {
5420 status = NVME_INVALID_FIELD | NVME_DNR;
5421 goto out;
5425 req->aiocb = &iocb->common;
5426 qemu_bh_schedule(iocb->bh);
5428 return NVME_NO_COMPLETE;
5430 out:
5431 qemu_bh_delete(iocb->bh);
5432 iocb->bh = NULL;
5433 qemu_aio_unref(iocb);
5434 return status;
5437 static uint16_t nvme_admin_cmd(NvmeCtrl *n, NvmeRequest *req)
5439 trace_pci_nvme_admin_cmd(nvme_cid(req), nvme_sqid(req), req->cmd.opcode,
5440 nvme_adm_opc_str(req->cmd.opcode));
5442 if (!(nvme_cse_acs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
5443 trace_pci_nvme_err_invalid_admin_opc(req->cmd.opcode);
5444 return NVME_INVALID_OPCODE | NVME_DNR;
5447 /* SGLs shall not be used for Admin commands in NVMe over PCIe */
5448 if (NVME_CMD_FLAGS_PSDT(req->cmd.flags) != NVME_PSDT_PRP) {
5449 return NVME_INVALID_FIELD | NVME_DNR;
5452 switch (req->cmd.opcode) {
5453 case NVME_ADM_CMD_DELETE_SQ:
5454 return nvme_del_sq(n, req);
5455 case NVME_ADM_CMD_CREATE_SQ:
5456 return nvme_create_sq(n, req);
5457 case NVME_ADM_CMD_GET_LOG_PAGE:
5458 return nvme_get_log(n, req);
5459 case NVME_ADM_CMD_DELETE_CQ:
5460 return nvme_del_cq(n, req);
5461 case NVME_ADM_CMD_CREATE_CQ:
5462 return nvme_create_cq(n, req);
5463 case NVME_ADM_CMD_IDENTIFY:
5464 return nvme_identify(n, req);
5465 case NVME_ADM_CMD_ABORT:
5466 return nvme_abort(n, req);
5467 case NVME_ADM_CMD_SET_FEATURES:
5468 return nvme_set_feature(n, req);
5469 case NVME_ADM_CMD_GET_FEATURES:
5470 return nvme_get_feature(n, req);
5471 case NVME_ADM_CMD_ASYNC_EV_REQ:
5472 return nvme_aer(n, req);
5473 case NVME_ADM_CMD_NS_ATTACHMENT:
5474 return nvme_ns_attachment(n, req);
5475 case NVME_ADM_CMD_FORMAT_NVM:
5476 return nvme_format(n, req);
5477 default:
5478 assert(false);
5481 return NVME_INVALID_OPCODE | NVME_DNR;
5484 static void nvme_process_sq(void *opaque)
5486 NvmeSQueue *sq = opaque;
5487 NvmeCtrl *n = sq->ctrl;
5488 NvmeCQueue *cq = n->cq[sq->cqid];
5490 uint16_t status;
5491 hwaddr addr;
5492 NvmeCmd cmd;
5493 NvmeRequest *req;
5495 while (!(nvme_sq_empty(sq) || QTAILQ_EMPTY(&sq->req_list))) {
5496 addr = sq->dma_addr + sq->head * n->sqe_size;
5497 if (nvme_addr_read(n, addr, (void *)&cmd, sizeof(cmd))) {
5498 trace_pci_nvme_err_addr_read(addr);
5499 trace_pci_nvme_err_cfs();
5500 n->bar.csts = NVME_CSTS_FAILED;
5501 break;
5503 nvme_inc_sq_head(sq);
5505 req = QTAILQ_FIRST(&sq->req_list);
5506 QTAILQ_REMOVE(&sq->req_list, req, entry);
5507 QTAILQ_INSERT_TAIL(&sq->out_req_list, req, entry);
5508 nvme_req_clear(req);
5509 req->cqe.cid = cmd.cid;
5510 memcpy(&req->cmd, &cmd, sizeof(NvmeCmd));
5512 status = sq->sqid ? nvme_io_cmd(n, req) :
5513 nvme_admin_cmd(n, req);
5514 if (status != NVME_NO_COMPLETE) {
5515 req->status = status;
5516 nvme_enqueue_req_completion(cq, req);
5521 static void nvme_ctrl_reset(NvmeCtrl *n)
5523 NvmeNamespace *ns;
5524 int i;
5526 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5527 ns = nvme_ns(n, i);
5528 if (!ns) {
5529 continue;
5532 nvme_ns_drain(ns);
5535 for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
5536 if (n->sq[i] != NULL) {
5537 nvme_free_sq(n->sq[i], n);
5540 for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
5541 if (n->cq[i] != NULL) {
5542 nvme_free_cq(n->cq[i], n);
5546 while (!QTAILQ_EMPTY(&n->aer_queue)) {
5547 NvmeAsyncEvent *event = QTAILQ_FIRST(&n->aer_queue);
5548 QTAILQ_REMOVE(&n->aer_queue, event, entry);
5549 g_free(event);
5552 n->aer_queued = 0;
5553 n->outstanding_aers = 0;
5554 n->qs_created = false;
5556 n->bar.cc = 0;
5559 static void nvme_ctrl_shutdown(NvmeCtrl *n)
5561 NvmeNamespace *ns;
5562 int i;
5564 if (n->pmr.dev) {
5565 memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
5568 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5569 ns = nvme_ns(n, i);
5570 if (!ns) {
5571 continue;
5574 nvme_ns_shutdown(ns);
5578 static void nvme_select_iocs(NvmeCtrl *n)
5580 NvmeNamespace *ns;
5581 int i;
5583 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5584 ns = nvme_ns(n, i);
5585 if (!ns) {
5586 continue;
5589 nvme_select_iocs_ns(n, ns);
5593 static int nvme_start_ctrl(NvmeCtrl *n)
5595 uint32_t page_bits = NVME_CC_MPS(n->bar.cc) + 12;
5596 uint32_t page_size = 1 << page_bits;
5598 if (unlikely(n->cq[0])) {
5599 trace_pci_nvme_err_startfail_cq();
5600 return -1;
5602 if (unlikely(n->sq[0])) {
5603 trace_pci_nvme_err_startfail_sq();
5604 return -1;
5606 if (unlikely(!n->bar.asq)) {
5607 trace_pci_nvme_err_startfail_nbarasq();
5608 return -1;
5610 if (unlikely(!n->bar.acq)) {
5611 trace_pci_nvme_err_startfail_nbaracq();
5612 return -1;
5614 if (unlikely(n->bar.asq & (page_size - 1))) {
5615 trace_pci_nvme_err_startfail_asq_misaligned(n->bar.asq);
5616 return -1;
5618 if (unlikely(n->bar.acq & (page_size - 1))) {
5619 trace_pci_nvme_err_startfail_acq_misaligned(n->bar.acq);
5620 return -1;
5622 if (unlikely(!(NVME_CAP_CSS(n->bar.cap) & (1 << NVME_CC_CSS(n->bar.cc))))) {
5623 trace_pci_nvme_err_startfail_css(NVME_CC_CSS(n->bar.cc));
5624 return -1;
5626 if (unlikely(NVME_CC_MPS(n->bar.cc) <
5627 NVME_CAP_MPSMIN(n->bar.cap))) {
5628 trace_pci_nvme_err_startfail_page_too_small(
5629 NVME_CC_MPS(n->bar.cc),
5630 NVME_CAP_MPSMIN(n->bar.cap));
5631 return -1;
5633 if (unlikely(NVME_CC_MPS(n->bar.cc) >
5634 NVME_CAP_MPSMAX(n->bar.cap))) {
5635 trace_pci_nvme_err_startfail_page_too_large(
5636 NVME_CC_MPS(n->bar.cc),
5637 NVME_CAP_MPSMAX(n->bar.cap));
5638 return -1;
5640 if (unlikely(NVME_CC_IOCQES(n->bar.cc) <
5641 NVME_CTRL_CQES_MIN(n->id_ctrl.cqes))) {
5642 trace_pci_nvme_err_startfail_cqent_too_small(
5643 NVME_CC_IOCQES(n->bar.cc),
5644 NVME_CTRL_CQES_MIN(n->bar.cap));
5645 return -1;
5647 if (unlikely(NVME_CC_IOCQES(n->bar.cc) >
5648 NVME_CTRL_CQES_MAX(n->id_ctrl.cqes))) {
5649 trace_pci_nvme_err_startfail_cqent_too_large(
5650 NVME_CC_IOCQES(n->bar.cc),
5651 NVME_CTRL_CQES_MAX(n->bar.cap));
5652 return -1;
5654 if (unlikely(NVME_CC_IOSQES(n->bar.cc) <
5655 NVME_CTRL_SQES_MIN(n->id_ctrl.sqes))) {
5656 trace_pci_nvme_err_startfail_sqent_too_small(
5657 NVME_CC_IOSQES(n->bar.cc),
5658 NVME_CTRL_SQES_MIN(n->bar.cap));
5659 return -1;
5661 if (unlikely(NVME_CC_IOSQES(n->bar.cc) >
5662 NVME_CTRL_SQES_MAX(n->id_ctrl.sqes))) {
5663 trace_pci_nvme_err_startfail_sqent_too_large(
5664 NVME_CC_IOSQES(n->bar.cc),
5665 NVME_CTRL_SQES_MAX(n->bar.cap));
5666 return -1;
5668 if (unlikely(!NVME_AQA_ASQS(n->bar.aqa))) {
5669 trace_pci_nvme_err_startfail_asqent_sz_zero();
5670 return -1;
5672 if (unlikely(!NVME_AQA_ACQS(n->bar.aqa))) {
5673 trace_pci_nvme_err_startfail_acqent_sz_zero();
5674 return -1;
5677 n->page_bits = page_bits;
5678 n->page_size = page_size;
5679 n->max_prp_ents = n->page_size / sizeof(uint64_t);
5680 n->cqe_size = 1 << NVME_CC_IOCQES(n->bar.cc);
5681 n->sqe_size = 1 << NVME_CC_IOSQES(n->bar.cc);
5682 nvme_init_cq(&n->admin_cq, n, n->bar.acq, 0, 0,
5683 NVME_AQA_ACQS(n->bar.aqa) + 1, 1);
5684 nvme_init_sq(&n->admin_sq, n, n->bar.asq, 0, 0,
5685 NVME_AQA_ASQS(n->bar.aqa) + 1);
5687 nvme_set_timestamp(n, 0ULL);
5689 QTAILQ_INIT(&n->aer_queue);
5691 nvme_select_iocs(n);
5693 return 0;
5696 static void nvme_cmb_enable_regs(NvmeCtrl *n)
5698 NVME_CMBLOC_SET_CDPCILS(n->bar.cmbloc, 1);
5699 NVME_CMBLOC_SET_CDPMLS(n->bar.cmbloc, 1);
5700 NVME_CMBLOC_SET_BIR(n->bar.cmbloc, NVME_CMB_BIR);
5702 NVME_CMBSZ_SET_SQS(n->bar.cmbsz, 1);
5703 NVME_CMBSZ_SET_CQS(n->bar.cmbsz, 0);
5704 NVME_CMBSZ_SET_LISTS(n->bar.cmbsz, 1);
5705 NVME_CMBSZ_SET_RDS(n->bar.cmbsz, 1);
5706 NVME_CMBSZ_SET_WDS(n->bar.cmbsz, 1);
5707 NVME_CMBSZ_SET_SZU(n->bar.cmbsz, 2); /* MBs */
5708 NVME_CMBSZ_SET_SZ(n->bar.cmbsz, n->params.cmb_size_mb);
5711 static void nvme_write_bar(NvmeCtrl *n, hwaddr offset, uint64_t data,
5712 unsigned size)
5714 if (unlikely(offset & (sizeof(uint32_t) - 1))) {
5715 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_misaligned32,
5716 "MMIO write not 32-bit aligned,"
5717 " offset=0x%"PRIx64"", offset);
5718 /* should be ignored, fall through for now */
5721 if (unlikely(size < sizeof(uint32_t))) {
5722 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_toosmall,
5723 "MMIO write smaller than 32-bits,"
5724 " offset=0x%"PRIx64", size=%u",
5725 offset, size);
5726 /* should be ignored, fall through for now */
5729 switch (offset) {
5730 case 0xc: /* INTMS */
5731 if (unlikely(msix_enabled(&(n->parent_obj)))) {
5732 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
5733 "undefined access to interrupt mask set"
5734 " when MSI-X is enabled");
5735 /* should be ignored, fall through for now */
5737 n->bar.intms |= data & 0xffffffff;
5738 n->bar.intmc = n->bar.intms;
5739 trace_pci_nvme_mmio_intm_set(data & 0xffffffff, n->bar.intmc);
5740 nvme_irq_check(n);
5741 break;
5742 case 0x10: /* INTMC */
5743 if (unlikely(msix_enabled(&(n->parent_obj)))) {
5744 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
5745 "undefined access to interrupt mask clr"
5746 " when MSI-X is enabled");
5747 /* should be ignored, fall through for now */
5749 n->bar.intms &= ~(data & 0xffffffff);
5750 n->bar.intmc = n->bar.intms;
5751 trace_pci_nvme_mmio_intm_clr(data & 0xffffffff, n->bar.intmc);
5752 nvme_irq_check(n);
5753 break;
5754 case 0x14: /* CC */
5755 trace_pci_nvme_mmio_cfg(data & 0xffffffff);
5756 /* Windows first sends data, then sends enable bit */
5757 if (!NVME_CC_EN(data) && !NVME_CC_EN(n->bar.cc) &&
5758 !NVME_CC_SHN(data) && !NVME_CC_SHN(n->bar.cc))
5760 n->bar.cc = data;
5763 if (NVME_CC_EN(data) && !NVME_CC_EN(n->bar.cc)) {
5764 n->bar.cc = data;
5765 if (unlikely(nvme_start_ctrl(n))) {
5766 trace_pci_nvme_err_startfail();
5767 n->bar.csts = NVME_CSTS_FAILED;
5768 } else {
5769 trace_pci_nvme_mmio_start_success();
5770 n->bar.csts = NVME_CSTS_READY;
5772 } else if (!NVME_CC_EN(data) && NVME_CC_EN(n->bar.cc)) {
5773 trace_pci_nvme_mmio_stopped();
5774 nvme_ctrl_reset(n);
5775 n->bar.csts &= ~NVME_CSTS_READY;
5777 if (NVME_CC_SHN(data) && !(NVME_CC_SHN(n->bar.cc))) {
5778 trace_pci_nvme_mmio_shutdown_set();
5779 nvme_ctrl_shutdown(n);
5780 n->bar.cc = data;
5781 n->bar.csts |= NVME_CSTS_SHST_COMPLETE;
5782 } else if (!NVME_CC_SHN(data) && NVME_CC_SHN(n->bar.cc)) {
5783 trace_pci_nvme_mmio_shutdown_cleared();
5784 n->bar.csts &= ~NVME_CSTS_SHST_COMPLETE;
5785 n->bar.cc = data;
5787 break;
5788 case 0x1c: /* CSTS */
5789 if (data & (1 << 4)) {
5790 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ssreset_w1c_unsupported,
5791 "attempted to W1C CSTS.NSSRO"
5792 " but CAP.NSSRS is zero (not supported)");
5793 } else if (data != 0) {
5794 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ro_csts,
5795 "attempted to set a read only bit"
5796 " of controller status");
5798 break;
5799 case 0x20: /* NSSR */
5800 if (data == 0x4e564d65) {
5801 trace_pci_nvme_ub_mmiowr_ssreset_unsupported();
5802 } else {
5803 /* The spec says that writes of other values have no effect */
5804 return;
5806 break;
5807 case 0x24: /* AQA */
5808 n->bar.aqa = data & 0xffffffff;
5809 trace_pci_nvme_mmio_aqattr(data & 0xffffffff);
5810 break;
5811 case 0x28: /* ASQ */
5812 n->bar.asq = size == 8 ? data :
5813 (n->bar.asq & ~0xffffffffULL) | (data & 0xffffffff);
5814 trace_pci_nvme_mmio_asqaddr(data);
5815 break;
5816 case 0x2c: /* ASQ hi */
5817 n->bar.asq = (n->bar.asq & 0xffffffff) | (data << 32);
5818 trace_pci_nvme_mmio_asqaddr_hi(data, n->bar.asq);
5819 break;
5820 case 0x30: /* ACQ */
5821 trace_pci_nvme_mmio_acqaddr(data);
5822 n->bar.acq = size == 8 ? data :
5823 (n->bar.acq & ~0xffffffffULL) | (data & 0xffffffff);
5824 break;
5825 case 0x34: /* ACQ hi */
5826 n->bar.acq = (n->bar.acq & 0xffffffff) | (data << 32);
5827 trace_pci_nvme_mmio_acqaddr_hi(data, n->bar.acq);
5828 break;
5829 case 0x38: /* CMBLOC */
5830 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbloc_reserved,
5831 "invalid write to reserved CMBLOC"
5832 " when CMBSZ is zero, ignored");
5833 return;
5834 case 0x3C: /* CMBSZ */
5835 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbsz_readonly,
5836 "invalid write to read only CMBSZ, ignored");
5837 return;
5838 case 0x50: /* CMBMSC */
5839 if (!NVME_CAP_CMBS(n->bar.cap)) {
5840 return;
5843 n->bar.cmbmsc = size == 8 ? data :
5844 (n->bar.cmbmsc & ~0xffffffff) | (data & 0xffffffff);
5845 n->cmb.cmse = false;
5847 if (NVME_CMBMSC_CRE(data)) {
5848 nvme_cmb_enable_regs(n);
5850 if (NVME_CMBMSC_CMSE(data)) {
5851 hwaddr cba = NVME_CMBMSC_CBA(data) << CMBMSC_CBA_SHIFT;
5852 if (cba + int128_get64(n->cmb.mem.size) < cba) {
5853 NVME_CMBSTS_SET_CBAI(n->bar.cmbsts, 1);
5854 return;
5857 n->cmb.cba = cba;
5858 n->cmb.cmse = true;
5860 } else {
5861 n->bar.cmbsz = 0;
5862 n->bar.cmbloc = 0;
5865 return;
5866 case 0x54: /* CMBMSC hi */
5867 n->bar.cmbmsc = (n->bar.cmbmsc & 0xffffffff) | (data << 32);
5868 return;
5870 case 0xe00: /* PMRCAP */
5871 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrcap_readonly,
5872 "invalid write to PMRCAP register, ignored");
5873 return;
5874 case 0xe04: /* PMRCTL */
5875 if (!NVME_CAP_PMRS(n->bar.cap)) {
5876 return;
5879 n->bar.pmrctl = data;
5880 if (NVME_PMRCTL_EN(data)) {
5881 memory_region_set_enabled(&n->pmr.dev->mr, true);
5882 n->bar.pmrsts = 0;
5883 } else {
5884 memory_region_set_enabled(&n->pmr.dev->mr, false);
5885 NVME_PMRSTS_SET_NRDY(n->bar.pmrsts, 1);
5886 n->pmr.cmse = false;
5888 return;
5889 case 0xe08: /* PMRSTS */
5890 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrsts_readonly,
5891 "invalid write to PMRSTS register, ignored");
5892 return;
5893 case 0xe0C: /* PMREBS */
5894 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrebs_readonly,
5895 "invalid write to PMREBS register, ignored");
5896 return;
5897 case 0xe10: /* PMRSWTP */
5898 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrswtp_readonly,
5899 "invalid write to PMRSWTP register, ignored");
5900 return;
5901 case 0xe14: /* PMRMSCL */
5902 if (!NVME_CAP_PMRS(n->bar.cap)) {
5903 return;
5906 n->bar.pmrmsc = (n->bar.pmrmsc & ~0xffffffff) | (data & 0xffffffff);
5907 n->pmr.cmse = false;
5909 if (NVME_PMRMSC_CMSE(n->bar.pmrmsc)) {
5910 hwaddr cba = NVME_PMRMSC_CBA(n->bar.pmrmsc) << PMRMSC_CBA_SHIFT;
5911 if (cba + int128_get64(n->pmr.dev->mr.size) < cba) {
5912 NVME_PMRSTS_SET_CBAI(n->bar.pmrsts, 1);
5913 return;
5916 n->pmr.cmse = true;
5917 n->pmr.cba = cba;
5920 return;
5921 case 0xe18: /* PMRMSCU */
5922 if (!NVME_CAP_PMRS(n->bar.cap)) {
5923 return;
5926 n->bar.pmrmsc = (n->bar.pmrmsc & 0xffffffff) | (data << 32);
5927 return;
5928 default:
5929 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_invalid,
5930 "invalid MMIO write,"
5931 " offset=0x%"PRIx64", data=%"PRIx64"",
5932 offset, data);
5933 break;
5937 static uint64_t nvme_mmio_read(void *opaque, hwaddr addr, unsigned size)
5939 NvmeCtrl *n = (NvmeCtrl *)opaque;
5940 uint8_t *ptr = (uint8_t *)&n->bar;
5941 uint64_t val = 0;
5943 trace_pci_nvme_mmio_read(addr, size);
5945 if (unlikely(addr & (sizeof(uint32_t) - 1))) {
5946 NVME_GUEST_ERR(pci_nvme_ub_mmiord_misaligned32,
5947 "MMIO read not 32-bit aligned,"
5948 " offset=0x%"PRIx64"", addr);
5949 /* should RAZ, fall through for now */
5950 } else if (unlikely(size < sizeof(uint32_t))) {
5951 NVME_GUEST_ERR(pci_nvme_ub_mmiord_toosmall,
5952 "MMIO read smaller than 32-bits,"
5953 " offset=0x%"PRIx64"", addr);
5954 /* should RAZ, fall through for now */
5957 if (addr < sizeof(n->bar)) {
5959 * When PMRWBM bit 1 is set then read from
5960 * from PMRSTS should ensure prior writes
5961 * made it to persistent media
5963 if (addr == 0xe08 &&
5964 (NVME_PMRCAP_PMRWBM(n->bar.pmrcap) & 0x02)) {
5965 memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
5967 memcpy(&val, ptr + addr, size);
5968 } else {
5969 NVME_GUEST_ERR(pci_nvme_ub_mmiord_invalid_ofs,
5970 "MMIO read beyond last register,"
5971 " offset=0x%"PRIx64", returning 0", addr);
5974 return val;
5977 static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)
5979 uint32_t qid;
5981 if (unlikely(addr & ((1 << 2) - 1))) {
5982 NVME_GUEST_ERR(pci_nvme_ub_db_wr_misaligned,
5983 "doorbell write not 32-bit aligned,"
5984 " offset=0x%"PRIx64", ignoring", addr);
5985 return;
5988 if (((addr - 0x1000) >> 2) & 1) {
5989 /* Completion queue doorbell write */
5991 uint16_t new_head = val & 0xffff;
5992 int start_sqs;
5993 NvmeCQueue *cq;
5995 qid = (addr - (0x1000 + (1 << 2))) >> 3;
5996 if (unlikely(nvme_check_cqid(n, qid))) {
5997 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cq,
5998 "completion queue doorbell write"
5999 " for nonexistent queue,"
6000 " sqid=%"PRIu32", ignoring", qid);
6003 * NVM Express v1.3d, Section 4.1 state: "If host software writes
6004 * an invalid value to the Submission Queue Tail Doorbell or
6005 * Completion Queue Head Doorbell regiter and an Asynchronous Event
6006 * Request command is outstanding, then an asynchronous event is
6007 * posted to the Admin Completion Queue with a status code of
6008 * Invalid Doorbell Write Value."
6010 * Also note that the spec includes the "Invalid Doorbell Register"
6011 * status code, but nowhere does it specify when to use it.
6012 * However, it seems reasonable to use it here in a similar
6013 * fashion.
6015 if (n->outstanding_aers) {
6016 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
6017 NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
6018 NVME_LOG_ERROR_INFO);
6021 return;
6024 cq = n->cq[qid];
6025 if (unlikely(new_head >= cq->size)) {
6026 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cqhead,
6027 "completion queue doorbell write value"
6028 " beyond queue size, sqid=%"PRIu32","
6029 " new_head=%"PRIu16", ignoring",
6030 qid, new_head);
6032 if (n->outstanding_aers) {
6033 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
6034 NVME_AER_INFO_ERR_INVALID_DB_VALUE,
6035 NVME_LOG_ERROR_INFO);
6038 return;
6041 trace_pci_nvme_mmio_doorbell_cq(cq->cqid, new_head);
6043 start_sqs = nvme_cq_full(cq) ? 1 : 0;
6044 cq->head = new_head;
6045 if (start_sqs) {
6046 NvmeSQueue *sq;
6047 QTAILQ_FOREACH(sq, &cq->sq_list, entry) {
6048 timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
6050 timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
6053 if (cq->tail == cq->head) {
6054 if (cq->irq_enabled) {
6055 n->cq_pending--;
6058 nvme_irq_deassert(n, cq);
6060 } else {
6061 /* Submission queue doorbell write */
6063 uint16_t new_tail = val & 0xffff;
6064 NvmeSQueue *sq;
6066 qid = (addr - 0x1000) >> 3;
6067 if (unlikely(nvme_check_sqid(n, qid))) {
6068 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sq,
6069 "submission queue doorbell write"
6070 " for nonexistent queue,"
6071 " sqid=%"PRIu32", ignoring", qid);
6073 if (n->outstanding_aers) {
6074 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
6075 NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
6076 NVME_LOG_ERROR_INFO);
6079 return;
6082 sq = n->sq[qid];
6083 if (unlikely(new_tail >= sq->size)) {
6084 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sqtail,
6085 "submission queue doorbell write value"
6086 " beyond queue size, sqid=%"PRIu32","
6087 " new_tail=%"PRIu16", ignoring",
6088 qid, new_tail);
6090 if (n->outstanding_aers) {
6091 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
6092 NVME_AER_INFO_ERR_INVALID_DB_VALUE,
6093 NVME_LOG_ERROR_INFO);
6096 return;
6099 trace_pci_nvme_mmio_doorbell_sq(sq->sqid, new_tail);
6101 sq->tail = new_tail;
6102 timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
6106 static void nvme_mmio_write(void *opaque, hwaddr addr, uint64_t data,
6107 unsigned size)
6109 NvmeCtrl *n = (NvmeCtrl *)opaque;
6111 trace_pci_nvme_mmio_write(addr, data, size);
6113 if (addr < sizeof(n->bar)) {
6114 nvme_write_bar(n, addr, data, size);
6115 } else {
6116 nvme_process_db(n, addr, data);
6120 static const MemoryRegionOps nvme_mmio_ops = {
6121 .read = nvme_mmio_read,
6122 .write = nvme_mmio_write,
6123 .endianness = DEVICE_LITTLE_ENDIAN,
6124 .impl = {
6125 .min_access_size = 2,
6126 .max_access_size = 8,
6130 static void nvme_cmb_write(void *opaque, hwaddr addr, uint64_t data,
6131 unsigned size)
6133 NvmeCtrl *n = (NvmeCtrl *)opaque;
6134 stn_le_p(&n->cmb.buf[addr], size, data);
6137 static uint64_t nvme_cmb_read(void *opaque, hwaddr addr, unsigned size)
6139 NvmeCtrl *n = (NvmeCtrl *)opaque;
6140 return ldn_le_p(&n->cmb.buf[addr], size);
6143 static const MemoryRegionOps nvme_cmb_ops = {
6144 .read = nvme_cmb_read,
6145 .write = nvme_cmb_write,
6146 .endianness = DEVICE_LITTLE_ENDIAN,
6147 .impl = {
6148 .min_access_size = 1,
6149 .max_access_size = 8,
6153 static void nvme_check_constraints(NvmeCtrl *n, Error **errp)
6155 NvmeParams *params = &n->params;
6157 if (params->num_queues) {
6158 warn_report("num_queues is deprecated; please use max_ioqpairs "
6159 "instead");
6161 params->max_ioqpairs = params->num_queues - 1;
6164 if (n->namespace.blkconf.blk && n->subsys) {
6165 error_setg(errp, "subsystem support is unavailable with legacy "
6166 "namespace ('drive' property)");
6167 return;
6170 if (params->max_ioqpairs < 1 ||
6171 params->max_ioqpairs > NVME_MAX_IOQPAIRS) {
6172 error_setg(errp, "max_ioqpairs must be between 1 and %d",
6173 NVME_MAX_IOQPAIRS);
6174 return;
6177 if (params->msix_qsize < 1 ||
6178 params->msix_qsize > PCI_MSIX_FLAGS_QSIZE + 1) {
6179 error_setg(errp, "msix_qsize must be between 1 and %d",
6180 PCI_MSIX_FLAGS_QSIZE + 1);
6181 return;
6184 if (!params->serial) {
6185 error_setg(errp, "serial property not set");
6186 return;
6189 if (n->pmr.dev) {
6190 if (host_memory_backend_is_mapped(n->pmr.dev)) {
6191 error_setg(errp, "can't use already busy memdev: %s",
6192 object_get_canonical_path_component(OBJECT(n->pmr.dev)));
6193 return;
6196 if (!is_power_of_2(n->pmr.dev->size)) {
6197 error_setg(errp, "pmr backend size needs to be power of 2 in size");
6198 return;
6201 host_memory_backend_set_mapped(n->pmr.dev, true);
6204 if (n->params.zasl > n->params.mdts) {
6205 error_setg(errp, "zoned.zasl (Zone Append Size Limit) must be less "
6206 "than or equal to mdts (Maximum Data Transfer Size)");
6207 return;
6210 if (!n->params.vsl) {
6211 error_setg(errp, "vsl must be non-zero");
6212 return;
6216 static void nvme_init_state(NvmeCtrl *n)
6218 /* add one to max_ioqpairs to account for the admin queue pair */
6219 n->reg_size = pow2ceil(sizeof(NvmeBar) +
6220 2 * (n->params.max_ioqpairs + 1) * NVME_DB_SIZE);
6221 n->sq = g_new0(NvmeSQueue *, n->params.max_ioqpairs + 1);
6222 n->cq = g_new0(NvmeCQueue *, n->params.max_ioqpairs + 1);
6223 n->temperature = NVME_TEMPERATURE;
6224 n->features.temp_thresh_hi = NVME_TEMPERATURE_WARNING;
6225 n->starttime_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
6226 n->aer_reqs = g_new0(NvmeRequest *, n->params.aerl + 1);
6229 static void nvme_init_cmb(NvmeCtrl *n, PCIDevice *pci_dev)
6231 uint64_t cmb_size = n->params.cmb_size_mb * MiB;
6233 n->cmb.buf = g_malloc0(cmb_size);
6234 memory_region_init_io(&n->cmb.mem, OBJECT(n), &nvme_cmb_ops, n,
6235 "nvme-cmb", cmb_size);
6236 pci_register_bar(pci_dev, NVME_CMB_BIR,
6237 PCI_BASE_ADDRESS_SPACE_MEMORY |
6238 PCI_BASE_ADDRESS_MEM_TYPE_64 |
6239 PCI_BASE_ADDRESS_MEM_PREFETCH, &n->cmb.mem);
6241 NVME_CAP_SET_CMBS(n->bar.cap, 1);
6243 if (n->params.legacy_cmb) {
6244 nvme_cmb_enable_regs(n);
6245 n->cmb.cmse = true;
6249 static void nvme_init_pmr(NvmeCtrl *n, PCIDevice *pci_dev)
6251 NVME_PMRCAP_SET_RDS(n->bar.pmrcap, 1);
6252 NVME_PMRCAP_SET_WDS(n->bar.pmrcap, 1);
6253 NVME_PMRCAP_SET_BIR(n->bar.pmrcap, NVME_PMR_BIR);
6254 /* Turn on bit 1 support */
6255 NVME_PMRCAP_SET_PMRWBM(n->bar.pmrcap, 0x02);
6256 NVME_PMRCAP_SET_CMSS(n->bar.pmrcap, 1);
6258 pci_register_bar(pci_dev, NVME_PMRCAP_BIR(n->bar.pmrcap),
6259 PCI_BASE_ADDRESS_SPACE_MEMORY |
6260 PCI_BASE_ADDRESS_MEM_TYPE_64 |
6261 PCI_BASE_ADDRESS_MEM_PREFETCH, &n->pmr.dev->mr);
6263 memory_region_set_enabled(&n->pmr.dev->mr, false);
6266 static int nvme_init_pci(NvmeCtrl *n, PCIDevice *pci_dev, Error **errp)
6268 uint8_t *pci_conf = pci_dev->config;
6269 uint64_t bar_size, msix_table_size, msix_pba_size;
6270 unsigned msix_table_offset, msix_pba_offset;
6271 int ret;
6273 Error *err = NULL;
6275 pci_conf[PCI_INTERRUPT_PIN] = 1;
6276 pci_config_set_prog_interface(pci_conf, 0x2);
6278 if (n->params.use_intel_id) {
6279 pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
6280 pci_config_set_device_id(pci_conf, 0x5845);
6281 } else {
6282 pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REDHAT);
6283 pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REDHAT_NVME);
6286 pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_EXPRESS);
6287 pcie_endpoint_cap_init(pci_dev, 0x80);
6289 bar_size = QEMU_ALIGN_UP(n->reg_size, 4 * KiB);
6290 msix_table_offset = bar_size;
6291 msix_table_size = PCI_MSIX_ENTRY_SIZE * n->params.msix_qsize;
6293 bar_size += msix_table_size;
6294 bar_size = QEMU_ALIGN_UP(bar_size, 4 * KiB);
6295 msix_pba_offset = bar_size;
6296 msix_pba_size = QEMU_ALIGN_UP(n->params.msix_qsize, 64) / 8;
6298 bar_size += msix_pba_size;
6299 bar_size = pow2ceil(bar_size);
6301 memory_region_init(&n->bar0, OBJECT(n), "nvme-bar0", bar_size);
6302 memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, "nvme",
6303 n->reg_size);
6304 memory_region_add_subregion(&n->bar0, 0, &n->iomem);
6306 pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |
6307 PCI_BASE_ADDRESS_MEM_TYPE_64, &n->bar0);
6308 ret = msix_init(pci_dev, n->params.msix_qsize,
6309 &n->bar0, 0, msix_table_offset,
6310 &n->bar0, 0, msix_pba_offset, 0, &err);
6311 if (ret < 0) {
6312 if (ret == -ENOTSUP) {
6313 warn_report_err(err);
6314 } else {
6315 error_propagate(errp, err);
6316 return ret;
6320 if (n->params.cmb_size_mb) {
6321 nvme_init_cmb(n, pci_dev);
6324 if (n->pmr.dev) {
6325 nvme_init_pmr(n, pci_dev);
6328 return 0;
6331 static void nvme_init_subnqn(NvmeCtrl *n)
6333 NvmeSubsystem *subsys = n->subsys;
6334 NvmeIdCtrl *id = &n->id_ctrl;
6336 if (!subsys) {
6337 snprintf((char *)id->subnqn, sizeof(id->subnqn),
6338 "nqn.2019-08.org.qemu:%s", n->params.serial);
6339 } else {
6340 pstrcpy((char *)id->subnqn, sizeof(id->subnqn), (char*)subsys->subnqn);
6344 static void nvme_init_ctrl(NvmeCtrl *n, PCIDevice *pci_dev)
6346 NvmeIdCtrl *id = &n->id_ctrl;
6347 uint8_t *pci_conf = pci_dev->config;
6349 id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID));
6350 id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID));
6351 strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' ');
6352 strpadcpy((char *)id->fr, sizeof(id->fr), "1.0", ' ');
6353 strpadcpy((char *)id->sn, sizeof(id->sn), n->params.serial, ' ');
6355 id->cntlid = cpu_to_le16(n->cntlid);
6357 id->oaes = cpu_to_le32(NVME_OAES_NS_ATTR);
6359 id->rab = 6;
6361 if (n->params.use_intel_id) {
6362 id->ieee[0] = 0xb3;
6363 id->ieee[1] = 0x02;
6364 id->ieee[2] = 0x00;
6365 } else {
6366 id->ieee[0] = 0x00;
6367 id->ieee[1] = 0x54;
6368 id->ieee[2] = 0x52;
6371 id->mdts = n->params.mdts;
6372 id->ver = cpu_to_le32(NVME_SPEC_VER);
6373 id->oacs = cpu_to_le16(NVME_OACS_NS_MGMT | NVME_OACS_FORMAT);
6374 id->cntrltype = 0x1;
6377 * Because the controller always completes the Abort command immediately,
6378 * there can never be more than one concurrently executing Abort command,
6379 * so this value is never used for anything. Note that there can easily be
6380 * many Abort commands in the queues, but they are not considered
6381 * "executing" until processed by nvme_abort.
6383 * The specification recommends a value of 3 for Abort Command Limit (four
6384 * concurrently outstanding Abort commands), so lets use that though it is
6385 * inconsequential.
6387 id->acl = 3;
6388 id->aerl = n->params.aerl;
6389 id->frmw = (NVME_NUM_FW_SLOTS << 1) | NVME_FRMW_SLOT1_RO;
6390 id->lpa = NVME_LPA_NS_SMART | NVME_LPA_CSE | NVME_LPA_EXTENDED;
6392 /* recommended default value (~70 C) */
6393 id->wctemp = cpu_to_le16(NVME_TEMPERATURE_WARNING);
6394 id->cctemp = cpu_to_le16(NVME_TEMPERATURE_CRITICAL);
6396 id->sqes = (0x6 << 4) | 0x6;
6397 id->cqes = (0x4 << 4) | 0x4;
6398 id->nn = cpu_to_le32(NVME_MAX_NAMESPACES);
6399 id->oncs = cpu_to_le16(NVME_ONCS_WRITE_ZEROES | NVME_ONCS_TIMESTAMP |
6400 NVME_ONCS_FEATURES | NVME_ONCS_DSM |
6401 NVME_ONCS_COMPARE | NVME_ONCS_COPY);
6404 * NOTE: If this device ever supports a command set that does NOT use 0x0
6405 * as a Flush-equivalent operation, support for the broadcast NSID in Flush
6406 * should probably be removed.
6408 * See comment in nvme_io_cmd.
6410 id->vwc = NVME_VWC_NSID_BROADCAST_SUPPORT | NVME_VWC_PRESENT;
6412 id->ocfs = cpu_to_le16(NVME_OCFS_COPY_FORMAT_0);
6413 id->sgls = cpu_to_le32(NVME_CTRL_SGLS_SUPPORT_NO_ALIGN |
6414 NVME_CTRL_SGLS_BITBUCKET);
6416 nvme_init_subnqn(n);
6418 id->psd[0].mp = cpu_to_le16(0x9c4);
6419 id->psd[0].enlat = cpu_to_le32(0x10);
6420 id->psd[0].exlat = cpu_to_le32(0x4);
6422 if (n->subsys) {
6423 id->cmic |= NVME_CMIC_MULTI_CTRL;
6426 NVME_CAP_SET_MQES(n->bar.cap, 0x7ff);
6427 NVME_CAP_SET_CQR(n->bar.cap, 1);
6428 NVME_CAP_SET_TO(n->bar.cap, 0xf);
6429 NVME_CAP_SET_CSS(n->bar.cap, NVME_CAP_CSS_NVM);
6430 NVME_CAP_SET_CSS(n->bar.cap, NVME_CAP_CSS_CSI_SUPP);
6431 NVME_CAP_SET_CSS(n->bar.cap, NVME_CAP_CSS_ADMIN_ONLY);
6432 NVME_CAP_SET_MPSMAX(n->bar.cap, 4);
6433 NVME_CAP_SET_CMBS(n->bar.cap, n->params.cmb_size_mb ? 1 : 0);
6434 NVME_CAP_SET_PMRS(n->bar.cap, n->pmr.dev ? 1 : 0);
6436 n->bar.vs = NVME_SPEC_VER;
6437 n->bar.intmc = n->bar.intms = 0;
6440 static int nvme_init_subsys(NvmeCtrl *n, Error **errp)
6442 int cntlid;
6444 if (!n->subsys) {
6445 return 0;
6448 cntlid = nvme_subsys_register_ctrl(n, errp);
6449 if (cntlid < 0) {
6450 return -1;
6453 n->cntlid = cntlid;
6455 return 0;
6458 void nvme_attach_ns(NvmeCtrl *n, NvmeNamespace *ns)
6460 uint32_t nsid = ns->params.nsid;
6461 assert(nsid && nsid <= NVME_MAX_NAMESPACES);
6463 n->namespaces[nsid] = ns;
6464 ns->attached++;
6466 n->dmrsl = MIN_NON_ZERO(n->dmrsl,
6467 BDRV_REQUEST_MAX_BYTES / nvme_l2b(ns, 1));
6470 static void nvme_realize(PCIDevice *pci_dev, Error **errp)
6472 NvmeCtrl *n = NVME(pci_dev);
6473 NvmeNamespace *ns;
6474 Error *local_err = NULL;
6476 nvme_check_constraints(n, &local_err);
6477 if (local_err) {
6478 error_propagate(errp, local_err);
6479 return;
6482 qbus_create_inplace(&n->bus, sizeof(NvmeBus), TYPE_NVME_BUS,
6483 &pci_dev->qdev, n->parent_obj.qdev.id);
6485 nvme_init_state(n);
6486 if (nvme_init_pci(n, pci_dev, errp)) {
6487 return;
6490 if (nvme_init_subsys(n, errp)) {
6491 error_propagate(errp, local_err);
6492 return;
6494 nvme_init_ctrl(n, pci_dev);
6496 /* setup a namespace if the controller drive property was given */
6497 if (n->namespace.blkconf.blk) {
6498 ns = &n->namespace;
6499 ns->params.nsid = 1;
6501 if (nvme_ns_setup(n, ns, errp)) {
6502 return;
6505 nvme_attach_ns(n, ns);
6509 static void nvme_exit(PCIDevice *pci_dev)
6511 NvmeCtrl *n = NVME(pci_dev);
6512 NvmeNamespace *ns;
6513 int i;
6515 nvme_ctrl_reset(n);
6517 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6518 ns = nvme_ns(n, i);
6519 if (!ns) {
6520 continue;
6523 nvme_ns_cleanup(ns);
6526 g_free(n->cq);
6527 g_free(n->sq);
6528 g_free(n->aer_reqs);
6530 if (n->params.cmb_size_mb) {
6531 g_free(n->cmb.buf);
6534 if (n->pmr.dev) {
6535 host_memory_backend_set_mapped(n->pmr.dev, false);
6537 msix_uninit(pci_dev, &n->bar0, &n->bar0);
6538 memory_region_del_subregion(&n->bar0, &n->iomem);
6541 static Property nvme_props[] = {
6542 DEFINE_BLOCK_PROPERTIES(NvmeCtrl, namespace.blkconf),
6543 DEFINE_PROP_LINK("pmrdev", NvmeCtrl, pmr.dev, TYPE_MEMORY_BACKEND,
6544 HostMemoryBackend *),
6545 DEFINE_PROP_LINK("subsys", NvmeCtrl, subsys, TYPE_NVME_SUBSYS,
6546 NvmeSubsystem *),
6547 DEFINE_PROP_STRING("serial", NvmeCtrl, params.serial),
6548 DEFINE_PROP_UINT32("cmb_size_mb", NvmeCtrl, params.cmb_size_mb, 0),
6549 DEFINE_PROP_UINT32("num_queues", NvmeCtrl, params.num_queues, 0),
6550 DEFINE_PROP_UINT32("max_ioqpairs", NvmeCtrl, params.max_ioqpairs, 64),
6551 DEFINE_PROP_UINT16("msix_qsize", NvmeCtrl, params.msix_qsize, 65),
6552 DEFINE_PROP_UINT8("aerl", NvmeCtrl, params.aerl, 3),
6553 DEFINE_PROP_UINT32("aer_max_queued", NvmeCtrl, params.aer_max_queued, 64),
6554 DEFINE_PROP_UINT8("mdts", NvmeCtrl, params.mdts, 7),
6555 DEFINE_PROP_UINT8("vsl", NvmeCtrl, params.vsl, 7),
6556 DEFINE_PROP_BOOL("use-intel-id", NvmeCtrl, params.use_intel_id, false),
6557 DEFINE_PROP_BOOL("legacy-cmb", NvmeCtrl, params.legacy_cmb, false),
6558 DEFINE_PROP_UINT8("zoned.zasl", NvmeCtrl, params.zasl, 0),
6559 DEFINE_PROP_BOOL("zoned.auto_transition", NvmeCtrl,
6560 params.auto_transition_zones, true),
6561 DEFINE_PROP_END_OF_LIST(),
6564 static void nvme_get_smart_warning(Object *obj, Visitor *v, const char *name,
6565 void *opaque, Error **errp)
6567 NvmeCtrl *n = NVME(obj);
6568 uint8_t value = n->smart_critical_warning;
6570 visit_type_uint8(v, name, &value, errp);
6573 static void nvme_set_smart_warning(Object *obj, Visitor *v, const char *name,
6574 void *opaque, Error **errp)
6576 NvmeCtrl *n = NVME(obj);
6577 uint8_t value, old_value, cap = 0, index, event;
6579 if (!visit_type_uint8(v, name, &value, errp)) {
6580 return;
6583 cap = NVME_SMART_SPARE | NVME_SMART_TEMPERATURE | NVME_SMART_RELIABILITY
6584 | NVME_SMART_MEDIA_READ_ONLY | NVME_SMART_FAILED_VOLATILE_MEDIA;
6585 if (NVME_CAP_PMRS(n->bar.cap)) {
6586 cap |= NVME_SMART_PMR_UNRELIABLE;
6589 if ((value & cap) != value) {
6590 error_setg(errp, "unsupported smart critical warning bits: 0x%x",
6591 value & ~cap);
6592 return;
6595 old_value = n->smart_critical_warning;
6596 n->smart_critical_warning = value;
6598 /* only inject new bits of smart critical warning */
6599 for (index = 0; index < NVME_SMART_WARN_MAX; index++) {
6600 event = 1 << index;
6601 if (value & ~old_value & event)
6602 nvme_smart_event(n, event);
6606 static const VMStateDescription nvme_vmstate = {
6607 .name = "nvme",
6608 .unmigratable = 1,
6611 static void nvme_class_init(ObjectClass *oc, void *data)
6613 DeviceClass *dc = DEVICE_CLASS(oc);
6614 PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc);
6616 pc->realize = nvme_realize;
6617 pc->exit = nvme_exit;
6618 pc->class_id = PCI_CLASS_STORAGE_EXPRESS;
6619 pc->revision = 2;
6621 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
6622 dc->desc = "Non-Volatile Memory Express";
6623 device_class_set_props(dc, nvme_props);
6624 dc->vmsd = &nvme_vmstate;
6627 static void nvme_instance_init(Object *obj)
6629 NvmeCtrl *n = NVME(obj);
6631 device_add_bootindex_property(obj, &n->namespace.blkconf.bootindex,
6632 "bootindex", "/namespace@1,0",
6633 DEVICE(obj));
6635 object_property_add(obj, "smart_critical_warning", "uint8",
6636 nvme_get_smart_warning,
6637 nvme_set_smart_warning, NULL, NULL);
6640 static const TypeInfo nvme_info = {
6641 .name = TYPE_NVME,
6642 .parent = TYPE_PCI_DEVICE,
6643 .instance_size = sizeof(NvmeCtrl),
6644 .instance_init = nvme_instance_init,
6645 .class_init = nvme_class_init,
6646 .interfaces = (InterfaceInfo[]) {
6647 { INTERFACE_PCIE_DEVICE },
6652 static const TypeInfo nvme_bus_info = {
6653 .name = TYPE_NVME_BUS,
6654 .parent = TYPE_BUS,
6655 .instance_size = sizeof(NvmeBus),
6658 static void nvme_register_types(void)
6660 type_register_static(&nvme_info);
6661 type_register_static(&nvme_bus_info);
6664 type_init(nvme_register_types)