qapi: Improve specificity of type/member descriptions
[qemu/armbru.git] / hw / nvme / ctrl.c
blobf59dfe1cbe96db18394c6d62a135e8acbca9113b
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 * sriov_max_vfs=<N[optional]> \
39 * sriov_vq_flexible=<N[optional]> \
40 * sriov_vi_flexible=<N[optional]> \
41 * sriov_max_vi_per_vf=<N[optional]> \
42 * sriov_max_vq_per_vf=<N[optional]> \
43 * subsys=<subsys_id>
44 * -device nvme-ns,drive=<drive_id>,bus=<bus_name>,nsid=<nsid>,\
45 * zoned=<true|false[optional]>, \
46 * subsys=<subsys_id>,detached=<true|false[optional]>
48 * Note cmb_size_mb denotes size of CMB in MB. CMB is assumed to be at
49 * offset 0 in BAR2 and supports only WDS, RDS and SQS for now. By default, the
50 * device will use the "v1.4 CMB scheme" - use the `legacy-cmb` parameter to
51 * always enable the CMBLOC and CMBSZ registers (v1.3 behavior).
53 * Enabling pmr emulation can be achieved by pointing to memory-backend-file.
54 * For example:
55 * -object memory-backend-file,id=<mem_id>,share=on,mem-path=<file_path>, \
56 * size=<size> .... -device nvme,...,pmrdev=<mem_id>
58 * The PMR will use BAR 4/5 exclusively.
60 * To place controller(s) and namespace(s) to a subsystem, then provide
61 * nvme-subsys device as above.
63 * nvme subsystem device parameters
64 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65 * - `nqn`
66 * This parameter provides the `<nqn_id>` part of the string
67 * `nqn.2019-08.org.qemu:<nqn_id>` which will be reported in the SUBNQN field
68 * of subsystem controllers. Note that `<nqn_id>` should be unique per
69 * subsystem, but this is not enforced by QEMU. If not specified, it will
70 * default to the value of the `id` parameter (`<subsys_id>`).
72 * nvme device parameters
73 * ~~~~~~~~~~~~~~~~~~~~~~
74 * - `subsys`
75 * Specifying this parameter attaches the controller to the subsystem and
76 * the SUBNQN field in the controller will report the NQN of the subsystem
77 * device. This also enables multi controller capability represented in
78 * Identify Controller data structure in CMIC (Controller Multi-path I/O and
79 * Namespace Sharing Capabilities).
81 * - `aerl`
82 * The Asynchronous Event Request Limit (AERL). Indicates the maximum number
83 * of concurrently outstanding Asynchronous Event Request commands support
84 * by the controller. This is a 0's based value.
86 * - `aer_max_queued`
87 * This is the maximum number of events that the device will enqueue for
88 * completion when there are no outstanding AERs. When the maximum number of
89 * enqueued events are reached, subsequent events will be dropped.
91 * - `mdts`
92 * Indicates the maximum data transfer size for a command that transfers data
93 * between host-accessible memory and the controller. The value is specified
94 * as a power of two (2^n) and is in units of the minimum memory page size
95 * (CAP.MPSMIN). The default value is 7 (i.e. 512 KiB).
97 * - `vsl`
98 * Indicates the maximum data size limit for the Verify command. Like `mdts`,
99 * this value is specified as a power of two (2^n) and is in units of the
100 * minimum memory page size (CAP.MPSMIN). The default value is 7 (i.e. 512
101 * KiB).
103 * - `zoned.zasl`
104 * Indicates the maximum data transfer size for the Zone Append command. Like
105 * `mdts`, the value is specified as a power of two (2^n) and is in units of
106 * the minimum memory page size (CAP.MPSMIN). The default value is 0 (i.e.
107 * defaulting to the value of `mdts`).
109 * - `zoned.auto_transition`
110 * Indicates if zones in zone state implicitly opened can be automatically
111 * transitioned to zone state closed for resource management purposes.
112 * Defaults to 'on'.
114 * - `sriov_max_vfs`
115 * Indicates the maximum number of PCIe virtual functions supported
116 * by the controller. The default value is 0. Specifying a non-zero value
117 * enables reporting of both SR-IOV and ARI capabilities by the NVMe device.
118 * Virtual function controllers will not report SR-IOV capability.
120 * NOTE: Single Root I/O Virtualization support is experimental.
121 * All the related parameters may be subject to change.
123 * - `sriov_vq_flexible`
124 * Indicates the total number of flexible queue resources assignable to all
125 * the secondary controllers. Implicitly sets the number of primary
126 * controller's private resources to `(max_ioqpairs - sriov_vq_flexible)`.
128 * - `sriov_vi_flexible`
129 * Indicates the total number of flexible interrupt resources assignable to
130 * all the secondary controllers. Implicitly sets the number of primary
131 * controller's private resources to `(msix_qsize - sriov_vi_flexible)`.
133 * - `sriov_max_vi_per_vf`
134 * Indicates the maximum number of virtual interrupt resources assignable
135 * to a secondary controller. The default 0 resolves to
136 * `(sriov_vi_flexible / sriov_max_vfs)`.
138 * - `sriov_max_vq_per_vf`
139 * Indicates the maximum number of virtual queue resources assignable to
140 * a secondary controller. The default 0 resolves to
141 * `(sriov_vq_flexible / sriov_max_vfs)`.
143 * nvme namespace device parameters
144 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
145 * - `shared`
146 * When the parent nvme device (as defined explicitly by the 'bus' parameter
147 * or implicitly by the most recently defined NvmeBus) is linked to an
148 * nvme-subsys device, the namespace will be attached to all controllers in
149 * the subsystem. If set to 'off' (the default), the namespace will remain a
150 * private namespace and may only be attached to a single controller at a
151 * time.
153 * - `detached`
154 * This parameter is only valid together with the `subsys` parameter. If left
155 * at the default value (`false/off`), the namespace will be attached to all
156 * controllers in the NVMe subsystem at boot-up. If set to `true/on`, the
157 * namespace will be available in the subsystem but not attached to any
158 * controllers.
160 * Setting `zoned` to true selects Zoned Command Set at the namespace.
161 * In this case, the following namespace properties are available to configure
162 * zoned operation:
163 * zoned.zone_size=<zone size in bytes, default: 128MiB>
164 * The number may be followed by K, M, G as in kilo-, mega- or giga-.
166 * zoned.zone_capacity=<zone capacity in bytes, default: zone size>
167 * The value 0 (default) forces zone capacity to be the same as zone
168 * size. The value of this property may not exceed zone size.
170 * zoned.descr_ext_size=<zone descriptor extension size, default 0>
171 * This value needs to be specified in 64B units. If it is zero,
172 * namespace(s) will not support zone descriptor extensions.
174 * zoned.max_active=<Maximum Active Resources (zones), default: 0>
175 * The default value means there is no limit to the number of
176 * concurrently active zones.
178 * zoned.max_open=<Maximum Open Resources (zones), default: 0>
179 * The default value means there is no limit to the number of
180 * concurrently open zones.
182 * zoned.cross_read=<enable RAZB, default: false>
183 * Setting this property to true enables Read Across Zone Boundaries.
186 #include "qemu/osdep.h"
187 #include "qemu/cutils.h"
188 #include "qemu/error-report.h"
189 #include "qemu/log.h"
190 #include "qemu/units.h"
191 #include "qemu/range.h"
192 #include "qapi/error.h"
193 #include "qapi/visitor.h"
194 #include "sysemu/sysemu.h"
195 #include "sysemu/block-backend.h"
196 #include "sysemu/hostmem.h"
197 #include "hw/pci/msix.h"
198 #include "hw/pci/pcie_sriov.h"
199 #include "migration/vmstate.h"
201 #include "nvme.h"
202 #include "dif.h"
203 #include "trace.h"
205 #define NVME_MAX_IOQPAIRS 0xffff
206 #define NVME_DB_SIZE 4
207 #define NVME_SPEC_VER 0x00010400
208 #define NVME_CMB_BIR 2
209 #define NVME_PMR_BIR 4
210 #define NVME_TEMPERATURE 0x143
211 #define NVME_TEMPERATURE_WARNING 0x157
212 #define NVME_TEMPERATURE_CRITICAL 0x175
213 #define NVME_NUM_FW_SLOTS 1
214 #define NVME_DEFAULT_MAX_ZA_SIZE (128 * KiB)
215 #define NVME_MAX_VFS 127
216 #define NVME_VF_RES_GRANULARITY 1
217 #define NVME_VF_OFFSET 0x1
218 #define NVME_VF_STRIDE 1
220 #define NVME_GUEST_ERR(trace, fmt, ...) \
221 do { \
222 (trace_##trace)(__VA_ARGS__); \
223 qemu_log_mask(LOG_GUEST_ERROR, #trace \
224 " in %s: " fmt "\n", __func__, ## __VA_ARGS__); \
225 } while (0)
227 static const bool nvme_feature_support[NVME_FID_MAX] = {
228 [NVME_ARBITRATION] = true,
229 [NVME_POWER_MANAGEMENT] = true,
230 [NVME_TEMPERATURE_THRESHOLD] = true,
231 [NVME_ERROR_RECOVERY] = true,
232 [NVME_VOLATILE_WRITE_CACHE] = true,
233 [NVME_NUMBER_OF_QUEUES] = true,
234 [NVME_INTERRUPT_COALESCING] = true,
235 [NVME_INTERRUPT_VECTOR_CONF] = true,
236 [NVME_WRITE_ATOMICITY] = true,
237 [NVME_ASYNCHRONOUS_EVENT_CONF] = true,
238 [NVME_TIMESTAMP] = true,
239 [NVME_HOST_BEHAVIOR_SUPPORT] = true,
240 [NVME_COMMAND_SET_PROFILE] = true,
241 [NVME_FDP_MODE] = true,
242 [NVME_FDP_EVENTS] = true,
245 static const uint32_t nvme_feature_cap[NVME_FID_MAX] = {
246 [NVME_TEMPERATURE_THRESHOLD] = NVME_FEAT_CAP_CHANGE,
247 [NVME_ERROR_RECOVERY] = NVME_FEAT_CAP_CHANGE | NVME_FEAT_CAP_NS,
248 [NVME_VOLATILE_WRITE_CACHE] = NVME_FEAT_CAP_CHANGE,
249 [NVME_NUMBER_OF_QUEUES] = NVME_FEAT_CAP_CHANGE,
250 [NVME_ASYNCHRONOUS_EVENT_CONF] = NVME_FEAT_CAP_CHANGE,
251 [NVME_TIMESTAMP] = NVME_FEAT_CAP_CHANGE,
252 [NVME_HOST_BEHAVIOR_SUPPORT] = NVME_FEAT_CAP_CHANGE,
253 [NVME_COMMAND_SET_PROFILE] = NVME_FEAT_CAP_CHANGE,
254 [NVME_FDP_MODE] = NVME_FEAT_CAP_CHANGE,
255 [NVME_FDP_EVENTS] = NVME_FEAT_CAP_CHANGE | NVME_FEAT_CAP_NS,
258 static const uint32_t nvme_cse_acs[256] = {
259 [NVME_ADM_CMD_DELETE_SQ] = NVME_CMD_EFF_CSUPP,
260 [NVME_ADM_CMD_CREATE_SQ] = NVME_CMD_EFF_CSUPP,
261 [NVME_ADM_CMD_GET_LOG_PAGE] = NVME_CMD_EFF_CSUPP,
262 [NVME_ADM_CMD_DELETE_CQ] = NVME_CMD_EFF_CSUPP,
263 [NVME_ADM_CMD_CREATE_CQ] = NVME_CMD_EFF_CSUPP,
264 [NVME_ADM_CMD_IDENTIFY] = NVME_CMD_EFF_CSUPP,
265 [NVME_ADM_CMD_ABORT] = NVME_CMD_EFF_CSUPP,
266 [NVME_ADM_CMD_SET_FEATURES] = NVME_CMD_EFF_CSUPP,
267 [NVME_ADM_CMD_GET_FEATURES] = NVME_CMD_EFF_CSUPP,
268 [NVME_ADM_CMD_ASYNC_EV_REQ] = NVME_CMD_EFF_CSUPP,
269 [NVME_ADM_CMD_NS_ATTACHMENT] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_NIC,
270 [NVME_ADM_CMD_VIRT_MNGMT] = NVME_CMD_EFF_CSUPP,
271 [NVME_ADM_CMD_DBBUF_CONFIG] = NVME_CMD_EFF_CSUPP,
272 [NVME_ADM_CMD_FORMAT_NVM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
273 [NVME_ADM_CMD_DIRECTIVE_RECV] = NVME_CMD_EFF_CSUPP,
274 [NVME_ADM_CMD_DIRECTIVE_SEND] = NVME_CMD_EFF_CSUPP,
277 static const uint32_t nvme_cse_iocs_none[256];
279 static const uint32_t nvme_cse_iocs_nvm[256] = {
280 [NVME_CMD_FLUSH] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
281 [NVME_CMD_WRITE_ZEROES] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
282 [NVME_CMD_WRITE] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
283 [NVME_CMD_READ] = NVME_CMD_EFF_CSUPP,
284 [NVME_CMD_DSM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
285 [NVME_CMD_VERIFY] = NVME_CMD_EFF_CSUPP,
286 [NVME_CMD_COPY] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
287 [NVME_CMD_COMPARE] = NVME_CMD_EFF_CSUPP,
288 [NVME_CMD_IO_MGMT_RECV] = NVME_CMD_EFF_CSUPP,
289 [NVME_CMD_IO_MGMT_SEND] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
292 static const uint32_t nvme_cse_iocs_zoned[256] = {
293 [NVME_CMD_FLUSH] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
294 [NVME_CMD_WRITE_ZEROES] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
295 [NVME_CMD_WRITE] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
296 [NVME_CMD_READ] = NVME_CMD_EFF_CSUPP,
297 [NVME_CMD_DSM] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
298 [NVME_CMD_VERIFY] = NVME_CMD_EFF_CSUPP,
299 [NVME_CMD_COPY] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
300 [NVME_CMD_COMPARE] = NVME_CMD_EFF_CSUPP,
301 [NVME_CMD_ZONE_APPEND] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
302 [NVME_CMD_ZONE_MGMT_SEND] = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
303 [NVME_CMD_ZONE_MGMT_RECV] = NVME_CMD_EFF_CSUPP,
306 static void nvme_process_sq(void *opaque);
307 static void nvme_ctrl_reset(NvmeCtrl *n, NvmeResetType rst);
308 static inline uint64_t nvme_get_timestamp(const NvmeCtrl *n);
310 static uint16_t nvme_sqid(NvmeRequest *req)
312 return le16_to_cpu(req->sq->sqid);
315 static inline uint16_t nvme_make_pid(NvmeNamespace *ns, uint16_t rg,
316 uint16_t ph)
318 uint16_t rgif = ns->endgrp->fdp.rgif;
320 if (!rgif) {
321 return ph;
324 return (rg << (16 - rgif)) | ph;
327 static inline bool nvme_ph_valid(NvmeNamespace *ns, uint16_t ph)
329 return ph < ns->fdp.nphs;
332 static inline bool nvme_rg_valid(NvmeEnduranceGroup *endgrp, uint16_t rg)
334 return rg < endgrp->fdp.nrg;
337 static inline uint16_t nvme_pid2ph(NvmeNamespace *ns, uint16_t pid)
339 uint16_t rgif = ns->endgrp->fdp.rgif;
341 if (!rgif) {
342 return pid;
345 return pid & ((1 << (15 - rgif)) - 1);
348 static inline uint16_t nvme_pid2rg(NvmeNamespace *ns, uint16_t pid)
350 uint16_t rgif = ns->endgrp->fdp.rgif;
352 if (!rgif) {
353 return 0;
356 return pid >> (16 - rgif);
359 static inline bool nvme_parse_pid(NvmeNamespace *ns, uint16_t pid,
360 uint16_t *ph, uint16_t *rg)
362 *rg = nvme_pid2rg(ns, pid);
363 *ph = nvme_pid2ph(ns, pid);
365 return nvme_ph_valid(ns, *ph) && nvme_rg_valid(ns->endgrp, *rg);
368 static void nvme_assign_zone_state(NvmeNamespace *ns, NvmeZone *zone,
369 NvmeZoneState state)
371 if (QTAILQ_IN_USE(zone, entry)) {
372 switch (nvme_get_zone_state(zone)) {
373 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
374 QTAILQ_REMOVE(&ns->exp_open_zones, zone, entry);
375 break;
376 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
377 QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
378 break;
379 case NVME_ZONE_STATE_CLOSED:
380 QTAILQ_REMOVE(&ns->closed_zones, zone, entry);
381 break;
382 case NVME_ZONE_STATE_FULL:
383 QTAILQ_REMOVE(&ns->full_zones, zone, entry);
384 default:
389 nvme_set_zone_state(zone, state);
391 switch (state) {
392 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
393 QTAILQ_INSERT_TAIL(&ns->exp_open_zones, zone, entry);
394 break;
395 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
396 QTAILQ_INSERT_TAIL(&ns->imp_open_zones, zone, entry);
397 break;
398 case NVME_ZONE_STATE_CLOSED:
399 QTAILQ_INSERT_TAIL(&ns->closed_zones, zone, entry);
400 break;
401 case NVME_ZONE_STATE_FULL:
402 QTAILQ_INSERT_TAIL(&ns->full_zones, zone, entry);
403 case NVME_ZONE_STATE_READ_ONLY:
404 break;
405 default:
406 zone->d.za = 0;
410 static uint16_t nvme_zns_check_resources(NvmeNamespace *ns, uint32_t act,
411 uint32_t opn, uint32_t zrwa)
413 if (ns->params.max_active_zones != 0 &&
414 ns->nr_active_zones + act > ns->params.max_active_zones) {
415 trace_pci_nvme_err_insuff_active_res(ns->params.max_active_zones);
416 return NVME_ZONE_TOO_MANY_ACTIVE | NVME_DNR;
419 if (ns->params.max_open_zones != 0 &&
420 ns->nr_open_zones + opn > ns->params.max_open_zones) {
421 trace_pci_nvme_err_insuff_open_res(ns->params.max_open_zones);
422 return NVME_ZONE_TOO_MANY_OPEN | NVME_DNR;
425 if (zrwa > ns->zns.numzrwa) {
426 return NVME_NOZRWA | NVME_DNR;
429 return NVME_SUCCESS;
433 * Check if we can open a zone without exceeding open/active limits.
434 * AOR stands for "Active and Open Resources" (see TP 4053 section 2.5).
436 static uint16_t nvme_aor_check(NvmeNamespace *ns, uint32_t act, uint32_t opn)
438 return nvme_zns_check_resources(ns, act, opn, 0);
441 static NvmeFdpEvent *nvme_fdp_alloc_event(NvmeCtrl *n, NvmeFdpEventBuffer *ebuf)
443 NvmeFdpEvent *ret = NULL;
444 bool is_full = ebuf->next == ebuf->start && ebuf->nelems;
446 ret = &ebuf->events[ebuf->next++];
447 if (unlikely(ebuf->next == NVME_FDP_MAX_EVENTS)) {
448 ebuf->next = 0;
450 if (is_full) {
451 ebuf->start = ebuf->next;
452 } else {
453 ebuf->nelems++;
456 memset(ret, 0, sizeof(NvmeFdpEvent));
457 ret->timestamp = nvme_get_timestamp(n);
459 return ret;
462 static inline int log_event(NvmeRuHandle *ruh, uint8_t event_type)
464 return (ruh->event_filter >> nvme_fdp_evf_shifts[event_type]) & 0x1;
467 static bool nvme_update_ruh(NvmeCtrl *n, NvmeNamespace *ns, uint16_t pid)
469 NvmeEnduranceGroup *endgrp = ns->endgrp;
470 NvmeRuHandle *ruh;
471 NvmeReclaimUnit *ru;
472 NvmeFdpEvent *e = NULL;
473 uint16_t ph, rg, ruhid;
475 if (!nvme_parse_pid(ns, pid, &ph, &rg)) {
476 return false;
479 ruhid = ns->fdp.phs[ph];
481 ruh = &endgrp->fdp.ruhs[ruhid];
482 ru = &ruh->rus[rg];
484 if (ru->ruamw) {
485 if (log_event(ruh, FDP_EVT_RU_NOT_FULLY_WRITTEN)) {
486 e = nvme_fdp_alloc_event(n, &endgrp->fdp.host_events);
487 e->type = FDP_EVT_RU_NOT_FULLY_WRITTEN;
488 e->flags = FDPEF_PIV | FDPEF_NSIDV | FDPEF_LV;
489 e->pid = cpu_to_le16(pid);
490 e->nsid = cpu_to_le32(ns->params.nsid);
491 e->rgid = cpu_to_le16(rg);
492 e->ruhid = cpu_to_le16(ruhid);
495 /* log (eventual) GC overhead of prematurely swapping the RU */
496 nvme_fdp_stat_inc(&endgrp->fdp.mbmw, nvme_l2b(ns, ru->ruamw));
499 ru->ruamw = ruh->ruamw;
501 return true;
504 static bool nvme_addr_is_cmb(NvmeCtrl *n, hwaddr addr)
506 hwaddr hi, lo;
508 if (!n->cmb.cmse) {
509 return false;
512 lo = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
513 hi = lo + int128_get64(n->cmb.mem.size);
515 return addr >= lo && addr < hi;
518 static inline void *nvme_addr_to_cmb(NvmeCtrl *n, hwaddr addr)
520 hwaddr base = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
521 return &n->cmb.buf[addr - base];
524 static bool nvme_addr_is_pmr(NvmeCtrl *n, hwaddr addr)
526 hwaddr hi;
528 if (!n->pmr.cmse) {
529 return false;
532 hi = n->pmr.cba + int128_get64(n->pmr.dev->mr.size);
534 return addr >= n->pmr.cba && addr < hi;
537 static inline void *nvme_addr_to_pmr(NvmeCtrl *n, hwaddr addr)
539 return memory_region_get_ram_ptr(&n->pmr.dev->mr) + (addr - n->pmr.cba);
542 static inline bool nvme_addr_is_iomem(NvmeCtrl *n, hwaddr addr)
544 hwaddr hi, lo;
547 * The purpose of this check is to guard against invalid "local" access to
548 * the iomem (i.e. controller registers). Thus, we check against the range
549 * covered by the 'bar0' MemoryRegion since that is currently composed of
550 * two subregions (the NVMe "MBAR" and the MSI-X table/pba). Note, however,
551 * that if the device model is ever changed to allow the CMB to be located
552 * in BAR0 as well, then this must be changed.
554 lo = n->bar0.addr;
555 hi = lo + int128_get64(n->bar0.size);
557 return addr >= lo && addr < hi;
560 static int nvme_addr_read(NvmeCtrl *n, hwaddr addr, void *buf, int size)
562 hwaddr hi = addr + size - 1;
563 if (hi < addr) {
564 return 1;
567 if (n->bar.cmbsz && nvme_addr_is_cmb(n, addr) && nvme_addr_is_cmb(n, hi)) {
568 memcpy(buf, nvme_addr_to_cmb(n, addr), size);
569 return 0;
572 if (nvme_addr_is_pmr(n, addr) && nvme_addr_is_pmr(n, hi)) {
573 memcpy(buf, nvme_addr_to_pmr(n, addr), size);
574 return 0;
577 return pci_dma_read(PCI_DEVICE(n), addr, buf, size);
580 static int nvme_addr_write(NvmeCtrl *n, hwaddr addr, const void *buf, int size)
582 hwaddr hi = addr + size - 1;
583 if (hi < addr) {
584 return 1;
587 if (n->bar.cmbsz && nvme_addr_is_cmb(n, addr) && nvme_addr_is_cmb(n, hi)) {
588 memcpy(nvme_addr_to_cmb(n, addr), buf, size);
589 return 0;
592 if (nvme_addr_is_pmr(n, addr) && nvme_addr_is_pmr(n, hi)) {
593 memcpy(nvme_addr_to_pmr(n, addr), buf, size);
594 return 0;
597 return pci_dma_write(PCI_DEVICE(n), addr, buf, size);
600 static bool nvme_nsid_valid(NvmeCtrl *n, uint32_t nsid)
602 return nsid &&
603 (nsid == NVME_NSID_BROADCAST || nsid <= NVME_MAX_NAMESPACES);
606 static int nvme_check_sqid(NvmeCtrl *n, uint16_t sqid)
608 return sqid < n->conf_ioqpairs + 1 && n->sq[sqid] != NULL ? 0 : -1;
611 static int nvme_check_cqid(NvmeCtrl *n, uint16_t cqid)
613 return cqid < n->conf_ioqpairs + 1 && n->cq[cqid] != NULL ? 0 : -1;
616 static void nvme_inc_cq_tail(NvmeCQueue *cq)
618 cq->tail++;
619 if (cq->tail >= cq->size) {
620 cq->tail = 0;
621 cq->phase = !cq->phase;
625 static void nvme_inc_sq_head(NvmeSQueue *sq)
627 sq->head = (sq->head + 1) % sq->size;
630 static uint8_t nvme_cq_full(NvmeCQueue *cq)
632 return (cq->tail + 1) % cq->size == cq->head;
635 static uint8_t nvme_sq_empty(NvmeSQueue *sq)
637 return sq->head == sq->tail;
640 static void nvme_irq_check(NvmeCtrl *n)
642 PCIDevice *pci = PCI_DEVICE(n);
643 uint32_t intms = ldl_le_p(&n->bar.intms);
645 if (msix_enabled(pci)) {
646 return;
648 if (~intms & n->irq_status) {
649 pci_irq_assert(pci);
650 } else {
651 pci_irq_deassert(pci);
655 static void nvme_irq_assert(NvmeCtrl *n, NvmeCQueue *cq)
657 PCIDevice *pci = PCI_DEVICE(n);
659 if (cq->irq_enabled) {
660 if (msix_enabled(pci)) {
661 trace_pci_nvme_irq_msix(cq->vector);
662 msix_notify(pci, cq->vector);
663 } else {
664 trace_pci_nvme_irq_pin();
665 assert(cq->vector < 32);
666 n->irq_status |= 1 << cq->vector;
667 nvme_irq_check(n);
669 } else {
670 trace_pci_nvme_irq_masked();
674 static void nvme_irq_deassert(NvmeCtrl *n, NvmeCQueue *cq)
676 if (cq->irq_enabled) {
677 if (msix_enabled(PCI_DEVICE(n))) {
678 return;
679 } else {
680 assert(cq->vector < 32);
681 if (!n->cq_pending) {
682 n->irq_status &= ~(1 << cq->vector);
684 nvme_irq_check(n);
689 static void nvme_req_clear(NvmeRequest *req)
691 req->ns = NULL;
692 req->opaque = NULL;
693 req->aiocb = NULL;
694 memset(&req->cqe, 0x0, sizeof(req->cqe));
695 req->status = NVME_SUCCESS;
698 static inline void nvme_sg_init(NvmeCtrl *n, NvmeSg *sg, bool dma)
700 if (dma) {
701 pci_dma_sglist_init(&sg->qsg, PCI_DEVICE(n), 0);
702 sg->flags = NVME_SG_DMA;
703 } else {
704 qemu_iovec_init(&sg->iov, 0);
707 sg->flags |= NVME_SG_ALLOC;
710 static inline void nvme_sg_unmap(NvmeSg *sg)
712 if (!(sg->flags & NVME_SG_ALLOC)) {
713 return;
716 if (sg->flags & NVME_SG_DMA) {
717 qemu_sglist_destroy(&sg->qsg);
718 } else {
719 qemu_iovec_destroy(&sg->iov);
722 memset(sg, 0x0, sizeof(*sg));
726 * When metadata is transfered as extended LBAs, the DPTR mapped into `sg`
727 * holds both data and metadata. This function splits the data and metadata
728 * into two separate QSG/IOVs.
730 static void nvme_sg_split(NvmeSg *sg, NvmeNamespace *ns, NvmeSg *data,
731 NvmeSg *mdata)
733 NvmeSg *dst = data;
734 uint32_t trans_len, count = ns->lbasz;
735 uint64_t offset = 0;
736 bool dma = sg->flags & NVME_SG_DMA;
737 size_t sge_len;
738 size_t sg_len = dma ? sg->qsg.size : sg->iov.size;
739 int sg_idx = 0;
741 assert(sg->flags & NVME_SG_ALLOC);
743 while (sg_len) {
744 sge_len = dma ? sg->qsg.sg[sg_idx].len : sg->iov.iov[sg_idx].iov_len;
746 trans_len = MIN(sg_len, count);
747 trans_len = MIN(trans_len, sge_len - offset);
749 if (dst) {
750 if (dma) {
751 qemu_sglist_add(&dst->qsg, sg->qsg.sg[sg_idx].base + offset,
752 trans_len);
753 } else {
754 qemu_iovec_add(&dst->iov,
755 sg->iov.iov[sg_idx].iov_base + offset,
756 trans_len);
760 sg_len -= trans_len;
761 count -= trans_len;
762 offset += trans_len;
764 if (count == 0) {
765 dst = (dst == data) ? mdata : data;
766 count = (dst == data) ? ns->lbasz : ns->lbaf.ms;
769 if (sge_len == offset) {
770 offset = 0;
771 sg_idx++;
776 static uint16_t nvme_map_addr_cmb(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
777 size_t len)
779 if (!len) {
780 return NVME_SUCCESS;
783 trace_pci_nvme_map_addr_cmb(addr, len);
785 if (!nvme_addr_is_cmb(n, addr) || !nvme_addr_is_cmb(n, addr + len - 1)) {
786 return NVME_DATA_TRAS_ERROR;
789 qemu_iovec_add(iov, nvme_addr_to_cmb(n, addr), len);
791 return NVME_SUCCESS;
794 static uint16_t nvme_map_addr_pmr(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
795 size_t len)
797 if (!len) {
798 return NVME_SUCCESS;
801 if (!nvme_addr_is_pmr(n, addr) || !nvme_addr_is_pmr(n, addr + len - 1)) {
802 return NVME_DATA_TRAS_ERROR;
805 qemu_iovec_add(iov, nvme_addr_to_pmr(n, addr), len);
807 return NVME_SUCCESS;
810 static uint16_t nvme_map_addr(NvmeCtrl *n, NvmeSg *sg, hwaddr addr, size_t len)
812 bool cmb = false, pmr = false;
814 if (!len) {
815 return NVME_SUCCESS;
818 trace_pci_nvme_map_addr(addr, len);
820 if (nvme_addr_is_iomem(n, addr)) {
821 return NVME_DATA_TRAS_ERROR;
824 if (nvme_addr_is_cmb(n, addr)) {
825 cmb = true;
826 } else if (nvme_addr_is_pmr(n, addr)) {
827 pmr = true;
830 if (cmb || pmr) {
831 if (sg->flags & NVME_SG_DMA) {
832 return NVME_INVALID_USE_OF_CMB | NVME_DNR;
835 if (sg->iov.niov + 1 > IOV_MAX) {
836 goto max_mappings_exceeded;
839 if (cmb) {
840 return nvme_map_addr_cmb(n, &sg->iov, addr, len);
841 } else {
842 return nvme_map_addr_pmr(n, &sg->iov, addr, len);
846 if (!(sg->flags & NVME_SG_DMA)) {
847 return NVME_INVALID_USE_OF_CMB | NVME_DNR;
850 if (sg->qsg.nsg + 1 > IOV_MAX) {
851 goto max_mappings_exceeded;
854 qemu_sglist_add(&sg->qsg, addr, len);
856 return NVME_SUCCESS;
858 max_mappings_exceeded:
859 NVME_GUEST_ERR(pci_nvme_ub_too_many_mappings,
860 "number of mappings exceed 1024");
861 return NVME_INTERNAL_DEV_ERROR | NVME_DNR;
864 static inline bool nvme_addr_is_dma(NvmeCtrl *n, hwaddr addr)
866 return !(nvme_addr_is_cmb(n, addr) || nvme_addr_is_pmr(n, addr));
869 static uint16_t nvme_map_prp(NvmeCtrl *n, NvmeSg *sg, uint64_t prp1,
870 uint64_t prp2, uint32_t len)
872 hwaddr trans_len = n->page_size - (prp1 % n->page_size);
873 trans_len = MIN(len, trans_len);
874 int num_prps = (len >> n->page_bits) + 1;
875 uint16_t status;
876 int ret;
878 trace_pci_nvme_map_prp(trans_len, len, prp1, prp2, num_prps);
880 nvme_sg_init(n, sg, nvme_addr_is_dma(n, prp1));
882 status = nvme_map_addr(n, sg, prp1, trans_len);
883 if (status) {
884 goto unmap;
887 len -= trans_len;
888 if (len) {
889 if (len > n->page_size) {
890 uint64_t prp_list[n->max_prp_ents];
891 uint32_t nents, prp_trans;
892 int i = 0;
895 * The first PRP list entry, pointed to by PRP2 may contain offset.
896 * Hence, we need to calculate the number of entries in based on
897 * that offset.
899 nents = (n->page_size - (prp2 & (n->page_size - 1))) >> 3;
900 prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);
901 ret = nvme_addr_read(n, prp2, (void *)prp_list, prp_trans);
902 if (ret) {
903 trace_pci_nvme_err_addr_read(prp2);
904 status = NVME_DATA_TRAS_ERROR;
905 goto unmap;
907 while (len != 0) {
908 uint64_t prp_ent = le64_to_cpu(prp_list[i]);
910 if (i == nents - 1 && len > n->page_size) {
911 if (unlikely(prp_ent & (n->page_size - 1))) {
912 trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
913 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
914 goto unmap;
917 i = 0;
918 nents = (len + n->page_size - 1) >> n->page_bits;
919 nents = MIN(nents, n->max_prp_ents);
920 prp_trans = nents * sizeof(uint64_t);
921 ret = nvme_addr_read(n, prp_ent, (void *)prp_list,
922 prp_trans);
923 if (ret) {
924 trace_pci_nvme_err_addr_read(prp_ent);
925 status = NVME_DATA_TRAS_ERROR;
926 goto unmap;
928 prp_ent = le64_to_cpu(prp_list[i]);
931 if (unlikely(prp_ent & (n->page_size - 1))) {
932 trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
933 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
934 goto unmap;
937 trans_len = MIN(len, n->page_size);
938 status = nvme_map_addr(n, sg, prp_ent, trans_len);
939 if (status) {
940 goto unmap;
943 len -= trans_len;
944 i++;
946 } else {
947 if (unlikely(prp2 & (n->page_size - 1))) {
948 trace_pci_nvme_err_invalid_prp2_align(prp2);
949 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
950 goto unmap;
952 status = nvme_map_addr(n, sg, prp2, len);
953 if (status) {
954 goto unmap;
959 return NVME_SUCCESS;
961 unmap:
962 nvme_sg_unmap(sg);
963 return status;
967 * Map 'nsgld' data descriptors from 'segment'. The function will subtract the
968 * number of bytes mapped in len.
970 static uint16_t nvme_map_sgl_data(NvmeCtrl *n, NvmeSg *sg,
971 NvmeSglDescriptor *segment, uint64_t nsgld,
972 size_t *len, NvmeCmd *cmd)
974 dma_addr_t addr, trans_len;
975 uint32_t dlen;
976 uint16_t status;
978 for (int i = 0; i < nsgld; i++) {
979 uint8_t type = NVME_SGL_TYPE(segment[i].type);
981 switch (type) {
982 case NVME_SGL_DESCR_TYPE_DATA_BLOCK:
983 break;
984 case NVME_SGL_DESCR_TYPE_SEGMENT:
985 case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
986 return NVME_INVALID_NUM_SGL_DESCRS | NVME_DNR;
987 default:
988 return NVME_SGL_DESCR_TYPE_INVALID | NVME_DNR;
991 dlen = le32_to_cpu(segment[i].len);
993 if (!dlen) {
994 continue;
997 if (*len == 0) {
999 * All data has been mapped, but the SGL contains additional
1000 * segments and/or descriptors. The controller might accept
1001 * ignoring the rest of the SGL.
1003 uint32_t sgls = le32_to_cpu(n->id_ctrl.sgls);
1004 if (sgls & NVME_CTRL_SGLS_EXCESS_LENGTH) {
1005 break;
1008 trace_pci_nvme_err_invalid_sgl_excess_length(dlen);
1009 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1012 trans_len = MIN(*len, dlen);
1014 addr = le64_to_cpu(segment[i].addr);
1016 if (UINT64_MAX - addr < dlen) {
1017 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1020 status = nvme_map_addr(n, sg, addr, trans_len);
1021 if (status) {
1022 return status;
1025 *len -= trans_len;
1028 return NVME_SUCCESS;
1031 static uint16_t nvme_map_sgl(NvmeCtrl *n, NvmeSg *sg, NvmeSglDescriptor sgl,
1032 size_t len, NvmeCmd *cmd)
1035 * Read the segment in chunks of 256 descriptors (one 4k page) to avoid
1036 * dynamically allocating a potentially huge SGL. The spec allows the SGL
1037 * to be larger (as in number of bytes required to describe the SGL
1038 * descriptors and segment chain) than the command transfer size, so it is
1039 * not bounded by MDTS.
1041 const int SEG_CHUNK_SIZE = 256;
1043 NvmeSglDescriptor segment[SEG_CHUNK_SIZE], *sgld, *last_sgld;
1044 uint64_t nsgld;
1045 uint32_t seg_len;
1046 uint16_t status;
1047 hwaddr addr;
1048 int ret;
1050 sgld = &sgl;
1051 addr = le64_to_cpu(sgl.addr);
1053 trace_pci_nvme_map_sgl(NVME_SGL_TYPE(sgl.type), len);
1055 nvme_sg_init(n, sg, nvme_addr_is_dma(n, addr));
1058 * If the entire transfer can be described with a single data block it can
1059 * be mapped directly.
1061 if (NVME_SGL_TYPE(sgl.type) == NVME_SGL_DESCR_TYPE_DATA_BLOCK) {
1062 status = nvme_map_sgl_data(n, sg, sgld, 1, &len, cmd);
1063 if (status) {
1064 goto unmap;
1067 goto out;
1070 for (;;) {
1071 switch (NVME_SGL_TYPE(sgld->type)) {
1072 case NVME_SGL_DESCR_TYPE_SEGMENT:
1073 case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
1074 break;
1075 default:
1076 return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
1079 seg_len = le32_to_cpu(sgld->len);
1081 /* check the length of the (Last) Segment descriptor */
1082 if (!seg_len || seg_len & 0xf) {
1083 return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
1086 if (UINT64_MAX - addr < seg_len) {
1087 return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1090 nsgld = seg_len / sizeof(NvmeSglDescriptor);
1092 while (nsgld > SEG_CHUNK_SIZE) {
1093 if (nvme_addr_read(n, addr, segment, sizeof(segment))) {
1094 trace_pci_nvme_err_addr_read(addr);
1095 status = NVME_DATA_TRAS_ERROR;
1096 goto unmap;
1099 status = nvme_map_sgl_data(n, sg, segment, SEG_CHUNK_SIZE,
1100 &len, cmd);
1101 if (status) {
1102 goto unmap;
1105 nsgld -= SEG_CHUNK_SIZE;
1106 addr += SEG_CHUNK_SIZE * sizeof(NvmeSglDescriptor);
1109 ret = nvme_addr_read(n, addr, segment, nsgld *
1110 sizeof(NvmeSglDescriptor));
1111 if (ret) {
1112 trace_pci_nvme_err_addr_read(addr);
1113 status = NVME_DATA_TRAS_ERROR;
1114 goto unmap;
1117 last_sgld = &segment[nsgld - 1];
1120 * If the segment ends with a Data Block, then we are done.
1122 if (NVME_SGL_TYPE(last_sgld->type) == NVME_SGL_DESCR_TYPE_DATA_BLOCK) {
1123 status = nvme_map_sgl_data(n, sg, segment, nsgld, &len, cmd);
1124 if (status) {
1125 goto unmap;
1128 goto out;
1132 * If the last descriptor was not a Data Block, then the current
1133 * segment must not be a Last Segment.
1135 if (NVME_SGL_TYPE(sgld->type) == NVME_SGL_DESCR_TYPE_LAST_SEGMENT) {
1136 status = NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
1137 goto unmap;
1140 sgld = last_sgld;
1141 addr = le64_to_cpu(sgld->addr);
1144 * Do not map the last descriptor; it will be a Segment or Last Segment
1145 * descriptor and is handled by the next iteration.
1147 status = nvme_map_sgl_data(n, sg, segment, nsgld - 1, &len, cmd);
1148 if (status) {
1149 goto unmap;
1153 out:
1154 /* if there is any residual left in len, the SGL was too short */
1155 if (len) {
1156 status = NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1157 goto unmap;
1160 return NVME_SUCCESS;
1162 unmap:
1163 nvme_sg_unmap(sg);
1164 return status;
1167 uint16_t nvme_map_dptr(NvmeCtrl *n, NvmeSg *sg, size_t len,
1168 NvmeCmd *cmd)
1170 uint64_t prp1, prp2;
1172 switch (NVME_CMD_FLAGS_PSDT(cmd->flags)) {
1173 case NVME_PSDT_PRP:
1174 prp1 = le64_to_cpu(cmd->dptr.prp1);
1175 prp2 = le64_to_cpu(cmd->dptr.prp2);
1177 return nvme_map_prp(n, sg, prp1, prp2, len);
1178 case NVME_PSDT_SGL_MPTR_CONTIGUOUS:
1179 case NVME_PSDT_SGL_MPTR_SGL:
1180 return nvme_map_sgl(n, sg, cmd->dptr.sgl, len, cmd);
1181 default:
1182 return NVME_INVALID_FIELD;
1186 static uint16_t nvme_map_mptr(NvmeCtrl *n, NvmeSg *sg, size_t len,
1187 NvmeCmd *cmd)
1189 int psdt = NVME_CMD_FLAGS_PSDT(cmd->flags);
1190 hwaddr mptr = le64_to_cpu(cmd->mptr);
1191 uint16_t status;
1193 if (psdt == NVME_PSDT_SGL_MPTR_SGL) {
1194 NvmeSglDescriptor sgl;
1196 if (nvme_addr_read(n, mptr, &sgl, sizeof(sgl))) {
1197 return NVME_DATA_TRAS_ERROR;
1200 status = nvme_map_sgl(n, sg, sgl, len, cmd);
1201 if (status && (status & 0x7ff) == NVME_DATA_SGL_LEN_INVALID) {
1202 status = NVME_MD_SGL_LEN_INVALID | NVME_DNR;
1205 return status;
1208 nvme_sg_init(n, sg, nvme_addr_is_dma(n, mptr));
1209 status = nvme_map_addr(n, sg, mptr, len);
1210 if (status) {
1211 nvme_sg_unmap(sg);
1214 return status;
1217 static uint16_t nvme_map_data(NvmeCtrl *n, uint32_t nlb, NvmeRequest *req)
1219 NvmeNamespace *ns = req->ns;
1220 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1221 bool pi = !!NVME_ID_NS_DPS_TYPE(ns->id_ns.dps);
1222 bool pract = !!(le16_to_cpu(rw->control) & NVME_RW_PRINFO_PRACT);
1223 size_t len = nvme_l2b(ns, nlb);
1224 uint16_t status;
1226 if (nvme_ns_ext(ns) &&
1227 !(pi && pract && ns->lbaf.ms == nvme_pi_tuple_size(ns))) {
1228 NvmeSg sg;
1230 len += nvme_m2b(ns, nlb);
1232 status = nvme_map_dptr(n, &sg, len, &req->cmd);
1233 if (status) {
1234 return status;
1237 nvme_sg_init(n, &req->sg, sg.flags & NVME_SG_DMA);
1238 nvme_sg_split(&sg, ns, &req->sg, NULL);
1239 nvme_sg_unmap(&sg);
1241 return NVME_SUCCESS;
1244 return nvme_map_dptr(n, &req->sg, len, &req->cmd);
1247 static uint16_t nvme_map_mdata(NvmeCtrl *n, uint32_t nlb, NvmeRequest *req)
1249 NvmeNamespace *ns = req->ns;
1250 size_t len = nvme_m2b(ns, nlb);
1251 uint16_t status;
1253 if (nvme_ns_ext(ns)) {
1254 NvmeSg sg;
1256 len += nvme_l2b(ns, nlb);
1258 status = nvme_map_dptr(n, &sg, len, &req->cmd);
1259 if (status) {
1260 return status;
1263 nvme_sg_init(n, &req->sg, sg.flags & NVME_SG_DMA);
1264 nvme_sg_split(&sg, ns, NULL, &req->sg);
1265 nvme_sg_unmap(&sg);
1267 return NVME_SUCCESS;
1270 return nvme_map_mptr(n, &req->sg, len, &req->cmd);
1273 static uint16_t nvme_tx_interleaved(NvmeCtrl *n, NvmeSg *sg, uint8_t *ptr,
1274 uint32_t len, uint32_t bytes,
1275 int32_t skip_bytes, int64_t offset,
1276 NvmeTxDirection dir)
1278 hwaddr addr;
1279 uint32_t trans_len, count = bytes;
1280 bool dma = sg->flags & NVME_SG_DMA;
1281 int64_t sge_len;
1282 int sg_idx = 0;
1283 int ret;
1285 assert(sg->flags & NVME_SG_ALLOC);
1287 while (len) {
1288 sge_len = dma ? sg->qsg.sg[sg_idx].len : sg->iov.iov[sg_idx].iov_len;
1290 if (sge_len - offset < 0) {
1291 offset -= sge_len;
1292 sg_idx++;
1293 continue;
1296 if (sge_len == offset) {
1297 offset = 0;
1298 sg_idx++;
1299 continue;
1302 trans_len = MIN(len, count);
1303 trans_len = MIN(trans_len, sge_len - offset);
1305 if (dma) {
1306 addr = sg->qsg.sg[sg_idx].base + offset;
1307 } else {
1308 addr = (hwaddr)(uintptr_t)sg->iov.iov[sg_idx].iov_base + offset;
1311 if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1312 ret = nvme_addr_read(n, addr, ptr, trans_len);
1313 } else {
1314 ret = nvme_addr_write(n, addr, ptr, trans_len);
1317 if (ret) {
1318 return NVME_DATA_TRAS_ERROR;
1321 ptr += trans_len;
1322 len -= trans_len;
1323 count -= trans_len;
1324 offset += trans_len;
1326 if (count == 0) {
1327 count = bytes;
1328 offset += skip_bytes;
1332 return NVME_SUCCESS;
1335 static uint16_t nvme_tx(NvmeCtrl *n, NvmeSg *sg, void *ptr, uint32_t len,
1336 NvmeTxDirection dir)
1338 assert(sg->flags & NVME_SG_ALLOC);
1340 if (sg->flags & NVME_SG_DMA) {
1341 const MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
1342 dma_addr_t residual;
1344 if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1345 dma_buf_write(ptr, len, &residual, &sg->qsg, attrs);
1346 } else {
1347 dma_buf_read(ptr, len, &residual, &sg->qsg, attrs);
1350 if (unlikely(residual)) {
1351 trace_pci_nvme_err_invalid_dma();
1352 return NVME_INVALID_FIELD | NVME_DNR;
1354 } else {
1355 size_t bytes;
1357 if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1358 bytes = qemu_iovec_to_buf(&sg->iov, 0, ptr, len);
1359 } else {
1360 bytes = qemu_iovec_from_buf(&sg->iov, 0, ptr, len);
1363 if (unlikely(bytes != len)) {
1364 trace_pci_nvme_err_invalid_dma();
1365 return NVME_INVALID_FIELD | NVME_DNR;
1369 return NVME_SUCCESS;
1372 static inline uint16_t nvme_c2h(NvmeCtrl *n, void *ptr, uint32_t len,
1373 NvmeRequest *req)
1375 uint16_t status;
1377 status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
1378 if (status) {
1379 return status;
1382 return nvme_tx(n, &req->sg, ptr, len, NVME_TX_DIRECTION_FROM_DEVICE);
1385 static inline uint16_t nvme_h2c(NvmeCtrl *n, void *ptr, uint32_t len,
1386 NvmeRequest *req)
1388 uint16_t status;
1390 status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
1391 if (status) {
1392 return status;
1395 return nvme_tx(n, &req->sg, ptr, len, NVME_TX_DIRECTION_TO_DEVICE);
1398 uint16_t nvme_bounce_data(NvmeCtrl *n, void *ptr, uint32_t len,
1399 NvmeTxDirection dir, NvmeRequest *req)
1401 NvmeNamespace *ns = req->ns;
1402 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1403 bool pi = !!NVME_ID_NS_DPS_TYPE(ns->id_ns.dps);
1404 bool pract = !!(le16_to_cpu(rw->control) & NVME_RW_PRINFO_PRACT);
1406 if (nvme_ns_ext(ns) &&
1407 !(pi && pract && ns->lbaf.ms == nvme_pi_tuple_size(ns))) {
1408 return nvme_tx_interleaved(n, &req->sg, ptr, len, ns->lbasz,
1409 ns->lbaf.ms, 0, dir);
1412 return nvme_tx(n, &req->sg, ptr, len, dir);
1415 uint16_t nvme_bounce_mdata(NvmeCtrl *n, void *ptr, uint32_t len,
1416 NvmeTxDirection dir, NvmeRequest *req)
1418 NvmeNamespace *ns = req->ns;
1419 uint16_t status;
1421 if (nvme_ns_ext(ns)) {
1422 return nvme_tx_interleaved(n, &req->sg, ptr, len, ns->lbaf.ms,
1423 ns->lbasz, ns->lbasz, dir);
1426 nvme_sg_unmap(&req->sg);
1428 status = nvme_map_mptr(n, &req->sg, len, &req->cmd);
1429 if (status) {
1430 return status;
1433 return nvme_tx(n, &req->sg, ptr, len, dir);
1436 static inline void nvme_blk_read(BlockBackend *blk, int64_t offset,
1437 uint32_t align, BlockCompletionFunc *cb,
1438 NvmeRequest *req)
1440 assert(req->sg.flags & NVME_SG_ALLOC);
1442 if (req->sg.flags & NVME_SG_DMA) {
1443 req->aiocb = dma_blk_read(blk, &req->sg.qsg, offset, align, cb, req);
1444 } else {
1445 req->aiocb = blk_aio_preadv(blk, offset, &req->sg.iov, 0, cb, req);
1449 static inline void nvme_blk_write(BlockBackend *blk, int64_t offset,
1450 uint32_t align, BlockCompletionFunc *cb,
1451 NvmeRequest *req)
1453 assert(req->sg.flags & NVME_SG_ALLOC);
1455 if (req->sg.flags & NVME_SG_DMA) {
1456 req->aiocb = dma_blk_write(blk, &req->sg.qsg, offset, align, cb, req);
1457 } else {
1458 req->aiocb = blk_aio_pwritev(blk, offset, &req->sg.iov, 0, cb, req);
1462 static void nvme_update_cq_eventidx(const NvmeCQueue *cq)
1464 uint32_t v = cpu_to_le32(cq->head);
1466 trace_pci_nvme_update_cq_eventidx(cq->cqid, cq->head);
1468 pci_dma_write(PCI_DEVICE(cq->ctrl), cq->ei_addr, &v, sizeof(v));
1471 static void nvme_update_cq_head(NvmeCQueue *cq)
1473 uint32_t v;
1475 pci_dma_read(PCI_DEVICE(cq->ctrl), cq->db_addr, &v, sizeof(v));
1477 cq->head = le32_to_cpu(v);
1479 trace_pci_nvme_update_cq_head(cq->cqid, cq->head);
1482 static void nvme_post_cqes(void *opaque)
1484 NvmeCQueue *cq = opaque;
1485 NvmeCtrl *n = cq->ctrl;
1486 NvmeRequest *req, *next;
1487 bool pending = cq->head != cq->tail;
1488 int ret;
1490 QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {
1491 NvmeSQueue *sq;
1492 hwaddr addr;
1494 if (n->dbbuf_enabled) {
1495 nvme_update_cq_eventidx(cq);
1496 nvme_update_cq_head(cq);
1499 if (nvme_cq_full(cq)) {
1500 break;
1503 sq = req->sq;
1504 req->cqe.status = cpu_to_le16((req->status << 1) | cq->phase);
1505 req->cqe.sq_id = cpu_to_le16(sq->sqid);
1506 req->cqe.sq_head = cpu_to_le16(sq->head);
1507 addr = cq->dma_addr + cq->tail * n->cqe_size;
1508 ret = pci_dma_write(PCI_DEVICE(n), addr, (void *)&req->cqe,
1509 sizeof(req->cqe));
1510 if (ret) {
1511 trace_pci_nvme_err_addr_write(addr);
1512 trace_pci_nvme_err_cfs();
1513 stl_le_p(&n->bar.csts, NVME_CSTS_FAILED);
1514 break;
1516 QTAILQ_REMOVE(&cq->req_list, req, entry);
1517 nvme_inc_cq_tail(cq);
1518 nvme_sg_unmap(&req->sg);
1519 QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);
1521 if (cq->tail != cq->head) {
1522 if (cq->irq_enabled && !pending) {
1523 n->cq_pending++;
1526 nvme_irq_assert(n, cq);
1530 static void nvme_enqueue_req_completion(NvmeCQueue *cq, NvmeRequest *req)
1532 assert(cq->cqid == req->sq->cqid);
1533 trace_pci_nvme_enqueue_req_completion(nvme_cid(req), cq->cqid,
1534 le32_to_cpu(req->cqe.result),
1535 le32_to_cpu(req->cqe.dw1),
1536 req->status);
1538 if (req->status) {
1539 trace_pci_nvme_err_req_status(nvme_cid(req), nvme_nsid(req->ns),
1540 req->status, req->cmd.opcode);
1543 QTAILQ_REMOVE(&req->sq->out_req_list, req, entry);
1544 QTAILQ_INSERT_TAIL(&cq->req_list, req, entry);
1546 qemu_bh_schedule(cq->bh);
1549 static void nvme_process_aers(void *opaque)
1551 NvmeCtrl *n = opaque;
1552 NvmeAsyncEvent *event, *next;
1554 trace_pci_nvme_process_aers(n->aer_queued);
1556 QTAILQ_FOREACH_SAFE(event, &n->aer_queue, entry, next) {
1557 NvmeRequest *req;
1558 NvmeAerResult *result;
1560 /* can't post cqe if there is nothing to complete */
1561 if (!n->outstanding_aers) {
1562 trace_pci_nvme_no_outstanding_aers();
1563 break;
1566 /* ignore if masked (cqe posted, but event not cleared) */
1567 if (n->aer_mask & (1 << event->result.event_type)) {
1568 trace_pci_nvme_aer_masked(event->result.event_type, n->aer_mask);
1569 continue;
1572 QTAILQ_REMOVE(&n->aer_queue, event, entry);
1573 n->aer_queued--;
1575 n->aer_mask |= 1 << event->result.event_type;
1576 n->outstanding_aers--;
1578 req = n->aer_reqs[n->outstanding_aers];
1580 result = (NvmeAerResult *) &req->cqe.result;
1581 result->event_type = event->result.event_type;
1582 result->event_info = event->result.event_info;
1583 result->log_page = event->result.log_page;
1584 g_free(event);
1586 trace_pci_nvme_aer_post_cqe(result->event_type, result->event_info,
1587 result->log_page);
1589 nvme_enqueue_req_completion(&n->admin_cq, req);
1593 static void nvme_enqueue_event(NvmeCtrl *n, uint8_t event_type,
1594 uint8_t event_info, uint8_t log_page)
1596 NvmeAsyncEvent *event;
1598 trace_pci_nvme_enqueue_event(event_type, event_info, log_page);
1600 if (n->aer_queued == n->params.aer_max_queued) {
1601 trace_pci_nvme_enqueue_event_noqueue(n->aer_queued);
1602 return;
1605 event = g_new(NvmeAsyncEvent, 1);
1606 event->result = (NvmeAerResult) {
1607 .event_type = event_type,
1608 .event_info = event_info,
1609 .log_page = log_page,
1612 QTAILQ_INSERT_TAIL(&n->aer_queue, event, entry);
1613 n->aer_queued++;
1615 nvme_process_aers(n);
1618 static void nvme_smart_event(NvmeCtrl *n, uint8_t event)
1620 uint8_t aer_info;
1622 /* Ref SPEC <Asynchronous Event Information 0x2013 SMART / Health Status> */
1623 if (!(NVME_AEC_SMART(n->features.async_config) & event)) {
1624 return;
1627 switch (event) {
1628 case NVME_SMART_SPARE:
1629 aer_info = NVME_AER_INFO_SMART_SPARE_THRESH;
1630 break;
1631 case NVME_SMART_TEMPERATURE:
1632 aer_info = NVME_AER_INFO_SMART_TEMP_THRESH;
1633 break;
1634 case NVME_SMART_RELIABILITY:
1635 case NVME_SMART_MEDIA_READ_ONLY:
1636 case NVME_SMART_FAILED_VOLATILE_MEDIA:
1637 case NVME_SMART_PMR_UNRELIABLE:
1638 aer_info = NVME_AER_INFO_SMART_RELIABILITY;
1639 break;
1640 default:
1641 return;
1644 nvme_enqueue_event(n, NVME_AER_TYPE_SMART, aer_info, NVME_LOG_SMART_INFO);
1647 static void nvme_clear_events(NvmeCtrl *n, uint8_t event_type)
1649 n->aer_mask &= ~(1 << event_type);
1650 if (!QTAILQ_EMPTY(&n->aer_queue)) {
1651 nvme_process_aers(n);
1655 static inline uint16_t nvme_check_mdts(NvmeCtrl *n, size_t len)
1657 uint8_t mdts = n->params.mdts;
1659 if (mdts && len > n->page_size << mdts) {
1660 trace_pci_nvme_err_mdts(len);
1661 return NVME_INVALID_FIELD | NVME_DNR;
1664 return NVME_SUCCESS;
1667 static inline uint16_t nvme_check_bounds(NvmeNamespace *ns, uint64_t slba,
1668 uint32_t nlb)
1670 uint64_t nsze = le64_to_cpu(ns->id_ns.nsze);
1672 if (unlikely(UINT64_MAX - slba < nlb || slba + nlb > nsze)) {
1673 trace_pci_nvme_err_invalid_lba_range(slba, nlb, nsze);
1674 return NVME_LBA_RANGE | NVME_DNR;
1677 return NVME_SUCCESS;
1680 static int nvme_block_status_all(NvmeNamespace *ns, uint64_t slba,
1681 uint32_t nlb, int flags)
1683 BlockDriverState *bs = blk_bs(ns->blkconf.blk);
1685 int64_t pnum = 0, bytes = nvme_l2b(ns, nlb);
1686 int64_t offset = nvme_l2b(ns, slba);
1687 int ret;
1690 * `pnum` holds the number of bytes after offset that shares the same
1691 * allocation status as the byte at offset. If `pnum` is different from
1692 * `bytes`, we should check the allocation status of the next range and
1693 * continue this until all bytes have been checked.
1695 do {
1696 bytes -= pnum;
1698 ret = bdrv_block_status(bs, offset, bytes, &pnum, NULL, NULL);
1699 if (ret < 0) {
1700 return ret;
1704 trace_pci_nvme_block_status(offset, bytes, pnum, ret,
1705 !!(ret & BDRV_BLOCK_ZERO));
1707 if (!(ret & flags)) {
1708 return 1;
1711 offset += pnum;
1712 } while (pnum != bytes);
1714 return 0;
1717 static uint16_t nvme_check_dulbe(NvmeNamespace *ns, uint64_t slba,
1718 uint32_t nlb)
1720 int ret;
1721 Error *err = NULL;
1723 ret = nvme_block_status_all(ns, slba, nlb, BDRV_BLOCK_DATA);
1724 if (ret) {
1725 if (ret < 0) {
1726 error_setg_errno(&err, -ret, "unable to get block status");
1727 error_report_err(err);
1729 return NVME_INTERNAL_DEV_ERROR;
1732 return NVME_DULB;
1735 return NVME_SUCCESS;
1738 static void nvme_aio_err(NvmeRequest *req, int ret)
1740 uint16_t status = NVME_SUCCESS;
1741 Error *local_err = NULL;
1743 switch (req->cmd.opcode) {
1744 case NVME_CMD_READ:
1745 status = NVME_UNRECOVERED_READ;
1746 break;
1747 case NVME_CMD_FLUSH:
1748 case NVME_CMD_WRITE:
1749 case NVME_CMD_WRITE_ZEROES:
1750 case NVME_CMD_ZONE_APPEND:
1751 status = NVME_WRITE_FAULT;
1752 break;
1753 default:
1754 status = NVME_INTERNAL_DEV_ERROR;
1755 break;
1758 trace_pci_nvme_err_aio(nvme_cid(req), strerror(-ret), status);
1760 error_setg_errno(&local_err, -ret, "aio failed");
1761 error_report_err(local_err);
1764 * Set the command status code to the first encountered error but allow a
1765 * subsequent Internal Device Error to trump it.
1767 if (req->status && status != NVME_INTERNAL_DEV_ERROR) {
1768 return;
1771 req->status = status;
1774 static inline uint32_t nvme_zone_idx(NvmeNamespace *ns, uint64_t slba)
1776 return ns->zone_size_log2 > 0 ? slba >> ns->zone_size_log2 :
1777 slba / ns->zone_size;
1780 static inline NvmeZone *nvme_get_zone_by_slba(NvmeNamespace *ns, uint64_t slba)
1782 uint32_t zone_idx = nvme_zone_idx(ns, slba);
1784 if (zone_idx >= ns->num_zones) {
1785 return NULL;
1788 return &ns->zone_array[zone_idx];
1791 static uint16_t nvme_check_zone_state_for_write(NvmeZone *zone)
1793 uint64_t zslba = zone->d.zslba;
1795 switch (nvme_get_zone_state(zone)) {
1796 case NVME_ZONE_STATE_EMPTY:
1797 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1798 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1799 case NVME_ZONE_STATE_CLOSED:
1800 return NVME_SUCCESS;
1801 case NVME_ZONE_STATE_FULL:
1802 trace_pci_nvme_err_zone_is_full(zslba);
1803 return NVME_ZONE_FULL;
1804 case NVME_ZONE_STATE_OFFLINE:
1805 trace_pci_nvme_err_zone_is_offline(zslba);
1806 return NVME_ZONE_OFFLINE;
1807 case NVME_ZONE_STATE_READ_ONLY:
1808 trace_pci_nvme_err_zone_is_read_only(zslba);
1809 return NVME_ZONE_READ_ONLY;
1810 default:
1811 assert(false);
1814 return NVME_INTERNAL_DEV_ERROR;
1817 static uint16_t nvme_check_zone_write(NvmeNamespace *ns, NvmeZone *zone,
1818 uint64_t slba, uint32_t nlb)
1820 uint64_t zcap = nvme_zone_wr_boundary(zone);
1821 uint16_t status;
1823 status = nvme_check_zone_state_for_write(zone);
1824 if (status) {
1825 return status;
1828 if (zone->d.za & NVME_ZA_ZRWA_VALID) {
1829 uint64_t ezrwa = zone->w_ptr + 2 * ns->zns.zrwas;
1831 if (slba < zone->w_ptr || slba + nlb > ezrwa) {
1832 trace_pci_nvme_err_zone_invalid_write(slba, zone->w_ptr);
1833 return NVME_ZONE_INVALID_WRITE;
1835 } else {
1836 if (unlikely(slba != zone->w_ptr)) {
1837 trace_pci_nvme_err_write_not_at_wp(slba, zone->d.zslba,
1838 zone->w_ptr);
1839 return NVME_ZONE_INVALID_WRITE;
1843 if (unlikely((slba + nlb) > zcap)) {
1844 trace_pci_nvme_err_zone_boundary(slba, nlb, zcap);
1845 return NVME_ZONE_BOUNDARY_ERROR;
1848 return NVME_SUCCESS;
1851 static uint16_t nvme_check_zone_state_for_read(NvmeZone *zone)
1853 switch (nvme_get_zone_state(zone)) {
1854 case NVME_ZONE_STATE_EMPTY:
1855 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1856 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1857 case NVME_ZONE_STATE_FULL:
1858 case NVME_ZONE_STATE_CLOSED:
1859 case NVME_ZONE_STATE_READ_ONLY:
1860 return NVME_SUCCESS;
1861 case NVME_ZONE_STATE_OFFLINE:
1862 trace_pci_nvme_err_zone_is_offline(zone->d.zslba);
1863 return NVME_ZONE_OFFLINE;
1864 default:
1865 assert(false);
1868 return NVME_INTERNAL_DEV_ERROR;
1871 static uint16_t nvme_check_zone_read(NvmeNamespace *ns, uint64_t slba,
1872 uint32_t nlb)
1874 NvmeZone *zone;
1875 uint64_t bndry, end;
1876 uint16_t status;
1878 zone = nvme_get_zone_by_slba(ns, slba);
1879 assert(zone);
1881 bndry = nvme_zone_rd_boundary(ns, zone);
1882 end = slba + nlb;
1884 status = nvme_check_zone_state_for_read(zone);
1885 if (status) {
1887 } else if (unlikely(end > bndry)) {
1888 if (!ns->params.cross_zone_read) {
1889 status = NVME_ZONE_BOUNDARY_ERROR;
1890 } else {
1892 * Read across zone boundary - check that all subsequent
1893 * zones that are being read have an appropriate state.
1895 do {
1896 zone++;
1897 status = nvme_check_zone_state_for_read(zone);
1898 if (status) {
1899 break;
1901 } while (end > nvme_zone_rd_boundary(ns, zone));
1905 return status;
1908 static uint16_t nvme_zrm_finish(NvmeNamespace *ns, NvmeZone *zone)
1910 switch (nvme_get_zone_state(zone)) {
1911 case NVME_ZONE_STATE_FULL:
1912 return NVME_SUCCESS;
1914 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1915 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1916 nvme_aor_dec_open(ns);
1917 /* fallthrough */
1918 case NVME_ZONE_STATE_CLOSED:
1919 nvme_aor_dec_active(ns);
1921 if (zone->d.za & NVME_ZA_ZRWA_VALID) {
1922 zone->d.za &= ~NVME_ZA_ZRWA_VALID;
1923 if (ns->params.numzrwa) {
1924 ns->zns.numzrwa++;
1928 /* fallthrough */
1929 case NVME_ZONE_STATE_EMPTY:
1930 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_FULL);
1931 return NVME_SUCCESS;
1933 default:
1934 return NVME_ZONE_INVAL_TRANSITION;
1938 static uint16_t nvme_zrm_close(NvmeNamespace *ns, NvmeZone *zone)
1940 switch (nvme_get_zone_state(zone)) {
1941 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1942 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1943 nvme_aor_dec_open(ns);
1944 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
1945 /* fall through */
1946 case NVME_ZONE_STATE_CLOSED:
1947 return NVME_SUCCESS;
1949 default:
1950 return NVME_ZONE_INVAL_TRANSITION;
1954 static uint16_t nvme_zrm_reset(NvmeNamespace *ns, NvmeZone *zone)
1956 switch (nvme_get_zone_state(zone)) {
1957 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1958 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1959 nvme_aor_dec_open(ns);
1960 /* fallthrough */
1961 case NVME_ZONE_STATE_CLOSED:
1962 nvme_aor_dec_active(ns);
1964 if (zone->d.za & NVME_ZA_ZRWA_VALID) {
1965 if (ns->params.numzrwa) {
1966 ns->zns.numzrwa++;
1970 /* fallthrough */
1971 case NVME_ZONE_STATE_FULL:
1972 zone->w_ptr = zone->d.zslba;
1973 zone->d.wp = zone->w_ptr;
1974 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EMPTY);
1975 /* fallthrough */
1976 case NVME_ZONE_STATE_EMPTY:
1977 return NVME_SUCCESS;
1979 default:
1980 return NVME_ZONE_INVAL_TRANSITION;
1984 static void nvme_zrm_auto_transition_zone(NvmeNamespace *ns)
1986 NvmeZone *zone;
1988 if (ns->params.max_open_zones &&
1989 ns->nr_open_zones == ns->params.max_open_zones) {
1990 zone = QTAILQ_FIRST(&ns->imp_open_zones);
1991 if (zone) {
1993 * Automatically close this implicitly open zone.
1995 QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
1996 nvme_zrm_close(ns, zone);
2001 enum {
2002 NVME_ZRM_AUTO = 1 << 0,
2003 NVME_ZRM_ZRWA = 1 << 1,
2006 static uint16_t nvme_zrm_open_flags(NvmeCtrl *n, NvmeNamespace *ns,
2007 NvmeZone *zone, int flags)
2009 int act = 0;
2010 uint16_t status;
2012 switch (nvme_get_zone_state(zone)) {
2013 case NVME_ZONE_STATE_EMPTY:
2014 act = 1;
2016 /* fallthrough */
2018 case NVME_ZONE_STATE_CLOSED:
2019 if (n->params.auto_transition_zones) {
2020 nvme_zrm_auto_transition_zone(ns);
2022 status = nvme_zns_check_resources(ns, act, 1,
2023 (flags & NVME_ZRM_ZRWA) ? 1 : 0);
2024 if (status) {
2025 return status;
2028 if (act) {
2029 nvme_aor_inc_active(ns);
2032 nvme_aor_inc_open(ns);
2034 if (flags & NVME_ZRM_AUTO) {
2035 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_IMPLICITLY_OPEN);
2036 return NVME_SUCCESS;
2039 /* fallthrough */
2041 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
2042 if (flags & NVME_ZRM_AUTO) {
2043 return NVME_SUCCESS;
2046 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EXPLICITLY_OPEN);
2048 /* fallthrough */
2050 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
2051 if (flags & NVME_ZRM_ZRWA) {
2052 ns->zns.numzrwa--;
2054 zone->d.za |= NVME_ZA_ZRWA_VALID;
2057 return NVME_SUCCESS;
2059 default:
2060 return NVME_ZONE_INVAL_TRANSITION;
2064 static inline uint16_t nvme_zrm_auto(NvmeCtrl *n, NvmeNamespace *ns,
2065 NvmeZone *zone)
2067 return nvme_zrm_open_flags(n, ns, zone, NVME_ZRM_AUTO);
2070 static void nvme_advance_zone_wp(NvmeNamespace *ns, NvmeZone *zone,
2071 uint32_t nlb)
2073 zone->d.wp += nlb;
2075 if (zone->d.wp == nvme_zone_wr_boundary(zone)) {
2076 nvme_zrm_finish(ns, zone);
2080 static void nvme_zoned_zrwa_implicit_flush(NvmeNamespace *ns, NvmeZone *zone,
2081 uint32_t nlbc)
2083 uint16_t nzrwafgs = DIV_ROUND_UP(nlbc, ns->zns.zrwafg);
2085 nlbc = nzrwafgs * ns->zns.zrwafg;
2087 trace_pci_nvme_zoned_zrwa_implicit_flush(zone->d.zslba, nlbc);
2089 zone->w_ptr += nlbc;
2091 nvme_advance_zone_wp(ns, zone, nlbc);
2094 static void nvme_finalize_zoned_write(NvmeNamespace *ns, NvmeRequest *req)
2096 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2097 NvmeZone *zone;
2098 uint64_t slba;
2099 uint32_t nlb;
2101 slba = le64_to_cpu(rw->slba);
2102 nlb = le16_to_cpu(rw->nlb) + 1;
2103 zone = nvme_get_zone_by_slba(ns, slba);
2104 assert(zone);
2106 if (zone->d.za & NVME_ZA_ZRWA_VALID) {
2107 uint64_t ezrwa = zone->w_ptr + ns->zns.zrwas - 1;
2108 uint64_t elba = slba + nlb - 1;
2110 if (elba > ezrwa) {
2111 nvme_zoned_zrwa_implicit_flush(ns, zone, elba - ezrwa);
2114 return;
2117 nvme_advance_zone_wp(ns, zone, nlb);
2120 static inline bool nvme_is_write(NvmeRequest *req)
2122 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2124 return rw->opcode == NVME_CMD_WRITE ||
2125 rw->opcode == NVME_CMD_ZONE_APPEND ||
2126 rw->opcode == NVME_CMD_WRITE_ZEROES;
2129 static AioContext *nvme_get_aio_context(BlockAIOCB *acb)
2131 return qemu_get_aio_context();
2134 static void nvme_misc_cb(void *opaque, int ret)
2136 NvmeRequest *req = opaque;
2138 trace_pci_nvme_misc_cb(nvme_cid(req));
2140 if (ret) {
2141 nvme_aio_err(req, ret);
2144 nvme_enqueue_req_completion(nvme_cq(req), req);
2147 void nvme_rw_complete_cb(void *opaque, int ret)
2149 NvmeRequest *req = opaque;
2150 NvmeNamespace *ns = req->ns;
2151 BlockBackend *blk = ns->blkconf.blk;
2152 BlockAcctCookie *acct = &req->acct;
2153 BlockAcctStats *stats = blk_get_stats(blk);
2155 trace_pci_nvme_rw_complete_cb(nvme_cid(req), blk_name(blk));
2157 if (ret) {
2158 block_acct_failed(stats, acct);
2159 nvme_aio_err(req, ret);
2160 } else {
2161 block_acct_done(stats, acct);
2164 if (ns->params.zoned && nvme_is_write(req)) {
2165 nvme_finalize_zoned_write(ns, req);
2168 nvme_enqueue_req_completion(nvme_cq(req), req);
2171 static void nvme_rw_cb(void *opaque, int ret)
2173 NvmeRequest *req = opaque;
2174 NvmeNamespace *ns = req->ns;
2176 BlockBackend *blk = ns->blkconf.blk;
2178 trace_pci_nvme_rw_cb(nvme_cid(req), blk_name(blk));
2180 if (ret) {
2181 goto out;
2184 if (ns->lbaf.ms) {
2185 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2186 uint64_t slba = le64_to_cpu(rw->slba);
2187 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
2188 uint64_t offset = nvme_moff(ns, slba);
2190 if (req->cmd.opcode == NVME_CMD_WRITE_ZEROES) {
2191 size_t mlen = nvme_m2b(ns, nlb);
2193 req->aiocb = blk_aio_pwrite_zeroes(blk, offset, mlen,
2194 BDRV_REQ_MAY_UNMAP,
2195 nvme_rw_complete_cb, req);
2196 return;
2199 if (nvme_ns_ext(ns) || req->cmd.mptr) {
2200 uint16_t status;
2202 nvme_sg_unmap(&req->sg);
2203 status = nvme_map_mdata(nvme_ctrl(req), nlb, req);
2204 if (status) {
2205 ret = -EFAULT;
2206 goto out;
2209 if (req->cmd.opcode == NVME_CMD_READ) {
2210 return nvme_blk_read(blk, offset, 1, nvme_rw_complete_cb, req);
2213 return nvme_blk_write(blk, offset, 1, nvme_rw_complete_cb, req);
2217 out:
2218 nvme_rw_complete_cb(req, ret);
2221 static void nvme_verify_cb(void *opaque, int ret)
2223 NvmeBounceContext *ctx = opaque;
2224 NvmeRequest *req = ctx->req;
2225 NvmeNamespace *ns = req->ns;
2226 BlockBackend *blk = ns->blkconf.blk;
2227 BlockAcctCookie *acct = &req->acct;
2228 BlockAcctStats *stats = blk_get_stats(blk);
2229 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2230 uint64_t slba = le64_to_cpu(rw->slba);
2231 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2232 uint16_t apptag = le16_to_cpu(rw->apptag);
2233 uint16_t appmask = le16_to_cpu(rw->appmask);
2234 uint64_t reftag = le32_to_cpu(rw->reftag);
2235 uint64_t cdw3 = le32_to_cpu(rw->cdw3);
2236 uint16_t status;
2238 reftag |= cdw3 << 32;
2240 trace_pci_nvme_verify_cb(nvme_cid(req), prinfo, apptag, appmask, reftag);
2242 if (ret) {
2243 block_acct_failed(stats, acct);
2244 nvme_aio_err(req, ret);
2245 goto out;
2248 block_acct_done(stats, acct);
2250 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2251 status = nvme_dif_mangle_mdata(ns, ctx->mdata.bounce,
2252 ctx->mdata.iov.size, slba);
2253 if (status) {
2254 req->status = status;
2255 goto out;
2258 req->status = nvme_dif_check(ns, ctx->data.bounce, ctx->data.iov.size,
2259 ctx->mdata.bounce, ctx->mdata.iov.size,
2260 prinfo, slba, apptag, appmask, &reftag);
2263 out:
2264 qemu_iovec_destroy(&ctx->data.iov);
2265 g_free(ctx->data.bounce);
2267 qemu_iovec_destroy(&ctx->mdata.iov);
2268 g_free(ctx->mdata.bounce);
2270 g_free(ctx);
2272 nvme_enqueue_req_completion(nvme_cq(req), req);
2276 static void nvme_verify_mdata_in_cb(void *opaque, int ret)
2278 NvmeBounceContext *ctx = opaque;
2279 NvmeRequest *req = ctx->req;
2280 NvmeNamespace *ns = req->ns;
2281 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2282 uint64_t slba = le64_to_cpu(rw->slba);
2283 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2284 size_t mlen = nvme_m2b(ns, nlb);
2285 uint64_t offset = nvme_moff(ns, slba);
2286 BlockBackend *blk = ns->blkconf.blk;
2288 trace_pci_nvme_verify_mdata_in_cb(nvme_cid(req), blk_name(blk));
2290 if (ret) {
2291 goto out;
2294 ctx->mdata.bounce = g_malloc(mlen);
2296 qemu_iovec_reset(&ctx->mdata.iov);
2297 qemu_iovec_add(&ctx->mdata.iov, ctx->mdata.bounce, mlen);
2299 req->aiocb = blk_aio_preadv(blk, offset, &ctx->mdata.iov, 0,
2300 nvme_verify_cb, ctx);
2301 return;
2303 out:
2304 nvme_verify_cb(ctx, ret);
2307 struct nvme_compare_ctx {
2308 struct {
2309 QEMUIOVector iov;
2310 uint8_t *bounce;
2311 } data;
2313 struct {
2314 QEMUIOVector iov;
2315 uint8_t *bounce;
2316 } mdata;
2319 static void nvme_compare_mdata_cb(void *opaque, int ret)
2321 NvmeRequest *req = opaque;
2322 NvmeNamespace *ns = req->ns;
2323 NvmeCtrl *n = nvme_ctrl(req);
2324 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2325 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2326 uint16_t apptag = le16_to_cpu(rw->apptag);
2327 uint16_t appmask = le16_to_cpu(rw->appmask);
2328 uint64_t reftag = le32_to_cpu(rw->reftag);
2329 uint64_t cdw3 = le32_to_cpu(rw->cdw3);
2330 struct nvme_compare_ctx *ctx = req->opaque;
2331 g_autofree uint8_t *buf = NULL;
2332 BlockBackend *blk = ns->blkconf.blk;
2333 BlockAcctCookie *acct = &req->acct;
2334 BlockAcctStats *stats = blk_get_stats(blk);
2335 uint16_t status = NVME_SUCCESS;
2337 reftag |= cdw3 << 32;
2339 trace_pci_nvme_compare_mdata_cb(nvme_cid(req));
2341 if (ret) {
2342 block_acct_failed(stats, acct);
2343 nvme_aio_err(req, ret);
2344 goto out;
2347 buf = g_malloc(ctx->mdata.iov.size);
2349 status = nvme_bounce_mdata(n, buf, ctx->mdata.iov.size,
2350 NVME_TX_DIRECTION_TO_DEVICE, req);
2351 if (status) {
2352 req->status = status;
2353 goto out;
2356 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2357 uint64_t slba = le64_to_cpu(rw->slba);
2358 uint8_t *bufp;
2359 uint8_t *mbufp = ctx->mdata.bounce;
2360 uint8_t *end = mbufp + ctx->mdata.iov.size;
2361 int16_t pil = 0;
2363 status = nvme_dif_check(ns, ctx->data.bounce, ctx->data.iov.size,
2364 ctx->mdata.bounce, ctx->mdata.iov.size, prinfo,
2365 slba, apptag, appmask, &reftag);
2366 if (status) {
2367 req->status = status;
2368 goto out;
2372 * When formatted with protection information, do not compare the DIF
2373 * tuple.
2375 if (!(ns->id_ns.dps & NVME_ID_NS_DPS_FIRST_EIGHT)) {
2376 pil = ns->lbaf.ms - nvme_pi_tuple_size(ns);
2379 for (bufp = buf; mbufp < end; bufp += ns->lbaf.ms, mbufp += ns->lbaf.ms) {
2380 if (memcmp(bufp + pil, mbufp + pil, ns->lbaf.ms - pil)) {
2381 req->status = NVME_CMP_FAILURE | NVME_DNR;
2382 goto out;
2386 goto out;
2389 if (memcmp(buf, ctx->mdata.bounce, ctx->mdata.iov.size)) {
2390 req->status = NVME_CMP_FAILURE | NVME_DNR;
2391 goto out;
2394 block_acct_done(stats, acct);
2396 out:
2397 qemu_iovec_destroy(&ctx->data.iov);
2398 g_free(ctx->data.bounce);
2400 qemu_iovec_destroy(&ctx->mdata.iov);
2401 g_free(ctx->mdata.bounce);
2403 g_free(ctx);
2405 nvme_enqueue_req_completion(nvme_cq(req), req);
2408 static void nvme_compare_data_cb(void *opaque, int ret)
2410 NvmeRequest *req = opaque;
2411 NvmeCtrl *n = nvme_ctrl(req);
2412 NvmeNamespace *ns = req->ns;
2413 BlockBackend *blk = ns->blkconf.blk;
2414 BlockAcctCookie *acct = &req->acct;
2415 BlockAcctStats *stats = blk_get_stats(blk);
2417 struct nvme_compare_ctx *ctx = req->opaque;
2418 g_autofree uint8_t *buf = NULL;
2419 uint16_t status;
2421 trace_pci_nvme_compare_data_cb(nvme_cid(req));
2423 if (ret) {
2424 block_acct_failed(stats, acct);
2425 nvme_aio_err(req, ret);
2426 goto out;
2429 buf = g_malloc(ctx->data.iov.size);
2431 status = nvme_bounce_data(n, buf, ctx->data.iov.size,
2432 NVME_TX_DIRECTION_TO_DEVICE, req);
2433 if (status) {
2434 req->status = status;
2435 goto out;
2438 if (memcmp(buf, ctx->data.bounce, ctx->data.iov.size)) {
2439 req->status = NVME_CMP_FAILURE | NVME_DNR;
2440 goto out;
2443 if (ns->lbaf.ms) {
2444 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2445 uint64_t slba = le64_to_cpu(rw->slba);
2446 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2447 size_t mlen = nvme_m2b(ns, nlb);
2448 uint64_t offset = nvme_moff(ns, slba);
2450 ctx->mdata.bounce = g_malloc(mlen);
2452 qemu_iovec_init(&ctx->mdata.iov, 1);
2453 qemu_iovec_add(&ctx->mdata.iov, ctx->mdata.bounce, mlen);
2455 req->aiocb = blk_aio_preadv(blk, offset, &ctx->mdata.iov, 0,
2456 nvme_compare_mdata_cb, req);
2457 return;
2460 block_acct_done(stats, acct);
2462 out:
2463 qemu_iovec_destroy(&ctx->data.iov);
2464 g_free(ctx->data.bounce);
2465 g_free(ctx);
2467 nvme_enqueue_req_completion(nvme_cq(req), req);
2470 typedef struct NvmeDSMAIOCB {
2471 BlockAIOCB common;
2472 BlockAIOCB *aiocb;
2473 NvmeRequest *req;
2474 int ret;
2476 NvmeDsmRange *range;
2477 unsigned int nr;
2478 unsigned int idx;
2479 } NvmeDSMAIOCB;
2481 static void nvme_dsm_cancel(BlockAIOCB *aiocb)
2483 NvmeDSMAIOCB *iocb = container_of(aiocb, NvmeDSMAIOCB, common);
2485 /* break nvme_dsm_cb loop */
2486 iocb->idx = iocb->nr;
2487 iocb->ret = -ECANCELED;
2489 if (iocb->aiocb) {
2490 blk_aio_cancel_async(iocb->aiocb);
2491 iocb->aiocb = NULL;
2492 } else {
2494 * We only reach this if nvme_dsm_cancel() has already been called or
2495 * the command ran to completion.
2497 assert(iocb->idx == iocb->nr);
2501 static const AIOCBInfo nvme_dsm_aiocb_info = {
2502 .aiocb_size = sizeof(NvmeDSMAIOCB),
2503 .cancel_async = nvme_dsm_cancel,
2506 static void nvme_dsm_cb(void *opaque, int ret);
2508 static void nvme_dsm_md_cb(void *opaque, int ret)
2510 NvmeDSMAIOCB *iocb = opaque;
2511 NvmeRequest *req = iocb->req;
2512 NvmeNamespace *ns = req->ns;
2513 NvmeDsmRange *range;
2514 uint64_t slba;
2515 uint32_t nlb;
2517 if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
2518 goto done;
2521 range = &iocb->range[iocb->idx - 1];
2522 slba = le64_to_cpu(range->slba);
2523 nlb = le32_to_cpu(range->nlb);
2526 * Check that all block were discarded (zeroed); otherwise we do not zero
2527 * the metadata.
2530 ret = nvme_block_status_all(ns, slba, nlb, BDRV_BLOCK_ZERO);
2531 if (ret) {
2532 if (ret < 0) {
2533 goto done;
2536 nvme_dsm_cb(iocb, 0);
2537 return;
2540 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, nvme_moff(ns, slba),
2541 nvme_m2b(ns, nlb), BDRV_REQ_MAY_UNMAP,
2542 nvme_dsm_cb, iocb);
2543 return;
2545 done:
2546 nvme_dsm_cb(iocb, ret);
2549 static void nvme_dsm_cb(void *opaque, int ret)
2551 NvmeDSMAIOCB *iocb = opaque;
2552 NvmeRequest *req = iocb->req;
2553 NvmeCtrl *n = nvme_ctrl(req);
2554 NvmeNamespace *ns = req->ns;
2555 NvmeDsmRange *range;
2556 uint64_t slba;
2557 uint32_t nlb;
2559 if (iocb->ret < 0) {
2560 goto done;
2561 } else if (ret < 0) {
2562 iocb->ret = ret;
2563 goto done;
2566 next:
2567 if (iocb->idx == iocb->nr) {
2568 goto done;
2571 range = &iocb->range[iocb->idx++];
2572 slba = le64_to_cpu(range->slba);
2573 nlb = le32_to_cpu(range->nlb);
2575 trace_pci_nvme_dsm_deallocate(slba, nlb);
2577 if (nlb > n->dmrsl) {
2578 trace_pci_nvme_dsm_single_range_limit_exceeded(nlb, n->dmrsl);
2579 goto next;
2582 if (nvme_check_bounds(ns, slba, nlb)) {
2583 trace_pci_nvme_err_invalid_lba_range(slba, nlb,
2584 ns->id_ns.nsze);
2585 goto next;
2588 iocb->aiocb = blk_aio_pdiscard(ns->blkconf.blk, nvme_l2b(ns, slba),
2589 nvme_l2b(ns, nlb),
2590 nvme_dsm_md_cb, iocb);
2591 return;
2593 done:
2594 iocb->aiocb = NULL;
2595 iocb->common.cb(iocb->common.opaque, iocb->ret);
2596 qemu_aio_unref(iocb);
2599 static uint16_t nvme_dsm(NvmeCtrl *n, NvmeRequest *req)
2601 NvmeNamespace *ns = req->ns;
2602 NvmeDsmCmd *dsm = (NvmeDsmCmd *) &req->cmd;
2603 uint32_t attr = le32_to_cpu(dsm->attributes);
2604 uint32_t nr = (le32_to_cpu(dsm->nr) & 0xff) + 1;
2605 uint16_t status = NVME_SUCCESS;
2607 trace_pci_nvme_dsm(nr, attr);
2609 if (attr & NVME_DSMGMT_AD) {
2610 NvmeDSMAIOCB *iocb = blk_aio_get(&nvme_dsm_aiocb_info, ns->blkconf.blk,
2611 nvme_misc_cb, req);
2613 iocb->req = req;
2614 iocb->ret = 0;
2615 iocb->range = g_new(NvmeDsmRange, nr);
2616 iocb->nr = nr;
2617 iocb->idx = 0;
2619 status = nvme_h2c(n, (uint8_t *)iocb->range, sizeof(NvmeDsmRange) * nr,
2620 req);
2621 if (status) {
2622 g_free(iocb->range);
2623 qemu_aio_unref(iocb);
2625 return status;
2628 req->aiocb = &iocb->common;
2629 nvme_dsm_cb(iocb, 0);
2631 return NVME_NO_COMPLETE;
2634 return status;
2637 static uint16_t nvme_verify(NvmeCtrl *n, NvmeRequest *req)
2639 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2640 NvmeNamespace *ns = req->ns;
2641 BlockBackend *blk = ns->blkconf.blk;
2642 uint64_t slba = le64_to_cpu(rw->slba);
2643 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2644 size_t len = nvme_l2b(ns, nlb);
2645 int64_t offset = nvme_l2b(ns, slba);
2646 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2647 uint32_t reftag = le32_to_cpu(rw->reftag);
2648 NvmeBounceContext *ctx = NULL;
2649 uint16_t status;
2651 trace_pci_nvme_verify(nvme_cid(req), nvme_nsid(ns), slba, nlb);
2653 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2654 status = nvme_check_prinfo(ns, prinfo, slba, reftag);
2655 if (status) {
2656 return status;
2659 if (prinfo & NVME_PRINFO_PRACT) {
2660 return NVME_INVALID_PROT_INFO | NVME_DNR;
2664 if (len > n->page_size << n->params.vsl) {
2665 return NVME_INVALID_FIELD | NVME_DNR;
2668 status = nvme_check_bounds(ns, slba, nlb);
2669 if (status) {
2670 return status;
2673 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
2674 status = nvme_check_dulbe(ns, slba, nlb);
2675 if (status) {
2676 return status;
2680 ctx = g_new0(NvmeBounceContext, 1);
2681 ctx->req = req;
2683 ctx->data.bounce = g_malloc(len);
2685 qemu_iovec_init(&ctx->data.iov, 1);
2686 qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, len);
2688 block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
2689 BLOCK_ACCT_READ);
2691 req->aiocb = blk_aio_preadv(ns->blkconf.blk, offset, &ctx->data.iov, 0,
2692 nvme_verify_mdata_in_cb, ctx);
2693 return NVME_NO_COMPLETE;
2696 typedef struct NvmeCopyAIOCB {
2697 BlockAIOCB common;
2698 BlockAIOCB *aiocb;
2699 NvmeRequest *req;
2700 int ret;
2702 void *ranges;
2703 unsigned int format;
2704 int nr;
2705 int idx;
2707 uint8_t *bounce;
2708 QEMUIOVector iov;
2709 struct {
2710 BlockAcctCookie read;
2711 BlockAcctCookie write;
2712 } acct;
2714 uint64_t reftag;
2715 uint64_t slba;
2717 NvmeZone *zone;
2718 } NvmeCopyAIOCB;
2720 static void nvme_copy_cancel(BlockAIOCB *aiocb)
2722 NvmeCopyAIOCB *iocb = container_of(aiocb, NvmeCopyAIOCB, common);
2724 iocb->ret = -ECANCELED;
2726 if (iocb->aiocb) {
2727 blk_aio_cancel_async(iocb->aiocb);
2728 iocb->aiocb = NULL;
2732 static const AIOCBInfo nvme_copy_aiocb_info = {
2733 .aiocb_size = sizeof(NvmeCopyAIOCB),
2734 .cancel_async = nvme_copy_cancel,
2737 static void nvme_copy_done(NvmeCopyAIOCB *iocb)
2739 NvmeRequest *req = iocb->req;
2740 NvmeNamespace *ns = req->ns;
2741 BlockAcctStats *stats = blk_get_stats(ns->blkconf.blk);
2743 if (iocb->idx != iocb->nr) {
2744 req->cqe.result = cpu_to_le32(iocb->idx);
2747 qemu_iovec_destroy(&iocb->iov);
2748 g_free(iocb->bounce);
2750 if (iocb->ret < 0) {
2751 block_acct_failed(stats, &iocb->acct.read);
2752 block_acct_failed(stats, &iocb->acct.write);
2753 } else {
2754 block_acct_done(stats, &iocb->acct.read);
2755 block_acct_done(stats, &iocb->acct.write);
2758 iocb->common.cb(iocb->common.opaque, iocb->ret);
2759 qemu_aio_unref(iocb);
2762 static void nvme_do_copy(NvmeCopyAIOCB *iocb);
2764 static void nvme_copy_source_range_parse_format0(void *ranges, int idx,
2765 uint64_t *slba, uint32_t *nlb,
2766 uint16_t *apptag,
2767 uint16_t *appmask,
2768 uint64_t *reftag)
2770 NvmeCopySourceRangeFormat0 *_ranges = ranges;
2772 if (slba) {
2773 *slba = le64_to_cpu(_ranges[idx].slba);
2776 if (nlb) {
2777 *nlb = le16_to_cpu(_ranges[idx].nlb) + 1;
2780 if (apptag) {
2781 *apptag = le16_to_cpu(_ranges[idx].apptag);
2784 if (appmask) {
2785 *appmask = le16_to_cpu(_ranges[idx].appmask);
2788 if (reftag) {
2789 *reftag = le32_to_cpu(_ranges[idx].reftag);
2793 static void nvme_copy_source_range_parse_format1(void *ranges, int idx,
2794 uint64_t *slba, uint32_t *nlb,
2795 uint16_t *apptag,
2796 uint16_t *appmask,
2797 uint64_t *reftag)
2799 NvmeCopySourceRangeFormat1 *_ranges = ranges;
2801 if (slba) {
2802 *slba = le64_to_cpu(_ranges[idx].slba);
2805 if (nlb) {
2806 *nlb = le16_to_cpu(_ranges[idx].nlb) + 1;
2809 if (apptag) {
2810 *apptag = le16_to_cpu(_ranges[idx].apptag);
2813 if (appmask) {
2814 *appmask = le16_to_cpu(_ranges[idx].appmask);
2817 if (reftag) {
2818 *reftag = 0;
2820 *reftag |= (uint64_t)_ranges[idx].sr[4] << 40;
2821 *reftag |= (uint64_t)_ranges[idx].sr[5] << 32;
2822 *reftag |= (uint64_t)_ranges[idx].sr[6] << 24;
2823 *reftag |= (uint64_t)_ranges[idx].sr[7] << 16;
2824 *reftag |= (uint64_t)_ranges[idx].sr[8] << 8;
2825 *reftag |= (uint64_t)_ranges[idx].sr[9];
2829 static void nvme_copy_source_range_parse(void *ranges, int idx, uint8_t format,
2830 uint64_t *slba, uint32_t *nlb,
2831 uint16_t *apptag, uint16_t *appmask,
2832 uint64_t *reftag)
2834 switch (format) {
2835 case NVME_COPY_FORMAT_0:
2836 nvme_copy_source_range_parse_format0(ranges, idx, slba, nlb, apptag,
2837 appmask, reftag);
2838 break;
2840 case NVME_COPY_FORMAT_1:
2841 nvme_copy_source_range_parse_format1(ranges, idx, slba, nlb, apptag,
2842 appmask, reftag);
2843 break;
2845 default:
2846 abort();
2850 static void nvme_copy_out_completed_cb(void *opaque, int ret)
2852 NvmeCopyAIOCB *iocb = opaque;
2853 NvmeRequest *req = iocb->req;
2854 NvmeNamespace *ns = req->ns;
2855 uint32_t nlb;
2857 nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, NULL,
2858 &nlb, NULL, NULL, NULL);
2860 if (ret < 0) {
2861 iocb->ret = ret;
2862 goto out;
2863 } else if (iocb->ret < 0) {
2864 goto out;
2867 if (ns->params.zoned) {
2868 nvme_advance_zone_wp(ns, iocb->zone, nlb);
2871 iocb->idx++;
2872 iocb->slba += nlb;
2873 out:
2874 nvme_do_copy(iocb);
2877 static void nvme_copy_out_cb(void *opaque, int ret)
2879 NvmeCopyAIOCB *iocb = opaque;
2880 NvmeRequest *req = iocb->req;
2881 NvmeNamespace *ns = req->ns;
2882 uint32_t nlb;
2883 size_t mlen;
2884 uint8_t *mbounce;
2886 if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
2887 goto out;
2890 nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, NULL,
2891 &nlb, NULL, NULL, NULL);
2893 mlen = nvme_m2b(ns, nlb);
2894 mbounce = iocb->bounce + nvme_l2b(ns, nlb);
2896 qemu_iovec_reset(&iocb->iov);
2897 qemu_iovec_add(&iocb->iov, mbounce, mlen);
2899 iocb->aiocb = blk_aio_pwritev(ns->blkconf.blk, nvme_moff(ns, iocb->slba),
2900 &iocb->iov, 0, nvme_copy_out_completed_cb,
2901 iocb);
2903 return;
2905 out:
2906 nvme_copy_out_completed_cb(iocb, ret);
2909 static void nvme_copy_in_completed_cb(void *opaque, int ret)
2911 NvmeCopyAIOCB *iocb = opaque;
2912 NvmeRequest *req = iocb->req;
2913 NvmeNamespace *ns = req->ns;
2914 uint32_t nlb;
2915 uint64_t slba;
2916 uint16_t apptag, appmask;
2917 uint64_t reftag;
2918 size_t len;
2919 uint16_t status;
2921 if (ret < 0) {
2922 iocb->ret = ret;
2923 goto out;
2924 } else if (iocb->ret < 0) {
2925 goto out;
2928 nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, &slba,
2929 &nlb, &apptag, &appmask, &reftag);
2930 len = nvme_l2b(ns, nlb);
2932 trace_pci_nvme_copy_out(iocb->slba, nlb);
2934 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2935 NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
2937 uint16_t prinfor = ((copy->control[0] >> 4) & 0xf);
2938 uint16_t prinfow = ((copy->control[2] >> 2) & 0xf);
2940 size_t mlen = nvme_m2b(ns, nlb);
2941 uint8_t *mbounce = iocb->bounce + nvme_l2b(ns, nlb);
2943 status = nvme_dif_mangle_mdata(ns, mbounce, mlen, slba);
2944 if (status) {
2945 goto invalid;
2947 status = nvme_dif_check(ns, iocb->bounce, len, mbounce, mlen, prinfor,
2948 slba, apptag, appmask, &reftag);
2949 if (status) {
2950 goto invalid;
2953 apptag = le16_to_cpu(copy->apptag);
2954 appmask = le16_to_cpu(copy->appmask);
2956 if (prinfow & NVME_PRINFO_PRACT) {
2957 status = nvme_check_prinfo(ns, prinfow, iocb->slba, iocb->reftag);
2958 if (status) {
2959 goto invalid;
2962 nvme_dif_pract_generate_dif(ns, iocb->bounce, len, mbounce, mlen,
2963 apptag, &iocb->reftag);
2964 } else {
2965 status = nvme_dif_check(ns, iocb->bounce, len, mbounce, mlen,
2966 prinfow, iocb->slba, apptag, appmask,
2967 &iocb->reftag);
2968 if (status) {
2969 goto invalid;
2974 status = nvme_check_bounds(ns, iocb->slba, nlb);
2975 if (status) {
2976 goto invalid;
2979 if (ns->params.zoned) {
2980 status = nvme_check_zone_write(ns, iocb->zone, iocb->slba, nlb);
2981 if (status) {
2982 goto invalid;
2985 if (!(iocb->zone->d.za & NVME_ZA_ZRWA_VALID)) {
2986 iocb->zone->w_ptr += nlb;
2990 qemu_iovec_reset(&iocb->iov);
2991 qemu_iovec_add(&iocb->iov, iocb->bounce, len);
2993 iocb->aiocb = blk_aio_pwritev(ns->blkconf.blk, nvme_l2b(ns, iocb->slba),
2994 &iocb->iov, 0, nvme_copy_out_cb, iocb);
2996 return;
2998 invalid:
2999 req->status = status;
3000 iocb->ret = -1;
3001 out:
3002 nvme_do_copy(iocb);
3005 static void nvme_copy_in_cb(void *opaque, int ret)
3007 NvmeCopyAIOCB *iocb = opaque;
3008 NvmeRequest *req = iocb->req;
3009 NvmeNamespace *ns = req->ns;
3010 uint64_t slba;
3011 uint32_t nlb;
3013 if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
3014 goto out;
3017 nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, &slba,
3018 &nlb, NULL, NULL, NULL);
3020 qemu_iovec_reset(&iocb->iov);
3021 qemu_iovec_add(&iocb->iov, iocb->bounce + nvme_l2b(ns, nlb),
3022 nvme_m2b(ns, nlb));
3024 iocb->aiocb = blk_aio_preadv(ns->blkconf.blk, nvme_moff(ns, slba),
3025 &iocb->iov, 0, nvme_copy_in_completed_cb,
3026 iocb);
3027 return;
3029 out:
3030 nvme_copy_in_completed_cb(iocb, ret);
3033 static void nvme_do_copy(NvmeCopyAIOCB *iocb)
3035 NvmeRequest *req = iocb->req;
3036 NvmeNamespace *ns = req->ns;
3037 uint64_t slba;
3038 uint32_t nlb;
3039 size_t len;
3040 uint16_t status;
3042 if (iocb->ret < 0) {
3043 goto done;
3046 if (iocb->idx == iocb->nr) {
3047 goto done;
3050 nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, &slba,
3051 &nlb, NULL, NULL, NULL);
3052 len = nvme_l2b(ns, nlb);
3054 trace_pci_nvme_copy_source_range(slba, nlb);
3056 if (nlb > le16_to_cpu(ns->id_ns.mssrl)) {
3057 status = NVME_CMD_SIZE_LIMIT | NVME_DNR;
3058 goto invalid;
3061 status = nvme_check_bounds(ns, slba, nlb);
3062 if (status) {
3063 goto invalid;
3066 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
3067 status = nvme_check_dulbe(ns, slba, nlb);
3068 if (status) {
3069 goto invalid;
3073 if (ns->params.zoned) {
3074 status = nvme_check_zone_read(ns, slba, nlb);
3075 if (status) {
3076 goto invalid;
3080 qemu_iovec_reset(&iocb->iov);
3081 qemu_iovec_add(&iocb->iov, iocb->bounce, len);
3083 iocb->aiocb = blk_aio_preadv(ns->blkconf.blk, nvme_l2b(ns, slba),
3084 &iocb->iov, 0, nvme_copy_in_cb, iocb);
3085 return;
3087 invalid:
3088 req->status = status;
3089 iocb->ret = -1;
3090 done:
3091 nvme_copy_done(iocb);
3094 static uint16_t nvme_copy(NvmeCtrl *n, NvmeRequest *req)
3096 NvmeNamespace *ns = req->ns;
3097 NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
3098 NvmeCopyAIOCB *iocb = blk_aio_get(&nvme_copy_aiocb_info, ns->blkconf.blk,
3099 nvme_misc_cb, req);
3100 uint16_t nr = copy->nr + 1;
3101 uint8_t format = copy->control[0] & 0xf;
3102 uint16_t prinfor = ((copy->control[0] >> 4) & 0xf);
3103 uint16_t prinfow = ((copy->control[2] >> 2) & 0xf);
3104 size_t len = sizeof(NvmeCopySourceRangeFormat0);
3106 uint16_t status;
3108 trace_pci_nvme_copy(nvme_cid(req), nvme_nsid(ns), nr, format);
3110 iocb->ranges = NULL;
3111 iocb->zone = NULL;
3113 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps) &&
3114 ((prinfor & NVME_PRINFO_PRACT) != (prinfow & NVME_PRINFO_PRACT))) {
3115 status = NVME_INVALID_FIELD | NVME_DNR;
3116 goto invalid;
3119 if (!(n->id_ctrl.ocfs & (1 << format))) {
3120 trace_pci_nvme_err_copy_invalid_format(format);
3121 status = NVME_INVALID_FIELD | NVME_DNR;
3122 goto invalid;
3125 if (nr > ns->id_ns.msrc + 1) {
3126 status = NVME_CMD_SIZE_LIMIT | NVME_DNR;
3127 goto invalid;
3130 if ((ns->pif == 0x0 && format != 0x0) ||
3131 (ns->pif != 0x0 && format != 0x1)) {
3132 status = NVME_INVALID_FORMAT | NVME_DNR;
3133 goto invalid;
3136 if (ns->pif) {
3137 len = sizeof(NvmeCopySourceRangeFormat1);
3140 iocb->format = format;
3141 iocb->ranges = g_malloc_n(nr, len);
3142 status = nvme_h2c(n, (uint8_t *)iocb->ranges, len * nr, req);
3143 if (status) {
3144 goto invalid;
3147 iocb->slba = le64_to_cpu(copy->sdlba);
3149 if (ns->params.zoned) {
3150 iocb->zone = nvme_get_zone_by_slba(ns, iocb->slba);
3151 if (!iocb->zone) {
3152 status = NVME_LBA_RANGE | NVME_DNR;
3153 goto invalid;
3156 status = nvme_zrm_auto(n, ns, iocb->zone);
3157 if (status) {
3158 goto invalid;
3162 iocb->req = req;
3163 iocb->ret = 0;
3164 iocb->nr = nr;
3165 iocb->idx = 0;
3166 iocb->reftag = le32_to_cpu(copy->reftag);
3167 iocb->reftag |= (uint64_t)le32_to_cpu(copy->cdw3) << 32;
3168 iocb->bounce = g_malloc_n(le16_to_cpu(ns->id_ns.mssrl),
3169 ns->lbasz + ns->lbaf.ms);
3171 qemu_iovec_init(&iocb->iov, 1);
3173 block_acct_start(blk_get_stats(ns->blkconf.blk), &iocb->acct.read, 0,
3174 BLOCK_ACCT_READ);
3175 block_acct_start(blk_get_stats(ns->blkconf.blk), &iocb->acct.write, 0,
3176 BLOCK_ACCT_WRITE);
3178 req->aiocb = &iocb->common;
3179 nvme_do_copy(iocb);
3181 return NVME_NO_COMPLETE;
3183 invalid:
3184 g_free(iocb->ranges);
3185 qemu_aio_unref(iocb);
3186 return status;
3189 static uint16_t nvme_compare(NvmeCtrl *n, NvmeRequest *req)
3191 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3192 NvmeNamespace *ns = req->ns;
3193 BlockBackend *blk = ns->blkconf.blk;
3194 uint64_t slba = le64_to_cpu(rw->slba);
3195 uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
3196 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
3197 size_t data_len = nvme_l2b(ns, nlb);
3198 size_t len = data_len;
3199 int64_t offset = nvme_l2b(ns, slba);
3200 struct nvme_compare_ctx *ctx = NULL;
3201 uint16_t status;
3203 trace_pci_nvme_compare(nvme_cid(req), nvme_nsid(ns), slba, nlb);
3205 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps) && (prinfo & NVME_PRINFO_PRACT)) {
3206 return NVME_INVALID_PROT_INFO | NVME_DNR;
3209 if (nvme_ns_ext(ns)) {
3210 len += nvme_m2b(ns, nlb);
3213 status = nvme_check_mdts(n, len);
3214 if (status) {
3215 return status;
3218 status = nvme_check_bounds(ns, slba, nlb);
3219 if (status) {
3220 return status;
3223 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
3224 status = nvme_check_dulbe(ns, slba, nlb);
3225 if (status) {
3226 return status;
3230 status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
3231 if (status) {
3232 return status;
3235 ctx = g_new(struct nvme_compare_ctx, 1);
3236 ctx->data.bounce = g_malloc(data_len);
3238 req->opaque = ctx;
3240 qemu_iovec_init(&ctx->data.iov, 1);
3241 qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, data_len);
3243 block_acct_start(blk_get_stats(blk), &req->acct, data_len,
3244 BLOCK_ACCT_READ);
3245 req->aiocb = blk_aio_preadv(blk, offset, &ctx->data.iov, 0,
3246 nvme_compare_data_cb, req);
3248 return NVME_NO_COMPLETE;
3251 typedef struct NvmeFlushAIOCB {
3252 BlockAIOCB common;
3253 BlockAIOCB *aiocb;
3254 NvmeRequest *req;
3255 int ret;
3257 NvmeNamespace *ns;
3258 uint32_t nsid;
3259 bool broadcast;
3260 } NvmeFlushAIOCB;
3262 static void nvme_flush_cancel(BlockAIOCB *acb)
3264 NvmeFlushAIOCB *iocb = container_of(acb, NvmeFlushAIOCB, common);
3266 iocb->ret = -ECANCELED;
3268 if (iocb->aiocb) {
3269 blk_aio_cancel_async(iocb->aiocb);
3270 iocb->aiocb = NULL;
3274 static const AIOCBInfo nvme_flush_aiocb_info = {
3275 .aiocb_size = sizeof(NvmeFlushAIOCB),
3276 .cancel_async = nvme_flush_cancel,
3277 .get_aio_context = nvme_get_aio_context,
3280 static void nvme_do_flush(NvmeFlushAIOCB *iocb);
3282 static void nvme_flush_ns_cb(void *opaque, int ret)
3284 NvmeFlushAIOCB *iocb = opaque;
3285 NvmeNamespace *ns = iocb->ns;
3287 if (ret < 0) {
3288 iocb->ret = ret;
3289 goto out;
3290 } else if (iocb->ret < 0) {
3291 goto out;
3294 if (ns) {
3295 trace_pci_nvme_flush_ns(iocb->nsid);
3297 iocb->ns = NULL;
3298 iocb->aiocb = blk_aio_flush(ns->blkconf.blk, nvme_flush_ns_cb, iocb);
3299 return;
3302 out:
3303 nvme_do_flush(iocb);
3306 static void nvme_do_flush(NvmeFlushAIOCB *iocb)
3308 NvmeRequest *req = iocb->req;
3309 NvmeCtrl *n = nvme_ctrl(req);
3310 int i;
3312 if (iocb->ret < 0) {
3313 goto done;
3316 if (iocb->broadcast) {
3317 for (i = iocb->nsid + 1; i <= NVME_MAX_NAMESPACES; i++) {
3318 iocb->ns = nvme_ns(n, i);
3319 if (iocb->ns) {
3320 iocb->nsid = i;
3321 break;
3326 if (!iocb->ns) {
3327 goto done;
3330 nvme_flush_ns_cb(iocb, 0);
3331 return;
3333 done:
3334 iocb->common.cb(iocb->common.opaque, iocb->ret);
3335 qemu_aio_unref(iocb);
3338 static uint16_t nvme_flush(NvmeCtrl *n, NvmeRequest *req)
3340 NvmeFlushAIOCB *iocb;
3341 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
3342 uint16_t status;
3344 iocb = qemu_aio_get(&nvme_flush_aiocb_info, NULL, nvme_misc_cb, req);
3346 iocb->req = req;
3347 iocb->ret = 0;
3348 iocb->ns = NULL;
3349 iocb->nsid = 0;
3350 iocb->broadcast = (nsid == NVME_NSID_BROADCAST);
3352 if (!iocb->broadcast) {
3353 if (!nvme_nsid_valid(n, nsid)) {
3354 status = NVME_INVALID_NSID | NVME_DNR;
3355 goto out;
3358 iocb->ns = nvme_ns(n, nsid);
3359 if (!iocb->ns) {
3360 status = NVME_INVALID_FIELD | NVME_DNR;
3361 goto out;
3364 iocb->nsid = nsid;
3367 req->aiocb = &iocb->common;
3368 nvme_do_flush(iocb);
3370 return NVME_NO_COMPLETE;
3372 out:
3373 qemu_aio_unref(iocb);
3375 return status;
3378 static uint16_t nvme_read(NvmeCtrl *n, NvmeRequest *req)
3380 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3381 NvmeNamespace *ns = req->ns;
3382 uint64_t slba = le64_to_cpu(rw->slba);
3383 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
3384 uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
3385 uint64_t data_size = nvme_l2b(ns, nlb);
3386 uint64_t mapped_size = data_size;
3387 uint64_t data_offset;
3388 BlockBackend *blk = ns->blkconf.blk;
3389 uint16_t status;
3391 if (nvme_ns_ext(ns)) {
3392 mapped_size += nvme_m2b(ns, nlb);
3394 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3395 bool pract = prinfo & NVME_PRINFO_PRACT;
3397 if (pract && ns->lbaf.ms == nvme_pi_tuple_size(ns)) {
3398 mapped_size = data_size;
3403 trace_pci_nvme_read(nvme_cid(req), nvme_nsid(ns), nlb, mapped_size, slba);
3405 status = nvme_check_mdts(n, mapped_size);
3406 if (status) {
3407 goto invalid;
3410 status = nvme_check_bounds(ns, slba, nlb);
3411 if (status) {
3412 goto invalid;
3415 if (ns->params.zoned) {
3416 status = nvme_check_zone_read(ns, slba, nlb);
3417 if (status) {
3418 trace_pci_nvme_err_zone_read_not_ok(slba, nlb, status);
3419 goto invalid;
3423 if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
3424 status = nvme_check_dulbe(ns, slba, nlb);
3425 if (status) {
3426 goto invalid;
3430 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3431 return nvme_dif_rw(n, req);
3434 status = nvme_map_data(n, nlb, req);
3435 if (status) {
3436 goto invalid;
3439 data_offset = nvme_l2b(ns, slba);
3441 block_acct_start(blk_get_stats(blk), &req->acct, data_size,
3442 BLOCK_ACCT_READ);
3443 nvme_blk_read(blk, data_offset, BDRV_SECTOR_SIZE, nvme_rw_cb, req);
3444 return NVME_NO_COMPLETE;
3446 invalid:
3447 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
3448 return status | NVME_DNR;
3451 static void nvme_do_write_fdp(NvmeCtrl *n, NvmeRequest *req, uint64_t slba,
3452 uint32_t nlb)
3454 NvmeNamespace *ns = req->ns;
3455 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3456 uint64_t data_size = nvme_l2b(ns, nlb);
3457 uint32_t dw12 = le32_to_cpu(req->cmd.cdw12);
3458 uint8_t dtype = (dw12 >> 20) & 0xf;
3459 uint16_t pid = le16_to_cpu(rw->dspec);
3460 uint16_t ph, rg, ruhid;
3461 NvmeReclaimUnit *ru;
3463 if (dtype != NVME_DIRECTIVE_DATA_PLACEMENT ||
3464 !nvme_parse_pid(ns, pid, &ph, &rg)) {
3465 ph = 0;
3466 rg = 0;
3469 ruhid = ns->fdp.phs[ph];
3470 ru = &ns->endgrp->fdp.ruhs[ruhid].rus[rg];
3472 nvme_fdp_stat_inc(&ns->endgrp->fdp.hbmw, data_size);
3473 nvme_fdp_stat_inc(&ns->endgrp->fdp.mbmw, data_size);
3475 while (nlb) {
3476 if (nlb < ru->ruamw) {
3477 ru->ruamw -= nlb;
3478 break;
3481 nlb -= ru->ruamw;
3482 nvme_update_ruh(n, ns, pid);
3486 static uint16_t nvme_do_write(NvmeCtrl *n, NvmeRequest *req, bool append,
3487 bool wrz)
3489 NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3490 NvmeNamespace *ns = req->ns;
3491 uint64_t slba = le64_to_cpu(rw->slba);
3492 uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
3493 uint16_t ctrl = le16_to_cpu(rw->control);
3494 uint8_t prinfo = NVME_RW_PRINFO(ctrl);
3495 uint64_t data_size = nvme_l2b(ns, nlb);
3496 uint64_t mapped_size = data_size;
3497 uint64_t data_offset;
3498 NvmeZone *zone;
3499 NvmeZonedResult *res = (NvmeZonedResult *)&req->cqe;
3500 BlockBackend *blk = ns->blkconf.blk;
3501 uint16_t status;
3503 if (nvme_ns_ext(ns)) {
3504 mapped_size += nvme_m2b(ns, nlb);
3506 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3507 bool pract = prinfo & NVME_PRINFO_PRACT;
3509 if (pract && ns->lbaf.ms == nvme_pi_tuple_size(ns)) {
3510 mapped_size -= nvme_m2b(ns, nlb);
3515 trace_pci_nvme_write(nvme_cid(req), nvme_io_opc_str(rw->opcode),
3516 nvme_nsid(ns), nlb, mapped_size, slba);
3518 if (!wrz) {
3519 status = nvme_check_mdts(n, mapped_size);
3520 if (status) {
3521 goto invalid;
3525 status = nvme_check_bounds(ns, slba, nlb);
3526 if (status) {
3527 goto invalid;
3530 if (ns->params.zoned) {
3531 zone = nvme_get_zone_by_slba(ns, slba);
3532 assert(zone);
3534 if (append) {
3535 bool piremap = !!(ctrl & NVME_RW_PIREMAP);
3537 if (unlikely(zone->d.za & NVME_ZA_ZRWA_VALID)) {
3538 return NVME_INVALID_ZONE_OP | NVME_DNR;
3541 if (unlikely(slba != zone->d.zslba)) {
3542 trace_pci_nvme_err_append_not_at_start(slba, zone->d.zslba);
3543 status = NVME_INVALID_FIELD;
3544 goto invalid;
3547 if (n->params.zasl &&
3548 data_size > (uint64_t)n->page_size << n->params.zasl) {
3549 trace_pci_nvme_err_zasl(data_size);
3550 return NVME_INVALID_FIELD | NVME_DNR;
3553 slba = zone->w_ptr;
3554 rw->slba = cpu_to_le64(slba);
3555 res->slba = cpu_to_le64(slba);
3557 switch (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3558 case NVME_ID_NS_DPS_TYPE_1:
3559 if (!piremap) {
3560 return NVME_INVALID_PROT_INFO | NVME_DNR;
3563 /* fallthrough */
3565 case NVME_ID_NS_DPS_TYPE_2:
3566 if (piremap) {
3567 uint32_t reftag = le32_to_cpu(rw->reftag);
3568 rw->reftag = cpu_to_le32(reftag + (slba - zone->d.zslba));
3571 break;
3573 case NVME_ID_NS_DPS_TYPE_3:
3574 if (piremap) {
3575 return NVME_INVALID_PROT_INFO | NVME_DNR;
3578 break;
3582 status = nvme_check_zone_write(ns, zone, slba, nlb);
3583 if (status) {
3584 goto invalid;
3587 status = nvme_zrm_auto(n, ns, zone);
3588 if (status) {
3589 goto invalid;
3592 if (!(zone->d.za & NVME_ZA_ZRWA_VALID)) {
3593 zone->w_ptr += nlb;
3595 } else if (ns->endgrp && ns->endgrp->fdp.enabled) {
3596 nvme_do_write_fdp(n, req, slba, nlb);
3599 data_offset = nvme_l2b(ns, slba);
3601 if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3602 return nvme_dif_rw(n, req);
3605 if (!wrz) {
3606 status = nvme_map_data(n, nlb, req);
3607 if (status) {
3608 goto invalid;
3611 block_acct_start(blk_get_stats(blk), &req->acct, data_size,
3612 BLOCK_ACCT_WRITE);
3613 nvme_blk_write(blk, data_offset, BDRV_SECTOR_SIZE, nvme_rw_cb, req);
3614 } else {
3615 req->aiocb = blk_aio_pwrite_zeroes(blk, data_offset, data_size,
3616 BDRV_REQ_MAY_UNMAP, nvme_rw_cb,
3617 req);
3620 return NVME_NO_COMPLETE;
3622 invalid:
3623 block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
3624 return status | NVME_DNR;
3627 static inline uint16_t nvme_write(NvmeCtrl *n, NvmeRequest *req)
3629 return nvme_do_write(n, req, false, false);
3632 static inline uint16_t nvme_write_zeroes(NvmeCtrl *n, NvmeRequest *req)
3634 return nvme_do_write(n, req, false, true);
3637 static inline uint16_t nvme_zone_append(NvmeCtrl *n, NvmeRequest *req)
3639 return nvme_do_write(n, req, true, false);
3642 static uint16_t nvme_get_mgmt_zone_slba_idx(NvmeNamespace *ns, NvmeCmd *c,
3643 uint64_t *slba, uint32_t *zone_idx)
3645 uint32_t dw10 = le32_to_cpu(c->cdw10);
3646 uint32_t dw11 = le32_to_cpu(c->cdw11);
3648 if (!ns->params.zoned) {
3649 trace_pci_nvme_err_invalid_opc(c->opcode);
3650 return NVME_INVALID_OPCODE | NVME_DNR;
3653 *slba = ((uint64_t)dw11) << 32 | dw10;
3654 if (unlikely(*slba >= ns->id_ns.nsze)) {
3655 trace_pci_nvme_err_invalid_lba_range(*slba, 0, ns->id_ns.nsze);
3656 *slba = 0;
3657 return NVME_LBA_RANGE | NVME_DNR;
3660 *zone_idx = nvme_zone_idx(ns, *slba);
3661 assert(*zone_idx < ns->num_zones);
3663 return NVME_SUCCESS;
3666 typedef uint16_t (*op_handler_t)(NvmeNamespace *, NvmeZone *, NvmeZoneState,
3667 NvmeRequest *);
3669 enum NvmeZoneProcessingMask {
3670 NVME_PROC_CURRENT_ZONE = 0,
3671 NVME_PROC_OPENED_ZONES = 1 << 0,
3672 NVME_PROC_CLOSED_ZONES = 1 << 1,
3673 NVME_PROC_READ_ONLY_ZONES = 1 << 2,
3674 NVME_PROC_FULL_ZONES = 1 << 3,
3677 static uint16_t nvme_open_zone(NvmeNamespace *ns, NvmeZone *zone,
3678 NvmeZoneState state, NvmeRequest *req)
3680 NvmeZoneSendCmd *cmd = (NvmeZoneSendCmd *)&req->cmd;
3681 int flags = 0;
3683 if (cmd->zsflags & NVME_ZSFLAG_ZRWA_ALLOC) {
3684 uint16_t ozcs = le16_to_cpu(ns->id_ns_zoned->ozcs);
3686 if (!(ozcs & NVME_ID_NS_ZONED_OZCS_ZRWASUP)) {
3687 return NVME_INVALID_ZONE_OP | NVME_DNR;
3690 if (zone->w_ptr % ns->zns.zrwafg) {
3691 return NVME_NOZRWA | NVME_DNR;
3694 flags = NVME_ZRM_ZRWA;
3697 return nvme_zrm_open_flags(nvme_ctrl(req), ns, zone, flags);
3700 static uint16_t nvme_close_zone(NvmeNamespace *ns, NvmeZone *zone,
3701 NvmeZoneState state, NvmeRequest *req)
3703 return nvme_zrm_close(ns, zone);
3706 static uint16_t nvme_finish_zone(NvmeNamespace *ns, NvmeZone *zone,
3707 NvmeZoneState state, NvmeRequest *req)
3709 return nvme_zrm_finish(ns, zone);
3712 static uint16_t nvme_offline_zone(NvmeNamespace *ns, NvmeZone *zone,
3713 NvmeZoneState state, NvmeRequest *req)
3715 switch (state) {
3716 case NVME_ZONE_STATE_READ_ONLY:
3717 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_OFFLINE);
3718 /* fall through */
3719 case NVME_ZONE_STATE_OFFLINE:
3720 return NVME_SUCCESS;
3721 default:
3722 return NVME_ZONE_INVAL_TRANSITION;
3726 static uint16_t nvme_set_zd_ext(NvmeNamespace *ns, NvmeZone *zone)
3728 uint16_t status;
3729 uint8_t state = nvme_get_zone_state(zone);
3731 if (state == NVME_ZONE_STATE_EMPTY) {
3732 status = nvme_aor_check(ns, 1, 0);
3733 if (status) {
3734 return status;
3736 nvme_aor_inc_active(ns);
3737 zone->d.za |= NVME_ZA_ZD_EXT_VALID;
3738 nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
3739 return NVME_SUCCESS;
3742 return NVME_ZONE_INVAL_TRANSITION;
3745 static uint16_t nvme_bulk_proc_zone(NvmeNamespace *ns, NvmeZone *zone,
3746 enum NvmeZoneProcessingMask proc_mask,
3747 op_handler_t op_hndlr, NvmeRequest *req)
3749 uint16_t status = NVME_SUCCESS;
3750 NvmeZoneState zs = nvme_get_zone_state(zone);
3751 bool proc_zone;
3753 switch (zs) {
3754 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
3755 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
3756 proc_zone = proc_mask & NVME_PROC_OPENED_ZONES;
3757 break;
3758 case NVME_ZONE_STATE_CLOSED:
3759 proc_zone = proc_mask & NVME_PROC_CLOSED_ZONES;
3760 break;
3761 case NVME_ZONE_STATE_READ_ONLY:
3762 proc_zone = proc_mask & NVME_PROC_READ_ONLY_ZONES;
3763 break;
3764 case NVME_ZONE_STATE_FULL:
3765 proc_zone = proc_mask & NVME_PROC_FULL_ZONES;
3766 break;
3767 default:
3768 proc_zone = false;
3771 if (proc_zone) {
3772 status = op_hndlr(ns, zone, zs, req);
3775 return status;
3778 static uint16_t nvme_do_zone_op(NvmeNamespace *ns, NvmeZone *zone,
3779 enum NvmeZoneProcessingMask proc_mask,
3780 op_handler_t op_hndlr, NvmeRequest *req)
3782 NvmeZone *next;
3783 uint16_t status = NVME_SUCCESS;
3784 int i;
3786 if (!proc_mask) {
3787 status = op_hndlr(ns, zone, nvme_get_zone_state(zone), req);
3788 } else {
3789 if (proc_mask & NVME_PROC_CLOSED_ZONES) {
3790 QTAILQ_FOREACH_SAFE(zone, &ns->closed_zones, entry, next) {
3791 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3792 req);
3793 if (status && status != NVME_NO_COMPLETE) {
3794 goto out;
3798 if (proc_mask & NVME_PROC_OPENED_ZONES) {
3799 QTAILQ_FOREACH_SAFE(zone, &ns->imp_open_zones, entry, next) {
3800 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3801 req);
3802 if (status && status != NVME_NO_COMPLETE) {
3803 goto out;
3807 QTAILQ_FOREACH_SAFE(zone, &ns->exp_open_zones, entry, next) {
3808 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3809 req);
3810 if (status && status != NVME_NO_COMPLETE) {
3811 goto out;
3815 if (proc_mask & NVME_PROC_FULL_ZONES) {
3816 QTAILQ_FOREACH_SAFE(zone, &ns->full_zones, entry, next) {
3817 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3818 req);
3819 if (status && status != NVME_NO_COMPLETE) {
3820 goto out;
3825 if (proc_mask & NVME_PROC_READ_ONLY_ZONES) {
3826 for (i = 0; i < ns->num_zones; i++, zone++) {
3827 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3828 req);
3829 if (status && status != NVME_NO_COMPLETE) {
3830 goto out;
3836 out:
3837 return status;
3840 typedef struct NvmeZoneResetAIOCB {
3841 BlockAIOCB common;
3842 BlockAIOCB *aiocb;
3843 NvmeRequest *req;
3844 int ret;
3846 bool all;
3847 int idx;
3848 NvmeZone *zone;
3849 } NvmeZoneResetAIOCB;
3851 static void nvme_zone_reset_cancel(BlockAIOCB *aiocb)
3853 NvmeZoneResetAIOCB *iocb = container_of(aiocb, NvmeZoneResetAIOCB, common);
3854 NvmeRequest *req = iocb->req;
3855 NvmeNamespace *ns = req->ns;
3857 iocb->idx = ns->num_zones;
3859 iocb->ret = -ECANCELED;
3861 if (iocb->aiocb) {
3862 blk_aio_cancel_async(iocb->aiocb);
3863 iocb->aiocb = NULL;
3867 static const AIOCBInfo nvme_zone_reset_aiocb_info = {
3868 .aiocb_size = sizeof(NvmeZoneResetAIOCB),
3869 .cancel_async = nvme_zone_reset_cancel,
3872 static void nvme_zone_reset_cb(void *opaque, int ret);
3874 static void nvme_zone_reset_epilogue_cb(void *opaque, int ret)
3876 NvmeZoneResetAIOCB *iocb = opaque;
3877 NvmeRequest *req = iocb->req;
3878 NvmeNamespace *ns = req->ns;
3879 int64_t moff;
3880 int count;
3882 if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
3883 goto out;
3886 moff = nvme_moff(ns, iocb->zone->d.zslba);
3887 count = nvme_m2b(ns, ns->zone_size);
3889 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, moff, count,
3890 BDRV_REQ_MAY_UNMAP,
3891 nvme_zone_reset_cb, iocb);
3892 return;
3894 out:
3895 nvme_zone_reset_cb(iocb, ret);
3898 static void nvme_zone_reset_cb(void *opaque, int ret)
3900 NvmeZoneResetAIOCB *iocb = opaque;
3901 NvmeRequest *req = iocb->req;
3902 NvmeNamespace *ns = req->ns;
3904 if (iocb->ret < 0) {
3905 goto done;
3906 } else if (ret < 0) {
3907 iocb->ret = ret;
3908 goto done;
3911 if (iocb->zone) {
3912 nvme_zrm_reset(ns, iocb->zone);
3914 if (!iocb->all) {
3915 goto done;
3919 while (iocb->idx < ns->num_zones) {
3920 NvmeZone *zone = &ns->zone_array[iocb->idx++];
3922 switch (nvme_get_zone_state(zone)) {
3923 case NVME_ZONE_STATE_EMPTY:
3924 if (!iocb->all) {
3925 goto done;
3928 continue;
3930 case NVME_ZONE_STATE_EXPLICITLY_OPEN:
3931 case NVME_ZONE_STATE_IMPLICITLY_OPEN:
3932 case NVME_ZONE_STATE_CLOSED:
3933 case NVME_ZONE_STATE_FULL:
3934 iocb->zone = zone;
3935 break;
3937 default:
3938 continue;
3941 trace_pci_nvme_zns_zone_reset(zone->d.zslba);
3943 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk,
3944 nvme_l2b(ns, zone->d.zslba),
3945 nvme_l2b(ns, ns->zone_size),
3946 BDRV_REQ_MAY_UNMAP,
3947 nvme_zone_reset_epilogue_cb,
3948 iocb);
3949 return;
3952 done:
3953 iocb->aiocb = NULL;
3955 iocb->common.cb(iocb->common.opaque, iocb->ret);
3956 qemu_aio_unref(iocb);
3959 static uint16_t nvme_zone_mgmt_send_zrwa_flush(NvmeCtrl *n, NvmeZone *zone,
3960 uint64_t elba, NvmeRequest *req)
3962 NvmeNamespace *ns = req->ns;
3963 uint16_t ozcs = le16_to_cpu(ns->id_ns_zoned->ozcs);
3964 uint64_t wp = zone->d.wp;
3965 uint32_t nlb = elba - wp + 1;
3966 uint16_t status;
3969 if (!(ozcs & NVME_ID_NS_ZONED_OZCS_ZRWASUP)) {
3970 return NVME_INVALID_ZONE_OP | NVME_DNR;
3973 if (!(zone->d.za & NVME_ZA_ZRWA_VALID)) {
3974 return NVME_INVALID_FIELD | NVME_DNR;
3977 if (elba < wp || elba > wp + ns->zns.zrwas) {
3978 return NVME_ZONE_BOUNDARY_ERROR | NVME_DNR;
3981 if (nlb % ns->zns.zrwafg) {
3982 return NVME_INVALID_FIELD | NVME_DNR;
3985 status = nvme_zrm_auto(n, ns, zone);
3986 if (status) {
3987 return status;
3990 zone->w_ptr += nlb;
3992 nvme_advance_zone_wp(ns, zone, nlb);
3994 return NVME_SUCCESS;
3997 static uint16_t nvme_zone_mgmt_send(NvmeCtrl *n, NvmeRequest *req)
3999 NvmeZoneSendCmd *cmd = (NvmeZoneSendCmd *)&req->cmd;
4000 NvmeNamespace *ns = req->ns;
4001 NvmeZone *zone;
4002 NvmeZoneResetAIOCB *iocb;
4003 uint8_t *zd_ext;
4004 uint64_t slba = 0;
4005 uint32_t zone_idx = 0;
4006 uint16_t status;
4007 uint8_t action = cmd->zsa;
4008 bool all;
4009 enum NvmeZoneProcessingMask proc_mask = NVME_PROC_CURRENT_ZONE;
4011 all = cmd->zsflags & NVME_ZSFLAG_SELECT_ALL;
4013 req->status = NVME_SUCCESS;
4015 if (!all) {
4016 status = nvme_get_mgmt_zone_slba_idx(ns, &req->cmd, &slba, &zone_idx);
4017 if (status) {
4018 return status;
4022 zone = &ns->zone_array[zone_idx];
4023 if (slba != zone->d.zslba && action != NVME_ZONE_ACTION_ZRWA_FLUSH) {
4024 trace_pci_nvme_err_unaligned_zone_cmd(action, slba, zone->d.zslba);
4025 return NVME_INVALID_FIELD | NVME_DNR;
4028 switch (action) {
4030 case NVME_ZONE_ACTION_OPEN:
4031 if (all) {
4032 proc_mask = NVME_PROC_CLOSED_ZONES;
4034 trace_pci_nvme_open_zone(slba, zone_idx, all);
4035 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_open_zone, req);
4036 break;
4038 case NVME_ZONE_ACTION_CLOSE:
4039 if (all) {
4040 proc_mask = NVME_PROC_OPENED_ZONES;
4042 trace_pci_nvme_close_zone(slba, zone_idx, all);
4043 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_close_zone, req);
4044 break;
4046 case NVME_ZONE_ACTION_FINISH:
4047 if (all) {
4048 proc_mask = NVME_PROC_OPENED_ZONES | NVME_PROC_CLOSED_ZONES;
4050 trace_pci_nvme_finish_zone(slba, zone_idx, all);
4051 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_finish_zone, req);
4052 break;
4054 case NVME_ZONE_ACTION_RESET:
4055 trace_pci_nvme_reset_zone(slba, zone_idx, all);
4057 iocb = blk_aio_get(&nvme_zone_reset_aiocb_info, ns->blkconf.blk,
4058 nvme_misc_cb, req);
4060 iocb->req = req;
4061 iocb->ret = 0;
4062 iocb->all = all;
4063 iocb->idx = zone_idx;
4064 iocb->zone = NULL;
4066 req->aiocb = &iocb->common;
4067 nvme_zone_reset_cb(iocb, 0);
4069 return NVME_NO_COMPLETE;
4071 case NVME_ZONE_ACTION_OFFLINE:
4072 if (all) {
4073 proc_mask = NVME_PROC_READ_ONLY_ZONES;
4075 trace_pci_nvme_offline_zone(slba, zone_idx, all);
4076 status = nvme_do_zone_op(ns, zone, proc_mask, nvme_offline_zone, req);
4077 break;
4079 case NVME_ZONE_ACTION_SET_ZD_EXT:
4080 trace_pci_nvme_set_descriptor_extension(slba, zone_idx);
4081 if (all || !ns->params.zd_extension_size) {
4082 return NVME_INVALID_FIELD | NVME_DNR;
4084 zd_ext = nvme_get_zd_extension(ns, zone_idx);
4085 status = nvme_h2c(n, zd_ext, ns->params.zd_extension_size, req);
4086 if (status) {
4087 trace_pci_nvme_err_zd_extension_map_error(zone_idx);
4088 return status;
4091 status = nvme_set_zd_ext(ns, zone);
4092 if (status == NVME_SUCCESS) {
4093 trace_pci_nvme_zd_extension_set(zone_idx);
4094 return status;
4096 break;
4098 case NVME_ZONE_ACTION_ZRWA_FLUSH:
4099 if (all) {
4100 return NVME_INVALID_FIELD | NVME_DNR;
4103 return nvme_zone_mgmt_send_zrwa_flush(n, zone, slba, req);
4105 default:
4106 trace_pci_nvme_err_invalid_mgmt_action(action);
4107 status = NVME_INVALID_FIELD;
4110 if (status == NVME_ZONE_INVAL_TRANSITION) {
4111 trace_pci_nvme_err_invalid_zone_state_transition(action, slba,
4112 zone->d.za);
4114 if (status) {
4115 status |= NVME_DNR;
4118 return status;
4121 static bool nvme_zone_matches_filter(uint32_t zafs, NvmeZone *zl)
4123 NvmeZoneState zs = nvme_get_zone_state(zl);
4125 switch (zafs) {
4126 case NVME_ZONE_REPORT_ALL:
4127 return true;
4128 case NVME_ZONE_REPORT_EMPTY:
4129 return zs == NVME_ZONE_STATE_EMPTY;
4130 case NVME_ZONE_REPORT_IMPLICITLY_OPEN:
4131 return zs == NVME_ZONE_STATE_IMPLICITLY_OPEN;
4132 case NVME_ZONE_REPORT_EXPLICITLY_OPEN:
4133 return zs == NVME_ZONE_STATE_EXPLICITLY_OPEN;
4134 case NVME_ZONE_REPORT_CLOSED:
4135 return zs == NVME_ZONE_STATE_CLOSED;
4136 case NVME_ZONE_REPORT_FULL:
4137 return zs == NVME_ZONE_STATE_FULL;
4138 case NVME_ZONE_REPORT_READ_ONLY:
4139 return zs == NVME_ZONE_STATE_READ_ONLY;
4140 case NVME_ZONE_REPORT_OFFLINE:
4141 return zs == NVME_ZONE_STATE_OFFLINE;
4142 default:
4143 return false;
4147 static uint16_t nvme_zone_mgmt_recv(NvmeCtrl *n, NvmeRequest *req)
4149 NvmeCmd *cmd = (NvmeCmd *)&req->cmd;
4150 NvmeNamespace *ns = req->ns;
4151 /* cdw12 is zero-based number of dwords to return. Convert to bytes */
4152 uint32_t data_size = (le32_to_cpu(cmd->cdw12) + 1) << 2;
4153 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
4154 uint32_t zone_idx, zra, zrasf, partial;
4155 uint64_t max_zones, nr_zones = 0;
4156 uint16_t status;
4157 uint64_t slba;
4158 NvmeZoneDescr *z;
4159 NvmeZone *zone;
4160 NvmeZoneReportHeader *header;
4161 void *buf, *buf_p;
4162 size_t zone_entry_sz;
4163 int i;
4165 req->status = NVME_SUCCESS;
4167 status = nvme_get_mgmt_zone_slba_idx(ns, cmd, &slba, &zone_idx);
4168 if (status) {
4169 return status;
4172 zra = dw13 & 0xff;
4173 if (zra != NVME_ZONE_REPORT && zra != NVME_ZONE_REPORT_EXTENDED) {
4174 return NVME_INVALID_FIELD | NVME_DNR;
4176 if (zra == NVME_ZONE_REPORT_EXTENDED && !ns->params.zd_extension_size) {
4177 return NVME_INVALID_FIELD | NVME_DNR;
4180 zrasf = (dw13 >> 8) & 0xff;
4181 if (zrasf > NVME_ZONE_REPORT_OFFLINE) {
4182 return NVME_INVALID_FIELD | NVME_DNR;
4185 if (data_size < sizeof(NvmeZoneReportHeader)) {
4186 return NVME_INVALID_FIELD | NVME_DNR;
4189 status = nvme_check_mdts(n, data_size);
4190 if (status) {
4191 return status;
4194 partial = (dw13 >> 16) & 0x01;
4196 zone_entry_sz = sizeof(NvmeZoneDescr);
4197 if (zra == NVME_ZONE_REPORT_EXTENDED) {
4198 zone_entry_sz += ns->params.zd_extension_size;
4201 max_zones = (data_size - sizeof(NvmeZoneReportHeader)) / zone_entry_sz;
4202 buf = g_malloc0(data_size);
4204 zone = &ns->zone_array[zone_idx];
4205 for (i = zone_idx; i < ns->num_zones; i++) {
4206 if (partial && nr_zones >= max_zones) {
4207 break;
4209 if (nvme_zone_matches_filter(zrasf, zone++)) {
4210 nr_zones++;
4213 header = buf;
4214 header->nr_zones = cpu_to_le64(nr_zones);
4216 buf_p = buf + sizeof(NvmeZoneReportHeader);
4217 for (; zone_idx < ns->num_zones && max_zones > 0; zone_idx++) {
4218 zone = &ns->zone_array[zone_idx];
4219 if (nvme_zone_matches_filter(zrasf, zone)) {
4220 z = buf_p;
4221 buf_p += sizeof(NvmeZoneDescr);
4223 z->zt = zone->d.zt;
4224 z->zs = zone->d.zs;
4225 z->zcap = cpu_to_le64(zone->d.zcap);
4226 z->zslba = cpu_to_le64(zone->d.zslba);
4227 z->za = zone->d.za;
4229 if (nvme_wp_is_valid(zone)) {
4230 z->wp = cpu_to_le64(zone->d.wp);
4231 } else {
4232 z->wp = cpu_to_le64(~0ULL);
4235 if (zra == NVME_ZONE_REPORT_EXTENDED) {
4236 if (zone->d.za & NVME_ZA_ZD_EXT_VALID) {
4237 memcpy(buf_p, nvme_get_zd_extension(ns, zone_idx),
4238 ns->params.zd_extension_size);
4240 buf_p += ns->params.zd_extension_size;
4243 max_zones--;
4247 status = nvme_c2h(n, (uint8_t *)buf, data_size, req);
4249 g_free(buf);
4251 return status;
4254 static uint16_t nvme_io_mgmt_recv_ruhs(NvmeCtrl *n, NvmeRequest *req,
4255 size_t len)
4257 NvmeNamespace *ns = req->ns;
4258 NvmeEnduranceGroup *endgrp;
4259 NvmeRuhStatus *hdr;
4260 NvmeRuhStatusDescr *ruhsd;
4261 unsigned int nruhsd;
4262 uint16_t rg, ph, *ruhid;
4263 size_t trans_len;
4264 g_autofree uint8_t *buf = NULL;
4266 if (!n->subsys) {
4267 return NVME_INVALID_FIELD | NVME_DNR;
4270 if (ns->params.nsid == 0 || ns->params.nsid == 0xffffffff) {
4271 return NVME_INVALID_NSID | NVME_DNR;
4274 if (!n->subsys->endgrp.fdp.enabled) {
4275 return NVME_FDP_DISABLED | NVME_DNR;
4278 endgrp = ns->endgrp;
4280 nruhsd = ns->fdp.nphs * endgrp->fdp.nrg;
4281 trans_len = sizeof(NvmeRuhStatus) + nruhsd * sizeof(NvmeRuhStatusDescr);
4282 buf = g_malloc(trans_len);
4284 trans_len = MIN(trans_len, len);
4286 hdr = (NvmeRuhStatus *)buf;
4287 ruhsd = (NvmeRuhStatusDescr *)(buf + sizeof(NvmeRuhStatus));
4289 hdr->nruhsd = cpu_to_le16(nruhsd);
4291 ruhid = ns->fdp.phs;
4293 for (ph = 0; ph < ns->fdp.nphs; ph++, ruhid++) {
4294 NvmeRuHandle *ruh = &endgrp->fdp.ruhs[*ruhid];
4296 for (rg = 0; rg < endgrp->fdp.nrg; rg++, ruhsd++) {
4297 uint16_t pid = nvme_make_pid(ns, rg, ph);
4299 ruhsd->pid = cpu_to_le16(pid);
4300 ruhsd->ruhid = *ruhid;
4301 ruhsd->earutr = 0;
4302 ruhsd->ruamw = cpu_to_le64(ruh->rus[rg].ruamw);
4306 return nvme_c2h(n, buf, trans_len, req);
4309 static uint16_t nvme_io_mgmt_recv(NvmeCtrl *n, NvmeRequest *req)
4311 NvmeCmd *cmd = &req->cmd;
4312 uint32_t cdw10 = le32_to_cpu(cmd->cdw10);
4313 uint32_t numd = le32_to_cpu(cmd->cdw11);
4314 uint8_t mo = (cdw10 & 0xff);
4315 size_t len = (numd + 1) << 2;
4317 switch (mo) {
4318 case NVME_IOMR_MO_NOP:
4319 return 0;
4320 case NVME_IOMR_MO_RUH_STATUS:
4321 return nvme_io_mgmt_recv_ruhs(n, req, len);
4322 default:
4323 return NVME_INVALID_FIELD | NVME_DNR;
4327 static uint16_t nvme_io_mgmt_send_ruh_update(NvmeCtrl *n, NvmeRequest *req)
4329 NvmeCmd *cmd = &req->cmd;
4330 NvmeNamespace *ns = req->ns;
4331 uint32_t cdw10 = le32_to_cpu(cmd->cdw10);
4332 uint16_t ret = NVME_SUCCESS;
4333 uint32_t npid = (cdw10 >> 1) + 1;
4334 unsigned int i = 0;
4335 g_autofree uint16_t *pids = NULL;
4336 uint32_t maxnpid = n->subsys->endgrp.fdp.nrg * n->subsys->endgrp.fdp.nruh;
4338 if (unlikely(npid >= MIN(NVME_FDP_MAXPIDS, maxnpid))) {
4339 return NVME_INVALID_FIELD | NVME_DNR;
4342 pids = g_new(uint16_t, npid);
4344 ret = nvme_h2c(n, pids, npid * sizeof(uint16_t), req);
4345 if (ret) {
4346 return ret;
4349 for (; i < npid; i++) {
4350 if (!nvme_update_ruh(n, ns, pids[i])) {
4351 return NVME_INVALID_FIELD | NVME_DNR;
4355 return ret;
4358 static uint16_t nvme_io_mgmt_send(NvmeCtrl *n, NvmeRequest *req)
4360 NvmeCmd *cmd = &req->cmd;
4361 uint32_t cdw10 = le32_to_cpu(cmd->cdw10);
4362 uint8_t mo = (cdw10 & 0xff);
4364 switch (mo) {
4365 case NVME_IOMS_MO_NOP:
4366 return 0;
4367 case NVME_IOMS_MO_RUH_UPDATE:
4368 return nvme_io_mgmt_send_ruh_update(n, req);
4369 default:
4370 return NVME_INVALID_FIELD | NVME_DNR;
4374 static uint16_t nvme_io_cmd(NvmeCtrl *n, NvmeRequest *req)
4376 NvmeNamespace *ns;
4377 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
4379 trace_pci_nvme_io_cmd(nvme_cid(req), nsid, nvme_sqid(req),
4380 req->cmd.opcode, nvme_io_opc_str(req->cmd.opcode));
4382 if (!nvme_nsid_valid(n, nsid)) {
4383 return NVME_INVALID_NSID | NVME_DNR;
4387 * In the base NVM command set, Flush may apply to all namespaces
4388 * (indicated by NSID being set to FFFFFFFFh). But if that feature is used
4389 * along with TP 4056 (Namespace Types), it may be pretty screwed up.
4391 * If NSID is indeed set to FFFFFFFFh, we simply cannot associate the
4392 * opcode with a specific command since we cannot determine a unique I/O
4393 * command set. Opcode 0h could have any other meaning than something
4394 * equivalent to flushing and say it DOES have completely different
4395 * semantics in some other command set - does an NSID of FFFFFFFFh then
4396 * mean "for all namespaces, apply whatever command set specific command
4397 * that uses the 0h opcode?" Or does it mean "for all namespaces, apply
4398 * whatever command that uses the 0h opcode if, and only if, it allows NSID
4399 * to be FFFFFFFFh"?
4401 * Anyway (and luckily), for now, we do not care about this since the
4402 * device only supports namespace types that includes the NVM Flush command
4403 * (NVM and Zoned), so always do an NVM Flush.
4405 if (req->cmd.opcode == NVME_CMD_FLUSH) {
4406 return nvme_flush(n, req);
4409 ns = nvme_ns(n, nsid);
4410 if (unlikely(!ns)) {
4411 return NVME_INVALID_FIELD | NVME_DNR;
4414 if (!(ns->iocs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
4415 trace_pci_nvme_err_invalid_opc(req->cmd.opcode);
4416 return NVME_INVALID_OPCODE | NVME_DNR;
4419 if (ns->status) {
4420 return ns->status;
4423 if (NVME_CMD_FLAGS_FUSE(req->cmd.flags)) {
4424 return NVME_INVALID_FIELD;
4427 req->ns = ns;
4429 switch (req->cmd.opcode) {
4430 case NVME_CMD_WRITE_ZEROES:
4431 return nvme_write_zeroes(n, req);
4432 case NVME_CMD_ZONE_APPEND:
4433 return nvme_zone_append(n, req);
4434 case NVME_CMD_WRITE:
4435 return nvme_write(n, req);
4436 case NVME_CMD_READ:
4437 return nvme_read(n, req);
4438 case NVME_CMD_COMPARE:
4439 return nvme_compare(n, req);
4440 case NVME_CMD_DSM:
4441 return nvme_dsm(n, req);
4442 case NVME_CMD_VERIFY:
4443 return nvme_verify(n, req);
4444 case NVME_CMD_COPY:
4445 return nvme_copy(n, req);
4446 case NVME_CMD_ZONE_MGMT_SEND:
4447 return nvme_zone_mgmt_send(n, req);
4448 case NVME_CMD_ZONE_MGMT_RECV:
4449 return nvme_zone_mgmt_recv(n, req);
4450 case NVME_CMD_IO_MGMT_RECV:
4451 return nvme_io_mgmt_recv(n, req);
4452 case NVME_CMD_IO_MGMT_SEND:
4453 return nvme_io_mgmt_send(n, req);
4454 default:
4455 assert(false);
4458 return NVME_INVALID_OPCODE | NVME_DNR;
4461 static void nvme_cq_notifier(EventNotifier *e)
4463 NvmeCQueue *cq = container_of(e, NvmeCQueue, notifier);
4464 NvmeCtrl *n = cq->ctrl;
4466 if (!event_notifier_test_and_clear(e)) {
4467 return;
4470 nvme_update_cq_head(cq);
4472 if (cq->tail == cq->head) {
4473 if (cq->irq_enabled) {
4474 n->cq_pending--;
4477 nvme_irq_deassert(n, cq);
4480 qemu_bh_schedule(cq->bh);
4483 static int nvme_init_cq_ioeventfd(NvmeCQueue *cq)
4485 NvmeCtrl *n = cq->ctrl;
4486 uint16_t offset = (cq->cqid << 3) + (1 << 2);
4487 int ret;
4489 ret = event_notifier_init(&cq->notifier, 0);
4490 if (ret < 0) {
4491 return ret;
4494 event_notifier_set_handler(&cq->notifier, nvme_cq_notifier);
4495 memory_region_add_eventfd(&n->iomem,
4496 0x1000 + offset, 4, false, 0, &cq->notifier);
4498 return 0;
4501 static void nvme_sq_notifier(EventNotifier *e)
4503 NvmeSQueue *sq = container_of(e, NvmeSQueue, notifier);
4505 if (!event_notifier_test_and_clear(e)) {
4506 return;
4509 nvme_process_sq(sq);
4512 static int nvme_init_sq_ioeventfd(NvmeSQueue *sq)
4514 NvmeCtrl *n = sq->ctrl;
4515 uint16_t offset = sq->sqid << 3;
4516 int ret;
4518 ret = event_notifier_init(&sq->notifier, 0);
4519 if (ret < 0) {
4520 return ret;
4523 event_notifier_set_handler(&sq->notifier, nvme_sq_notifier);
4524 memory_region_add_eventfd(&n->iomem,
4525 0x1000 + offset, 4, false, 0, &sq->notifier);
4527 return 0;
4530 static void nvme_free_sq(NvmeSQueue *sq, NvmeCtrl *n)
4532 uint16_t offset = sq->sqid << 3;
4534 n->sq[sq->sqid] = NULL;
4535 qemu_bh_delete(sq->bh);
4536 if (sq->ioeventfd_enabled) {
4537 memory_region_del_eventfd(&n->iomem,
4538 0x1000 + offset, 4, false, 0, &sq->notifier);
4539 event_notifier_set_handler(&sq->notifier, NULL);
4540 event_notifier_cleanup(&sq->notifier);
4542 g_free(sq->io_req);
4543 if (sq->sqid) {
4544 g_free(sq);
4548 static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeRequest *req)
4550 NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
4551 NvmeRequest *r, *next;
4552 NvmeSQueue *sq;
4553 NvmeCQueue *cq;
4554 uint16_t qid = le16_to_cpu(c->qid);
4556 if (unlikely(!qid || nvme_check_sqid(n, qid))) {
4557 trace_pci_nvme_err_invalid_del_sq(qid);
4558 return NVME_INVALID_QID | NVME_DNR;
4561 trace_pci_nvme_del_sq(qid);
4563 sq = n->sq[qid];
4564 while (!QTAILQ_EMPTY(&sq->out_req_list)) {
4565 r = QTAILQ_FIRST(&sq->out_req_list);
4566 assert(r->aiocb);
4567 blk_aio_cancel(r->aiocb);
4570 assert(QTAILQ_EMPTY(&sq->out_req_list));
4572 if (!nvme_check_cqid(n, sq->cqid)) {
4573 cq = n->cq[sq->cqid];
4574 QTAILQ_REMOVE(&cq->sq_list, sq, entry);
4576 nvme_post_cqes(cq);
4577 QTAILQ_FOREACH_SAFE(r, &cq->req_list, entry, next) {
4578 if (r->sq == sq) {
4579 QTAILQ_REMOVE(&cq->req_list, r, entry);
4580 QTAILQ_INSERT_TAIL(&sq->req_list, r, entry);
4585 nvme_free_sq(sq, n);
4586 return NVME_SUCCESS;
4589 static void nvme_init_sq(NvmeSQueue *sq, NvmeCtrl *n, uint64_t dma_addr,
4590 uint16_t sqid, uint16_t cqid, uint16_t size)
4592 int i;
4593 NvmeCQueue *cq;
4595 sq->ctrl = n;
4596 sq->dma_addr = dma_addr;
4597 sq->sqid = sqid;
4598 sq->size = size;
4599 sq->cqid = cqid;
4600 sq->head = sq->tail = 0;
4601 sq->io_req = g_new0(NvmeRequest, sq->size);
4603 QTAILQ_INIT(&sq->req_list);
4604 QTAILQ_INIT(&sq->out_req_list);
4605 for (i = 0; i < sq->size; i++) {
4606 sq->io_req[i].sq = sq;
4607 QTAILQ_INSERT_TAIL(&(sq->req_list), &sq->io_req[i], entry);
4610 sq->bh = qemu_bh_new(nvme_process_sq, sq);
4612 if (n->dbbuf_enabled) {
4613 sq->db_addr = n->dbbuf_dbs + (sqid << 3);
4614 sq->ei_addr = n->dbbuf_eis + (sqid << 3);
4616 if (n->params.ioeventfd && sq->sqid != 0) {
4617 if (!nvme_init_sq_ioeventfd(sq)) {
4618 sq->ioeventfd_enabled = true;
4623 assert(n->cq[cqid]);
4624 cq = n->cq[cqid];
4625 QTAILQ_INSERT_TAIL(&(cq->sq_list), sq, entry);
4626 n->sq[sqid] = sq;
4629 static uint16_t nvme_create_sq(NvmeCtrl *n, NvmeRequest *req)
4631 NvmeSQueue *sq;
4632 NvmeCreateSq *c = (NvmeCreateSq *)&req->cmd;
4634 uint16_t cqid = le16_to_cpu(c->cqid);
4635 uint16_t sqid = le16_to_cpu(c->sqid);
4636 uint16_t qsize = le16_to_cpu(c->qsize);
4637 uint16_t qflags = le16_to_cpu(c->sq_flags);
4638 uint64_t prp1 = le64_to_cpu(c->prp1);
4640 trace_pci_nvme_create_sq(prp1, sqid, cqid, qsize, qflags);
4642 if (unlikely(!cqid || nvme_check_cqid(n, cqid))) {
4643 trace_pci_nvme_err_invalid_create_sq_cqid(cqid);
4644 return NVME_INVALID_CQID | NVME_DNR;
4646 if (unlikely(!sqid || sqid > n->conf_ioqpairs || n->sq[sqid] != NULL)) {
4647 trace_pci_nvme_err_invalid_create_sq_sqid(sqid);
4648 return NVME_INVALID_QID | NVME_DNR;
4650 if (unlikely(!qsize || qsize > NVME_CAP_MQES(ldq_le_p(&n->bar.cap)))) {
4651 trace_pci_nvme_err_invalid_create_sq_size(qsize);
4652 return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
4654 if (unlikely(prp1 & (n->page_size - 1))) {
4655 trace_pci_nvme_err_invalid_create_sq_addr(prp1);
4656 return NVME_INVALID_PRP_OFFSET | NVME_DNR;
4658 if (unlikely(!(NVME_SQ_FLAGS_PC(qflags)))) {
4659 trace_pci_nvme_err_invalid_create_sq_qflags(NVME_SQ_FLAGS_PC(qflags));
4660 return NVME_INVALID_FIELD | NVME_DNR;
4662 sq = g_malloc0(sizeof(*sq));
4663 nvme_init_sq(sq, n, prp1, sqid, cqid, qsize + 1);
4664 return NVME_SUCCESS;
4667 struct nvme_stats {
4668 uint64_t units_read;
4669 uint64_t units_written;
4670 uint64_t read_commands;
4671 uint64_t write_commands;
4674 static void nvme_set_blk_stats(NvmeNamespace *ns, struct nvme_stats *stats)
4676 BlockAcctStats *s = blk_get_stats(ns->blkconf.blk);
4678 stats->units_read += s->nr_bytes[BLOCK_ACCT_READ];
4679 stats->units_written += s->nr_bytes[BLOCK_ACCT_WRITE];
4680 stats->read_commands += s->nr_ops[BLOCK_ACCT_READ];
4681 stats->write_commands += s->nr_ops[BLOCK_ACCT_WRITE];
4684 static uint16_t nvme_smart_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4685 uint64_t off, NvmeRequest *req)
4687 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
4688 struct nvme_stats stats = { 0 };
4689 NvmeSmartLog smart = { 0 };
4690 uint32_t trans_len;
4691 NvmeNamespace *ns;
4692 time_t current_ms;
4693 uint64_t u_read, u_written;
4695 if (off >= sizeof(smart)) {
4696 return NVME_INVALID_FIELD | NVME_DNR;
4699 if (nsid != 0xffffffff) {
4700 ns = nvme_ns(n, nsid);
4701 if (!ns) {
4702 return NVME_INVALID_NSID | NVME_DNR;
4704 nvme_set_blk_stats(ns, &stats);
4705 } else {
4706 int i;
4708 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4709 ns = nvme_ns(n, i);
4710 if (!ns) {
4711 continue;
4713 nvme_set_blk_stats(ns, &stats);
4717 trans_len = MIN(sizeof(smart) - off, buf_len);
4718 smart.critical_warning = n->smart_critical_warning;
4720 u_read = DIV_ROUND_UP(stats.units_read >> BDRV_SECTOR_BITS, 1000);
4721 u_written = DIV_ROUND_UP(stats.units_written >> BDRV_SECTOR_BITS, 1000);
4723 smart.data_units_read[0] = cpu_to_le64(u_read);
4724 smart.data_units_written[0] = cpu_to_le64(u_written);
4725 smart.host_read_commands[0] = cpu_to_le64(stats.read_commands);
4726 smart.host_write_commands[0] = cpu_to_le64(stats.write_commands);
4728 smart.temperature = cpu_to_le16(n->temperature);
4730 if ((n->temperature >= n->features.temp_thresh_hi) ||
4731 (n->temperature <= n->features.temp_thresh_low)) {
4732 smart.critical_warning |= NVME_SMART_TEMPERATURE;
4735 current_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
4736 smart.power_on_hours[0] =
4737 cpu_to_le64((((current_ms - n->starttime_ms) / 1000) / 60) / 60);
4739 if (!rae) {
4740 nvme_clear_events(n, NVME_AER_TYPE_SMART);
4743 return nvme_c2h(n, (uint8_t *) &smart + off, trans_len, req);
4746 static uint16_t nvme_endgrp_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4747 uint64_t off, NvmeRequest *req)
4749 uint32_t dw11 = le32_to_cpu(req->cmd.cdw11);
4750 uint16_t endgrpid = (dw11 >> 16) & 0xffff;
4751 struct nvme_stats stats = {};
4752 NvmeEndGrpLog info = {};
4753 int i;
4755 if (!n->subsys || endgrpid != 0x1) {
4756 return NVME_INVALID_FIELD | NVME_DNR;
4759 if (off >= sizeof(info)) {
4760 return NVME_INVALID_FIELD | NVME_DNR;
4763 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4764 NvmeNamespace *ns = nvme_subsys_ns(n->subsys, i);
4765 if (!ns) {
4766 continue;
4769 nvme_set_blk_stats(ns, &stats);
4772 info.data_units_read[0] =
4773 cpu_to_le64(DIV_ROUND_UP(stats.units_read / 1000000000, 1000000000));
4774 info.data_units_written[0] =
4775 cpu_to_le64(DIV_ROUND_UP(stats.units_written / 1000000000, 1000000000));
4776 info.media_units_written[0] =
4777 cpu_to_le64(DIV_ROUND_UP(stats.units_written / 1000000000, 1000000000));
4779 info.host_read_commands[0] = cpu_to_le64(stats.read_commands);
4780 info.host_write_commands[0] = cpu_to_le64(stats.write_commands);
4782 buf_len = MIN(sizeof(info) - off, buf_len);
4784 return nvme_c2h(n, (uint8_t *)&info + off, buf_len, req);
4788 static uint16_t nvme_fw_log_info(NvmeCtrl *n, uint32_t buf_len, uint64_t off,
4789 NvmeRequest *req)
4791 uint32_t trans_len;
4792 NvmeFwSlotInfoLog fw_log = {
4793 .afi = 0x1,
4796 if (off >= sizeof(fw_log)) {
4797 return NVME_INVALID_FIELD | NVME_DNR;
4800 strpadcpy((char *)&fw_log.frs1, sizeof(fw_log.frs1), "1.0", ' ');
4801 trans_len = MIN(sizeof(fw_log) - off, buf_len);
4803 return nvme_c2h(n, (uint8_t *) &fw_log + off, trans_len, req);
4806 static uint16_t nvme_error_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4807 uint64_t off, NvmeRequest *req)
4809 uint32_t trans_len;
4810 NvmeErrorLog errlog;
4812 if (off >= sizeof(errlog)) {
4813 return NVME_INVALID_FIELD | NVME_DNR;
4816 if (!rae) {
4817 nvme_clear_events(n, NVME_AER_TYPE_ERROR);
4820 memset(&errlog, 0x0, sizeof(errlog));
4821 trans_len = MIN(sizeof(errlog) - off, buf_len);
4823 return nvme_c2h(n, (uint8_t *)&errlog, trans_len, req);
4826 static uint16_t nvme_changed_nslist(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4827 uint64_t off, NvmeRequest *req)
4829 uint32_t nslist[1024];
4830 uint32_t trans_len;
4831 int i = 0;
4832 uint32_t nsid;
4834 if (off >= sizeof(nslist)) {
4835 trace_pci_nvme_err_invalid_log_page_offset(off, sizeof(nslist));
4836 return NVME_INVALID_FIELD | NVME_DNR;
4839 memset(nslist, 0x0, sizeof(nslist));
4840 trans_len = MIN(sizeof(nslist) - off, buf_len);
4842 while ((nsid = find_first_bit(n->changed_nsids, NVME_CHANGED_NSID_SIZE)) !=
4843 NVME_CHANGED_NSID_SIZE) {
4845 * If more than 1024 namespaces, the first entry in the log page should
4846 * be set to FFFFFFFFh and the others to 0 as spec.
4848 if (i == ARRAY_SIZE(nslist)) {
4849 memset(nslist, 0x0, sizeof(nslist));
4850 nslist[0] = 0xffffffff;
4851 break;
4854 nslist[i++] = nsid;
4855 clear_bit(nsid, n->changed_nsids);
4859 * Remove all the remaining list entries in case returns directly due to
4860 * more than 1024 namespaces.
4862 if (nslist[0] == 0xffffffff) {
4863 bitmap_zero(n->changed_nsids, NVME_CHANGED_NSID_SIZE);
4866 if (!rae) {
4867 nvme_clear_events(n, NVME_AER_TYPE_NOTICE);
4870 return nvme_c2h(n, ((uint8_t *)nslist) + off, trans_len, req);
4873 static uint16_t nvme_cmd_effects(NvmeCtrl *n, uint8_t csi, uint32_t buf_len,
4874 uint64_t off, NvmeRequest *req)
4876 NvmeEffectsLog log = {};
4877 const uint32_t *src_iocs = NULL;
4878 uint32_t trans_len;
4880 if (off >= sizeof(log)) {
4881 trace_pci_nvme_err_invalid_log_page_offset(off, sizeof(log));
4882 return NVME_INVALID_FIELD | NVME_DNR;
4885 switch (NVME_CC_CSS(ldl_le_p(&n->bar.cc))) {
4886 case NVME_CC_CSS_NVM:
4887 src_iocs = nvme_cse_iocs_nvm;
4888 /* fall through */
4889 case NVME_CC_CSS_ADMIN_ONLY:
4890 break;
4891 case NVME_CC_CSS_CSI:
4892 switch (csi) {
4893 case NVME_CSI_NVM:
4894 src_iocs = nvme_cse_iocs_nvm;
4895 break;
4896 case NVME_CSI_ZONED:
4897 src_iocs = nvme_cse_iocs_zoned;
4898 break;
4902 memcpy(log.acs, nvme_cse_acs, sizeof(nvme_cse_acs));
4904 if (src_iocs) {
4905 memcpy(log.iocs, src_iocs, sizeof(log.iocs));
4908 trans_len = MIN(sizeof(log) - off, buf_len);
4910 return nvme_c2h(n, ((uint8_t *)&log) + off, trans_len, req);
4913 static size_t sizeof_fdp_conf_descr(size_t nruh, size_t vss)
4915 size_t entry_siz = sizeof(NvmeFdpDescrHdr) + nruh * sizeof(NvmeRuhDescr)
4916 + vss;
4917 return ROUND_UP(entry_siz, 8);
4920 static uint16_t nvme_fdp_confs(NvmeCtrl *n, uint32_t endgrpid, uint32_t buf_len,
4921 uint64_t off, NvmeRequest *req)
4923 uint32_t log_size, trans_len;
4924 g_autofree uint8_t *buf = NULL;
4925 NvmeFdpDescrHdr *hdr;
4926 NvmeRuhDescr *ruhd;
4927 NvmeEnduranceGroup *endgrp;
4928 NvmeFdpConfsHdr *log;
4929 size_t nruh, fdp_descr_size;
4930 int i;
4932 if (endgrpid != 1 || !n->subsys) {
4933 return NVME_INVALID_FIELD | NVME_DNR;
4936 endgrp = &n->subsys->endgrp;
4938 if (endgrp->fdp.enabled) {
4939 nruh = endgrp->fdp.nruh;
4940 } else {
4941 nruh = 1;
4944 fdp_descr_size = sizeof_fdp_conf_descr(nruh, FDPVSS);
4945 log_size = sizeof(NvmeFdpConfsHdr) + fdp_descr_size;
4947 if (off >= log_size) {
4948 return NVME_INVALID_FIELD | NVME_DNR;
4951 trans_len = MIN(log_size - off, buf_len);
4953 buf = g_malloc0(log_size);
4954 log = (NvmeFdpConfsHdr *)buf;
4955 hdr = (NvmeFdpDescrHdr *)(log + 1);
4956 ruhd = (NvmeRuhDescr *)(buf + sizeof(*log) + sizeof(*hdr));
4958 log->num_confs = cpu_to_le16(0);
4959 log->size = cpu_to_le32(log_size);
4961 hdr->descr_size = cpu_to_le16(fdp_descr_size);
4962 if (endgrp->fdp.enabled) {
4963 hdr->fdpa = FIELD_DP8(hdr->fdpa, FDPA, VALID, 1);
4964 hdr->fdpa = FIELD_DP8(hdr->fdpa, FDPA, RGIF, endgrp->fdp.rgif);
4965 hdr->nrg = cpu_to_le16(endgrp->fdp.nrg);
4966 hdr->nruh = cpu_to_le16(endgrp->fdp.nruh);
4967 hdr->maxpids = cpu_to_le16(NVME_FDP_MAXPIDS - 1);
4968 hdr->nnss = cpu_to_le32(NVME_MAX_NAMESPACES);
4969 hdr->runs = cpu_to_le64(endgrp->fdp.runs);
4971 for (i = 0; i < nruh; i++) {
4972 ruhd->ruht = NVME_RUHT_INITIALLY_ISOLATED;
4973 ruhd++;
4975 } else {
4976 /* 1 bit for RUH in PIF -> 2 RUHs max. */
4977 hdr->nrg = cpu_to_le16(1);
4978 hdr->nruh = cpu_to_le16(1);
4979 hdr->maxpids = cpu_to_le16(NVME_FDP_MAXPIDS - 1);
4980 hdr->nnss = cpu_to_le32(1);
4981 hdr->runs = cpu_to_le64(96 * MiB);
4983 ruhd->ruht = NVME_RUHT_INITIALLY_ISOLATED;
4986 return nvme_c2h(n, (uint8_t *)buf + off, trans_len, req);
4989 static uint16_t nvme_fdp_ruh_usage(NvmeCtrl *n, uint32_t endgrpid,
4990 uint32_t dw10, uint32_t dw12,
4991 uint32_t buf_len, uint64_t off,
4992 NvmeRequest *req)
4994 NvmeRuHandle *ruh;
4995 NvmeRuhuLog *hdr;
4996 NvmeRuhuDescr *ruhud;
4997 NvmeEnduranceGroup *endgrp;
4998 g_autofree uint8_t *buf = NULL;
4999 uint32_t log_size, trans_len;
5000 uint16_t i;
5002 if (endgrpid != 1 || !n->subsys) {
5003 return NVME_INVALID_FIELD | NVME_DNR;
5006 endgrp = &n->subsys->endgrp;
5008 if (!endgrp->fdp.enabled) {
5009 return NVME_FDP_DISABLED | NVME_DNR;
5012 log_size = sizeof(NvmeRuhuLog) + endgrp->fdp.nruh * sizeof(NvmeRuhuDescr);
5014 if (off >= log_size) {
5015 return NVME_INVALID_FIELD | NVME_DNR;
5018 trans_len = MIN(log_size - off, buf_len);
5020 buf = g_malloc0(log_size);
5021 hdr = (NvmeRuhuLog *)buf;
5022 ruhud = (NvmeRuhuDescr *)(hdr + 1);
5024 ruh = endgrp->fdp.ruhs;
5025 hdr->nruh = cpu_to_le16(endgrp->fdp.nruh);
5027 for (i = 0; i < endgrp->fdp.nruh; i++, ruhud++, ruh++) {
5028 ruhud->ruha = ruh->ruha;
5031 return nvme_c2h(n, (uint8_t *)buf + off, trans_len, req);
5034 static uint16_t nvme_fdp_stats(NvmeCtrl *n, uint32_t endgrpid, uint32_t buf_len,
5035 uint64_t off, NvmeRequest *req)
5037 NvmeEnduranceGroup *endgrp;
5038 NvmeFdpStatsLog log = {};
5039 uint32_t trans_len;
5041 if (off >= sizeof(NvmeFdpStatsLog)) {
5042 return NVME_INVALID_FIELD | NVME_DNR;
5045 if (endgrpid != 1 || !n->subsys) {
5046 return NVME_INVALID_FIELD | NVME_DNR;
5049 if (!n->subsys->endgrp.fdp.enabled) {
5050 return NVME_FDP_DISABLED | NVME_DNR;
5053 endgrp = &n->subsys->endgrp;
5055 trans_len = MIN(sizeof(log) - off, buf_len);
5057 /* spec value is 128 bit, we only use 64 bit */
5058 log.hbmw[0] = cpu_to_le64(endgrp->fdp.hbmw);
5059 log.mbmw[0] = cpu_to_le64(endgrp->fdp.mbmw);
5060 log.mbe[0] = cpu_to_le64(endgrp->fdp.mbe);
5062 return nvme_c2h(n, (uint8_t *)&log + off, trans_len, req);
5065 static uint16_t nvme_fdp_events(NvmeCtrl *n, uint32_t endgrpid,
5066 uint32_t buf_len, uint64_t off,
5067 NvmeRequest *req)
5069 NvmeEnduranceGroup *endgrp;
5070 NvmeCmd *cmd = &req->cmd;
5071 bool host_events = (cmd->cdw10 >> 8) & 0x1;
5072 uint32_t log_size, trans_len;
5073 NvmeFdpEventBuffer *ebuf;
5074 g_autofree NvmeFdpEventsLog *elog = NULL;
5075 NvmeFdpEvent *event;
5077 if (endgrpid != 1 || !n->subsys) {
5078 return NVME_INVALID_FIELD | NVME_DNR;
5081 endgrp = &n->subsys->endgrp;
5083 if (!endgrp->fdp.enabled) {
5084 return NVME_FDP_DISABLED | NVME_DNR;
5087 if (host_events) {
5088 ebuf = &endgrp->fdp.host_events;
5089 } else {
5090 ebuf = &endgrp->fdp.ctrl_events;
5093 log_size = sizeof(NvmeFdpEventsLog) + ebuf->nelems * sizeof(NvmeFdpEvent);
5094 trans_len = MIN(log_size - off, buf_len);
5095 elog = g_malloc0(log_size);
5096 elog->num_events = cpu_to_le32(ebuf->nelems);
5097 event = (NvmeFdpEvent *)(elog + 1);
5099 if (ebuf->nelems && ebuf->start == ebuf->next) {
5100 unsigned int nelems = (NVME_FDP_MAX_EVENTS - ebuf->start);
5101 /* wrap over, copy [start;NVME_FDP_MAX_EVENTS[ and [0; next[ */
5102 memcpy(event, &ebuf->events[ebuf->start],
5103 sizeof(NvmeFdpEvent) * nelems);
5104 memcpy(event + nelems, ebuf->events,
5105 sizeof(NvmeFdpEvent) * ebuf->next);
5106 } else if (ebuf->start < ebuf->next) {
5107 memcpy(event, &ebuf->events[ebuf->start],
5108 sizeof(NvmeFdpEvent) * (ebuf->next - ebuf->start));
5111 return nvme_c2h(n, (uint8_t *)elog + off, trans_len, req);
5114 static uint16_t nvme_get_log(NvmeCtrl *n, NvmeRequest *req)
5116 NvmeCmd *cmd = &req->cmd;
5118 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
5119 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
5120 uint32_t dw12 = le32_to_cpu(cmd->cdw12);
5121 uint32_t dw13 = le32_to_cpu(cmd->cdw13);
5122 uint8_t lid = dw10 & 0xff;
5123 uint8_t lsp = (dw10 >> 8) & 0xf;
5124 uint8_t rae = (dw10 >> 15) & 0x1;
5125 uint8_t csi = le32_to_cpu(cmd->cdw14) >> 24;
5126 uint32_t numdl, numdu, lspi;
5127 uint64_t off, lpol, lpou;
5128 size_t len;
5129 uint16_t status;
5131 numdl = (dw10 >> 16);
5132 numdu = (dw11 & 0xffff);
5133 lspi = (dw11 >> 16);
5134 lpol = dw12;
5135 lpou = dw13;
5137 len = (((numdu << 16) | numdl) + 1) << 2;
5138 off = (lpou << 32ULL) | lpol;
5140 if (off & 0x3) {
5141 return NVME_INVALID_FIELD | NVME_DNR;
5144 trace_pci_nvme_get_log(nvme_cid(req), lid, lsp, rae, len, off);
5146 status = nvme_check_mdts(n, len);
5147 if (status) {
5148 return status;
5151 switch (lid) {
5152 case NVME_LOG_ERROR_INFO:
5153 return nvme_error_info(n, rae, len, off, req);
5154 case NVME_LOG_SMART_INFO:
5155 return nvme_smart_info(n, rae, len, off, req);
5156 case NVME_LOG_FW_SLOT_INFO:
5157 return nvme_fw_log_info(n, len, off, req);
5158 case NVME_LOG_CHANGED_NSLIST:
5159 return nvme_changed_nslist(n, rae, len, off, req);
5160 case NVME_LOG_CMD_EFFECTS:
5161 return nvme_cmd_effects(n, csi, len, off, req);
5162 case NVME_LOG_ENDGRP:
5163 return nvme_endgrp_info(n, rae, len, off, req);
5164 case NVME_LOG_FDP_CONFS:
5165 return nvme_fdp_confs(n, lspi, len, off, req);
5166 case NVME_LOG_FDP_RUH_USAGE:
5167 return nvme_fdp_ruh_usage(n, lspi, dw10, dw12, len, off, req);
5168 case NVME_LOG_FDP_STATS:
5169 return nvme_fdp_stats(n, lspi, len, off, req);
5170 case NVME_LOG_FDP_EVENTS:
5171 return nvme_fdp_events(n, lspi, len, off, req);
5172 default:
5173 trace_pci_nvme_err_invalid_log_page(nvme_cid(req), lid);
5174 return NVME_INVALID_FIELD | NVME_DNR;
5178 static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
5180 PCIDevice *pci = PCI_DEVICE(n);
5181 uint16_t offset = (cq->cqid << 3) + (1 << 2);
5183 n->cq[cq->cqid] = NULL;
5184 qemu_bh_delete(cq->bh);
5185 if (cq->ioeventfd_enabled) {
5186 memory_region_del_eventfd(&n->iomem,
5187 0x1000 + offset, 4, false, 0, &cq->notifier);
5188 event_notifier_set_handler(&cq->notifier, NULL);
5189 event_notifier_cleanup(&cq->notifier);
5191 if (msix_enabled(pci)) {
5192 msix_vector_unuse(pci, cq->vector);
5194 if (cq->cqid) {
5195 g_free(cq);
5199 static uint16_t nvme_del_cq(NvmeCtrl *n, NvmeRequest *req)
5201 NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
5202 NvmeCQueue *cq;
5203 uint16_t qid = le16_to_cpu(c->qid);
5205 if (unlikely(!qid || nvme_check_cqid(n, qid))) {
5206 trace_pci_nvme_err_invalid_del_cq_cqid(qid);
5207 return NVME_INVALID_CQID | NVME_DNR;
5210 cq = n->cq[qid];
5211 if (unlikely(!QTAILQ_EMPTY(&cq->sq_list))) {
5212 trace_pci_nvme_err_invalid_del_cq_notempty(qid);
5213 return NVME_INVALID_QUEUE_DEL;
5216 if (cq->irq_enabled && cq->tail != cq->head) {
5217 n->cq_pending--;
5220 nvme_irq_deassert(n, cq);
5221 trace_pci_nvme_del_cq(qid);
5222 nvme_free_cq(cq, n);
5223 return NVME_SUCCESS;
5226 static void nvme_init_cq(NvmeCQueue *cq, NvmeCtrl *n, uint64_t dma_addr,
5227 uint16_t cqid, uint16_t vector, uint16_t size,
5228 uint16_t irq_enabled)
5230 PCIDevice *pci = PCI_DEVICE(n);
5232 if (msix_enabled(pci)) {
5233 msix_vector_use(pci, vector);
5235 cq->ctrl = n;
5236 cq->cqid = cqid;
5237 cq->size = size;
5238 cq->dma_addr = dma_addr;
5239 cq->phase = 1;
5240 cq->irq_enabled = irq_enabled;
5241 cq->vector = vector;
5242 cq->head = cq->tail = 0;
5243 QTAILQ_INIT(&cq->req_list);
5244 QTAILQ_INIT(&cq->sq_list);
5245 if (n->dbbuf_enabled) {
5246 cq->db_addr = n->dbbuf_dbs + (cqid << 3) + (1 << 2);
5247 cq->ei_addr = n->dbbuf_eis + (cqid << 3) + (1 << 2);
5249 if (n->params.ioeventfd && cqid != 0) {
5250 if (!nvme_init_cq_ioeventfd(cq)) {
5251 cq->ioeventfd_enabled = true;
5255 n->cq[cqid] = cq;
5256 cq->bh = qemu_bh_new(nvme_post_cqes, cq);
5259 static uint16_t nvme_create_cq(NvmeCtrl *n, NvmeRequest *req)
5261 NvmeCQueue *cq;
5262 NvmeCreateCq *c = (NvmeCreateCq *)&req->cmd;
5263 uint16_t cqid = le16_to_cpu(c->cqid);
5264 uint16_t vector = le16_to_cpu(c->irq_vector);
5265 uint16_t qsize = le16_to_cpu(c->qsize);
5266 uint16_t qflags = le16_to_cpu(c->cq_flags);
5267 uint64_t prp1 = le64_to_cpu(c->prp1);
5269 trace_pci_nvme_create_cq(prp1, cqid, vector, qsize, qflags,
5270 NVME_CQ_FLAGS_IEN(qflags) != 0);
5272 if (unlikely(!cqid || cqid > n->conf_ioqpairs || n->cq[cqid] != NULL)) {
5273 trace_pci_nvme_err_invalid_create_cq_cqid(cqid);
5274 return NVME_INVALID_QID | NVME_DNR;
5276 if (unlikely(!qsize || qsize > NVME_CAP_MQES(ldq_le_p(&n->bar.cap)))) {
5277 trace_pci_nvme_err_invalid_create_cq_size(qsize);
5278 return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
5280 if (unlikely(prp1 & (n->page_size - 1))) {
5281 trace_pci_nvme_err_invalid_create_cq_addr(prp1);
5282 return NVME_INVALID_PRP_OFFSET | NVME_DNR;
5284 if (unlikely(!msix_enabled(PCI_DEVICE(n)) && vector)) {
5285 trace_pci_nvme_err_invalid_create_cq_vector(vector);
5286 return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
5288 if (unlikely(vector >= n->conf_msix_qsize)) {
5289 trace_pci_nvme_err_invalid_create_cq_vector(vector);
5290 return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
5292 if (unlikely(!(NVME_CQ_FLAGS_PC(qflags)))) {
5293 trace_pci_nvme_err_invalid_create_cq_qflags(NVME_CQ_FLAGS_PC(qflags));
5294 return NVME_INVALID_FIELD | NVME_DNR;
5297 cq = g_malloc0(sizeof(*cq));
5298 nvme_init_cq(cq, n, prp1, cqid, vector, qsize + 1,
5299 NVME_CQ_FLAGS_IEN(qflags));
5302 * It is only required to set qs_created when creating a completion queue;
5303 * creating a submission queue without a matching completion queue will
5304 * fail.
5306 n->qs_created = true;
5307 return NVME_SUCCESS;
5310 static uint16_t nvme_rpt_empty_id_struct(NvmeCtrl *n, NvmeRequest *req)
5312 uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
5314 return nvme_c2h(n, id, sizeof(id), req);
5317 static uint16_t nvme_identify_ctrl(NvmeCtrl *n, NvmeRequest *req)
5319 trace_pci_nvme_identify_ctrl();
5321 return nvme_c2h(n, (uint8_t *)&n->id_ctrl, sizeof(n->id_ctrl), req);
5324 static uint16_t nvme_identify_ctrl_csi(NvmeCtrl *n, NvmeRequest *req)
5326 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5327 uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
5328 NvmeIdCtrlNvm *id_nvm = (NvmeIdCtrlNvm *)&id;
5330 trace_pci_nvme_identify_ctrl_csi(c->csi);
5332 switch (c->csi) {
5333 case NVME_CSI_NVM:
5334 id_nvm->vsl = n->params.vsl;
5335 id_nvm->dmrsl = cpu_to_le32(n->dmrsl);
5336 break;
5338 case NVME_CSI_ZONED:
5339 ((NvmeIdCtrlZoned *)&id)->zasl = n->params.zasl;
5340 break;
5342 default:
5343 return NVME_INVALID_FIELD | NVME_DNR;
5346 return nvme_c2h(n, id, sizeof(id), req);
5349 static uint16_t nvme_identify_ns(NvmeCtrl *n, NvmeRequest *req, bool active)
5351 NvmeNamespace *ns;
5352 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5353 uint32_t nsid = le32_to_cpu(c->nsid);
5355 trace_pci_nvme_identify_ns(nsid);
5357 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5358 return NVME_INVALID_NSID | NVME_DNR;
5361 ns = nvme_ns(n, nsid);
5362 if (unlikely(!ns)) {
5363 if (!active) {
5364 ns = nvme_subsys_ns(n->subsys, nsid);
5365 if (!ns) {
5366 return nvme_rpt_empty_id_struct(n, req);
5368 } else {
5369 return nvme_rpt_empty_id_struct(n, req);
5373 if (active || ns->csi == NVME_CSI_NVM) {
5374 return nvme_c2h(n, (uint8_t *)&ns->id_ns, sizeof(NvmeIdNs), req);
5377 return NVME_INVALID_CMD_SET | NVME_DNR;
5380 static uint16_t nvme_identify_ctrl_list(NvmeCtrl *n, NvmeRequest *req,
5381 bool attached)
5383 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5384 uint32_t nsid = le32_to_cpu(c->nsid);
5385 uint16_t min_id = le16_to_cpu(c->ctrlid);
5386 uint16_t list[NVME_CONTROLLER_LIST_SIZE] = {};
5387 uint16_t *ids = &list[1];
5388 NvmeNamespace *ns;
5389 NvmeCtrl *ctrl;
5390 int cntlid, nr_ids = 0;
5392 trace_pci_nvme_identify_ctrl_list(c->cns, min_id);
5394 if (!n->subsys) {
5395 return NVME_INVALID_FIELD | NVME_DNR;
5398 if (attached) {
5399 if (nsid == NVME_NSID_BROADCAST) {
5400 return NVME_INVALID_FIELD | NVME_DNR;
5403 ns = nvme_subsys_ns(n->subsys, nsid);
5404 if (!ns) {
5405 return NVME_INVALID_FIELD | NVME_DNR;
5409 for (cntlid = min_id; cntlid < ARRAY_SIZE(n->subsys->ctrls); cntlid++) {
5410 ctrl = nvme_subsys_ctrl(n->subsys, cntlid);
5411 if (!ctrl) {
5412 continue;
5415 if (attached && !nvme_ns(ctrl, nsid)) {
5416 continue;
5419 ids[nr_ids++] = cntlid;
5422 list[0] = nr_ids;
5424 return nvme_c2h(n, (uint8_t *)list, sizeof(list), req);
5427 static uint16_t nvme_identify_pri_ctrl_cap(NvmeCtrl *n, NvmeRequest *req)
5429 trace_pci_nvme_identify_pri_ctrl_cap(le16_to_cpu(n->pri_ctrl_cap.cntlid));
5431 return nvme_c2h(n, (uint8_t *)&n->pri_ctrl_cap,
5432 sizeof(NvmePriCtrlCap), req);
5435 static uint16_t nvme_identify_sec_ctrl_list(NvmeCtrl *n, NvmeRequest *req)
5437 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5438 uint16_t pri_ctrl_id = le16_to_cpu(n->pri_ctrl_cap.cntlid);
5439 uint16_t min_id = le16_to_cpu(c->ctrlid);
5440 uint8_t num_sec_ctrl = n->sec_ctrl_list.numcntl;
5441 NvmeSecCtrlList list = {0};
5442 uint8_t i;
5444 for (i = 0; i < num_sec_ctrl; i++) {
5445 if (n->sec_ctrl_list.sec[i].scid >= min_id) {
5446 list.numcntl = num_sec_ctrl - i;
5447 memcpy(&list.sec, n->sec_ctrl_list.sec + i,
5448 list.numcntl * sizeof(NvmeSecCtrlEntry));
5449 break;
5453 trace_pci_nvme_identify_sec_ctrl_list(pri_ctrl_id, list.numcntl);
5455 return nvme_c2h(n, (uint8_t *)&list, sizeof(list), req);
5458 static uint16_t nvme_identify_ns_csi(NvmeCtrl *n, NvmeRequest *req,
5459 bool active)
5461 NvmeNamespace *ns;
5462 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5463 uint32_t nsid = le32_to_cpu(c->nsid);
5465 trace_pci_nvme_identify_ns_csi(nsid, c->csi);
5467 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5468 return NVME_INVALID_NSID | NVME_DNR;
5471 ns = nvme_ns(n, nsid);
5472 if (unlikely(!ns)) {
5473 if (!active) {
5474 ns = nvme_subsys_ns(n->subsys, nsid);
5475 if (!ns) {
5476 return nvme_rpt_empty_id_struct(n, req);
5478 } else {
5479 return nvme_rpt_empty_id_struct(n, req);
5483 if (c->csi == NVME_CSI_NVM) {
5484 return nvme_c2h(n, (uint8_t *)&ns->id_ns_nvm, sizeof(NvmeIdNsNvm),
5485 req);
5486 } else if (c->csi == NVME_CSI_ZONED && ns->csi == NVME_CSI_ZONED) {
5487 return nvme_c2h(n, (uint8_t *)ns->id_ns_zoned, sizeof(NvmeIdNsZoned),
5488 req);
5491 return NVME_INVALID_FIELD | NVME_DNR;
5494 static uint16_t nvme_identify_nslist(NvmeCtrl *n, NvmeRequest *req,
5495 bool active)
5497 NvmeNamespace *ns;
5498 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5499 uint32_t min_nsid = le32_to_cpu(c->nsid);
5500 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5501 static const int data_len = sizeof(list);
5502 uint32_t *list_ptr = (uint32_t *)list;
5503 int i, j = 0;
5505 trace_pci_nvme_identify_nslist(min_nsid);
5508 * Both FFFFFFFFh (NVME_NSID_BROADCAST) and FFFFFFFFEh are invalid values
5509 * since the Active Namespace ID List should return namespaces with ids
5510 * *higher* than the NSID specified in the command. This is also specified
5511 * in the spec (NVM Express v1.3d, Section 5.15.4).
5513 if (min_nsid >= NVME_NSID_BROADCAST - 1) {
5514 return NVME_INVALID_NSID | NVME_DNR;
5517 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5518 ns = nvme_ns(n, i);
5519 if (!ns) {
5520 if (!active) {
5521 ns = nvme_subsys_ns(n->subsys, i);
5522 if (!ns) {
5523 continue;
5525 } else {
5526 continue;
5529 if (ns->params.nsid <= min_nsid) {
5530 continue;
5532 list_ptr[j++] = cpu_to_le32(ns->params.nsid);
5533 if (j == data_len / sizeof(uint32_t)) {
5534 break;
5538 return nvme_c2h(n, list, data_len, req);
5541 static uint16_t nvme_identify_nslist_csi(NvmeCtrl *n, NvmeRequest *req,
5542 bool active)
5544 NvmeNamespace *ns;
5545 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5546 uint32_t min_nsid = le32_to_cpu(c->nsid);
5547 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5548 static const int data_len = sizeof(list);
5549 uint32_t *list_ptr = (uint32_t *)list;
5550 int i, j = 0;
5552 trace_pci_nvme_identify_nslist_csi(min_nsid, c->csi);
5555 * Same as in nvme_identify_nslist(), FFFFFFFFh/FFFFFFFFEh are invalid.
5557 if (min_nsid >= NVME_NSID_BROADCAST - 1) {
5558 return NVME_INVALID_NSID | NVME_DNR;
5561 if (c->csi != NVME_CSI_NVM && c->csi != NVME_CSI_ZONED) {
5562 return NVME_INVALID_FIELD | NVME_DNR;
5565 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5566 ns = nvme_ns(n, i);
5567 if (!ns) {
5568 if (!active) {
5569 ns = nvme_subsys_ns(n->subsys, i);
5570 if (!ns) {
5571 continue;
5573 } else {
5574 continue;
5577 if (ns->params.nsid <= min_nsid || c->csi != ns->csi) {
5578 continue;
5580 list_ptr[j++] = cpu_to_le32(ns->params.nsid);
5581 if (j == data_len / sizeof(uint32_t)) {
5582 break;
5586 return nvme_c2h(n, list, data_len, req);
5589 static uint16_t nvme_identify_ns_descr_list(NvmeCtrl *n, NvmeRequest *req)
5591 NvmeNamespace *ns;
5592 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5593 uint32_t nsid = le32_to_cpu(c->nsid);
5594 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5595 uint8_t *pos = list;
5596 struct {
5597 NvmeIdNsDescr hdr;
5598 uint8_t v[NVME_NIDL_UUID];
5599 } QEMU_PACKED uuid = {};
5600 struct {
5601 NvmeIdNsDescr hdr;
5602 uint64_t v;
5603 } QEMU_PACKED eui64 = {};
5604 struct {
5605 NvmeIdNsDescr hdr;
5606 uint8_t v;
5607 } QEMU_PACKED csi = {};
5609 trace_pci_nvme_identify_ns_descr_list(nsid);
5611 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5612 return NVME_INVALID_NSID | NVME_DNR;
5615 ns = nvme_ns(n, nsid);
5616 if (unlikely(!ns)) {
5617 return NVME_INVALID_FIELD | NVME_DNR;
5620 if (!qemu_uuid_is_null(&ns->params.uuid)) {
5621 uuid.hdr.nidt = NVME_NIDT_UUID;
5622 uuid.hdr.nidl = NVME_NIDL_UUID;
5623 memcpy(uuid.v, ns->params.uuid.data, NVME_NIDL_UUID);
5624 memcpy(pos, &uuid, sizeof(uuid));
5625 pos += sizeof(uuid);
5628 if (ns->params.eui64) {
5629 eui64.hdr.nidt = NVME_NIDT_EUI64;
5630 eui64.hdr.nidl = NVME_NIDL_EUI64;
5631 eui64.v = cpu_to_be64(ns->params.eui64);
5632 memcpy(pos, &eui64, sizeof(eui64));
5633 pos += sizeof(eui64);
5636 csi.hdr.nidt = NVME_NIDT_CSI;
5637 csi.hdr.nidl = NVME_NIDL_CSI;
5638 csi.v = ns->csi;
5639 memcpy(pos, &csi, sizeof(csi));
5640 pos += sizeof(csi);
5642 return nvme_c2h(n, list, sizeof(list), req);
5645 static uint16_t nvme_identify_cmd_set(NvmeCtrl *n, NvmeRequest *req)
5647 uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5648 static const int data_len = sizeof(list);
5650 trace_pci_nvme_identify_cmd_set();
5652 NVME_SET_CSI(*list, NVME_CSI_NVM);
5653 NVME_SET_CSI(*list, NVME_CSI_ZONED);
5655 return nvme_c2h(n, list, data_len, req);
5658 static uint16_t nvme_identify(NvmeCtrl *n, NvmeRequest *req)
5660 NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5662 trace_pci_nvme_identify(nvme_cid(req), c->cns, le16_to_cpu(c->ctrlid),
5663 c->csi);
5665 switch (c->cns) {
5666 case NVME_ID_CNS_NS:
5667 return nvme_identify_ns(n, req, true);
5668 case NVME_ID_CNS_NS_PRESENT:
5669 return nvme_identify_ns(n, req, false);
5670 case NVME_ID_CNS_NS_ATTACHED_CTRL_LIST:
5671 return nvme_identify_ctrl_list(n, req, true);
5672 case NVME_ID_CNS_CTRL_LIST:
5673 return nvme_identify_ctrl_list(n, req, false);
5674 case NVME_ID_CNS_PRIMARY_CTRL_CAP:
5675 return nvme_identify_pri_ctrl_cap(n, req);
5676 case NVME_ID_CNS_SECONDARY_CTRL_LIST:
5677 return nvme_identify_sec_ctrl_list(n, req);
5678 case NVME_ID_CNS_CS_NS:
5679 return nvme_identify_ns_csi(n, req, true);
5680 case NVME_ID_CNS_CS_NS_PRESENT:
5681 return nvme_identify_ns_csi(n, req, false);
5682 case NVME_ID_CNS_CTRL:
5683 return nvme_identify_ctrl(n, req);
5684 case NVME_ID_CNS_CS_CTRL:
5685 return nvme_identify_ctrl_csi(n, req);
5686 case NVME_ID_CNS_NS_ACTIVE_LIST:
5687 return nvme_identify_nslist(n, req, true);
5688 case NVME_ID_CNS_NS_PRESENT_LIST:
5689 return nvme_identify_nslist(n, req, false);
5690 case NVME_ID_CNS_CS_NS_ACTIVE_LIST:
5691 return nvme_identify_nslist_csi(n, req, true);
5692 case NVME_ID_CNS_CS_NS_PRESENT_LIST:
5693 return nvme_identify_nslist_csi(n, req, false);
5694 case NVME_ID_CNS_NS_DESCR_LIST:
5695 return nvme_identify_ns_descr_list(n, req);
5696 case NVME_ID_CNS_IO_COMMAND_SET:
5697 return nvme_identify_cmd_set(n, req);
5698 default:
5699 trace_pci_nvme_err_invalid_identify_cns(le32_to_cpu(c->cns));
5700 return NVME_INVALID_FIELD | NVME_DNR;
5704 static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
5706 uint16_t sqid = le32_to_cpu(req->cmd.cdw10) & 0xffff;
5708 req->cqe.result = 1;
5709 if (nvme_check_sqid(n, sqid)) {
5710 return NVME_INVALID_FIELD | NVME_DNR;
5713 return NVME_SUCCESS;
5716 static inline void nvme_set_timestamp(NvmeCtrl *n, uint64_t ts)
5718 trace_pci_nvme_setfeat_timestamp(ts);
5720 n->host_timestamp = le64_to_cpu(ts);
5721 n->timestamp_set_qemu_clock_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
5724 static inline uint64_t nvme_get_timestamp(const NvmeCtrl *n)
5726 uint64_t current_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
5727 uint64_t elapsed_time = current_time - n->timestamp_set_qemu_clock_ms;
5729 union nvme_timestamp {
5730 struct {
5731 uint64_t timestamp:48;
5732 uint64_t sync:1;
5733 uint64_t origin:3;
5734 uint64_t rsvd1:12;
5736 uint64_t all;
5739 union nvme_timestamp ts;
5740 ts.all = 0;
5741 ts.timestamp = n->host_timestamp + elapsed_time;
5743 /* If the host timestamp is non-zero, set the timestamp origin */
5744 ts.origin = n->host_timestamp ? 0x01 : 0x00;
5746 trace_pci_nvme_getfeat_timestamp(ts.all);
5748 return cpu_to_le64(ts.all);
5751 static uint16_t nvme_get_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
5753 uint64_t timestamp = nvme_get_timestamp(n);
5755 return nvme_c2h(n, (uint8_t *)&timestamp, sizeof(timestamp), req);
5758 static int nvme_get_feature_fdp(NvmeCtrl *n, uint32_t endgrpid,
5759 uint32_t *result)
5761 *result = 0;
5763 if (!n->subsys || !n->subsys->endgrp.fdp.enabled) {
5764 return NVME_INVALID_FIELD | NVME_DNR;
5767 *result = FIELD_DP16(0, FEAT_FDP, FDPE, 1);
5768 *result = FIELD_DP16(*result, FEAT_FDP, CONF_NDX, 0);
5770 return NVME_SUCCESS;
5773 static uint16_t nvme_get_feature_fdp_events(NvmeCtrl *n, NvmeNamespace *ns,
5774 NvmeRequest *req, uint32_t *result)
5776 NvmeCmd *cmd = &req->cmd;
5777 uint32_t cdw11 = le32_to_cpu(cmd->cdw11);
5778 uint16_t ph = cdw11 & 0xffff;
5779 uint8_t noet = (cdw11 >> 16) & 0xff;
5780 uint16_t ruhid, ret;
5781 uint32_t nentries = 0;
5782 uint8_t s_events_ndx = 0;
5783 size_t s_events_siz = sizeof(NvmeFdpEventDescr) * noet;
5784 g_autofree NvmeFdpEventDescr *s_events = g_malloc0(s_events_siz);
5785 NvmeRuHandle *ruh;
5786 NvmeFdpEventDescr *s_event;
5788 if (!n->subsys || !n->subsys->endgrp.fdp.enabled) {
5789 return NVME_FDP_DISABLED | NVME_DNR;
5792 if (!nvme_ph_valid(ns, ph)) {
5793 return NVME_INVALID_FIELD | NVME_DNR;
5796 ruhid = ns->fdp.phs[ph];
5797 ruh = &n->subsys->endgrp.fdp.ruhs[ruhid];
5799 assert(ruh);
5801 if (unlikely(noet == 0)) {
5802 return NVME_INVALID_FIELD | NVME_DNR;
5805 for (uint8_t event_type = 0; event_type < FDP_EVT_MAX; event_type++) {
5806 uint8_t shift = nvme_fdp_evf_shifts[event_type];
5807 if (!shift && event_type) {
5809 * only first entry (event_type == 0) has a shift value of 0
5810 * other entries are simply unpopulated.
5812 continue;
5815 nentries++;
5817 s_event = &s_events[s_events_ndx];
5818 s_event->evt = event_type;
5819 s_event->evta = (ruh->event_filter >> shift) & 0x1;
5821 /* break if all `noet` entries are filled */
5822 if ((++s_events_ndx) == noet) {
5823 break;
5827 ret = nvme_c2h(n, s_events, s_events_siz, req);
5828 if (ret) {
5829 return ret;
5832 *result = nentries;
5833 return NVME_SUCCESS;
5836 static uint16_t nvme_get_feature(NvmeCtrl *n, NvmeRequest *req)
5838 NvmeCmd *cmd = &req->cmd;
5839 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
5840 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
5841 uint32_t nsid = le32_to_cpu(cmd->nsid);
5842 uint32_t result;
5843 uint8_t fid = NVME_GETSETFEAT_FID(dw10);
5844 NvmeGetFeatureSelect sel = NVME_GETFEAT_SELECT(dw10);
5845 uint16_t iv;
5846 NvmeNamespace *ns;
5847 int i;
5848 uint16_t endgrpid = 0, ret = NVME_SUCCESS;
5850 static const uint32_t nvme_feature_default[NVME_FID_MAX] = {
5851 [NVME_ARBITRATION] = NVME_ARB_AB_NOLIMIT,
5854 trace_pci_nvme_getfeat(nvme_cid(req), nsid, fid, sel, dw11);
5856 if (!nvme_feature_support[fid]) {
5857 return NVME_INVALID_FIELD | NVME_DNR;
5860 if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
5861 if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5863 * The Reservation Notification Mask and Reservation Persistence
5864 * features require a status code of Invalid Field in Command when
5865 * NSID is FFFFFFFFh. Since the device does not support those
5866 * features we can always return Invalid Namespace or Format as we
5867 * should do for all other features.
5869 return NVME_INVALID_NSID | NVME_DNR;
5872 if (!nvme_ns(n, nsid)) {
5873 return NVME_INVALID_FIELD | NVME_DNR;
5877 switch (sel) {
5878 case NVME_GETFEAT_SELECT_CURRENT:
5879 break;
5880 case NVME_GETFEAT_SELECT_SAVED:
5881 /* no features are saveable by the controller; fallthrough */
5882 case NVME_GETFEAT_SELECT_DEFAULT:
5883 goto defaults;
5884 case NVME_GETFEAT_SELECT_CAP:
5885 result = nvme_feature_cap[fid];
5886 goto out;
5889 switch (fid) {
5890 case NVME_TEMPERATURE_THRESHOLD:
5891 result = 0;
5894 * The controller only implements the Composite Temperature sensor, so
5895 * return 0 for all other sensors.
5897 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
5898 goto out;
5901 switch (NVME_TEMP_THSEL(dw11)) {
5902 case NVME_TEMP_THSEL_OVER:
5903 result = n->features.temp_thresh_hi;
5904 goto out;
5905 case NVME_TEMP_THSEL_UNDER:
5906 result = n->features.temp_thresh_low;
5907 goto out;
5910 return NVME_INVALID_FIELD | NVME_DNR;
5911 case NVME_ERROR_RECOVERY:
5912 if (!nvme_nsid_valid(n, nsid)) {
5913 return NVME_INVALID_NSID | NVME_DNR;
5916 ns = nvme_ns(n, nsid);
5917 if (unlikely(!ns)) {
5918 return NVME_INVALID_FIELD | NVME_DNR;
5921 result = ns->features.err_rec;
5922 goto out;
5923 case NVME_VOLATILE_WRITE_CACHE:
5924 result = 0;
5925 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5926 ns = nvme_ns(n, i);
5927 if (!ns) {
5928 continue;
5931 result = blk_enable_write_cache(ns->blkconf.blk);
5932 if (result) {
5933 break;
5936 trace_pci_nvme_getfeat_vwcache(result ? "enabled" : "disabled");
5937 goto out;
5938 case NVME_ASYNCHRONOUS_EVENT_CONF:
5939 result = n->features.async_config;
5940 goto out;
5941 case NVME_TIMESTAMP:
5942 return nvme_get_feature_timestamp(n, req);
5943 case NVME_HOST_BEHAVIOR_SUPPORT:
5944 return nvme_c2h(n, (uint8_t *)&n->features.hbs,
5945 sizeof(n->features.hbs), req);
5946 case NVME_FDP_MODE:
5947 endgrpid = dw11 & 0xff;
5949 if (endgrpid != 0x1) {
5950 return NVME_INVALID_FIELD | NVME_DNR;
5953 ret = nvme_get_feature_fdp(n, endgrpid, &result);
5954 if (ret) {
5955 return ret;
5957 goto out;
5958 case NVME_FDP_EVENTS:
5959 if (!nvme_nsid_valid(n, nsid)) {
5960 return NVME_INVALID_NSID | NVME_DNR;
5963 ns = nvme_ns(n, nsid);
5964 if (unlikely(!ns)) {
5965 return NVME_INVALID_FIELD | NVME_DNR;
5968 ret = nvme_get_feature_fdp_events(n, ns, req, &result);
5969 if (ret) {
5970 return ret;
5972 goto out;
5973 default:
5974 break;
5977 defaults:
5978 switch (fid) {
5979 case NVME_TEMPERATURE_THRESHOLD:
5980 result = 0;
5982 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
5983 break;
5986 if (NVME_TEMP_THSEL(dw11) == NVME_TEMP_THSEL_OVER) {
5987 result = NVME_TEMPERATURE_WARNING;
5990 break;
5991 case NVME_NUMBER_OF_QUEUES:
5992 result = (n->conf_ioqpairs - 1) | ((n->conf_ioqpairs - 1) << 16);
5993 trace_pci_nvme_getfeat_numq(result);
5994 break;
5995 case NVME_INTERRUPT_VECTOR_CONF:
5996 iv = dw11 & 0xffff;
5997 if (iv >= n->conf_ioqpairs + 1) {
5998 return NVME_INVALID_FIELD | NVME_DNR;
6001 result = iv;
6002 if (iv == n->admin_cq.vector) {
6003 result |= NVME_INTVC_NOCOALESCING;
6005 break;
6006 case NVME_FDP_MODE:
6007 endgrpid = dw11 & 0xff;
6009 if (endgrpid != 0x1) {
6010 return NVME_INVALID_FIELD | NVME_DNR;
6013 ret = nvme_get_feature_fdp(n, endgrpid, &result);
6014 if (ret) {
6015 return ret;
6017 goto out;
6019 break;
6020 default:
6021 result = nvme_feature_default[fid];
6022 break;
6025 out:
6026 req->cqe.result = cpu_to_le32(result);
6027 return ret;
6030 static uint16_t nvme_set_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
6032 uint16_t ret;
6033 uint64_t timestamp;
6035 ret = nvme_h2c(n, (uint8_t *)&timestamp, sizeof(timestamp), req);
6036 if (ret) {
6037 return ret;
6040 nvme_set_timestamp(n, timestamp);
6042 return NVME_SUCCESS;
6045 static uint16_t nvme_set_feature_fdp_events(NvmeCtrl *n, NvmeNamespace *ns,
6046 NvmeRequest *req)
6048 NvmeCmd *cmd = &req->cmd;
6049 uint32_t cdw11 = le32_to_cpu(cmd->cdw11);
6050 uint16_t ph = cdw11 & 0xffff;
6051 uint8_t noet = (cdw11 >> 16) & 0xff;
6052 uint16_t ret, ruhid;
6053 uint8_t enable = le32_to_cpu(cmd->cdw12) & 0x1;
6054 uint8_t event_mask = 0;
6055 unsigned int i;
6056 g_autofree uint8_t *events = g_malloc0(noet);
6057 NvmeRuHandle *ruh = NULL;
6059 assert(ns);
6061 if (!n->subsys || !n->subsys->endgrp.fdp.enabled) {
6062 return NVME_FDP_DISABLED | NVME_DNR;
6065 if (!nvme_ph_valid(ns, ph)) {
6066 return NVME_INVALID_FIELD | NVME_DNR;
6069 ruhid = ns->fdp.phs[ph];
6070 ruh = &n->subsys->endgrp.fdp.ruhs[ruhid];
6072 ret = nvme_h2c(n, events, noet, req);
6073 if (ret) {
6074 return ret;
6077 for (i = 0; i < noet; i++) {
6078 event_mask |= (1 << nvme_fdp_evf_shifts[events[i]]);
6081 if (enable) {
6082 ruh->event_filter |= event_mask;
6083 } else {
6084 ruh->event_filter = ruh->event_filter & ~event_mask;
6087 return NVME_SUCCESS;
6090 static uint16_t nvme_set_feature(NvmeCtrl *n, NvmeRequest *req)
6092 NvmeNamespace *ns = NULL;
6094 NvmeCmd *cmd = &req->cmd;
6095 uint32_t dw10 = le32_to_cpu(cmd->cdw10);
6096 uint32_t dw11 = le32_to_cpu(cmd->cdw11);
6097 uint32_t nsid = le32_to_cpu(cmd->nsid);
6098 uint8_t fid = NVME_GETSETFEAT_FID(dw10);
6099 uint8_t save = NVME_SETFEAT_SAVE(dw10);
6100 uint16_t status;
6101 int i;
6103 trace_pci_nvme_setfeat(nvme_cid(req), nsid, fid, save, dw11);
6105 if (save && !(nvme_feature_cap[fid] & NVME_FEAT_CAP_SAVE)) {
6106 return NVME_FID_NOT_SAVEABLE | NVME_DNR;
6109 if (!nvme_feature_support[fid]) {
6110 return NVME_INVALID_FIELD | NVME_DNR;
6113 if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
6114 if (nsid != NVME_NSID_BROADCAST) {
6115 if (!nvme_nsid_valid(n, nsid)) {
6116 return NVME_INVALID_NSID | NVME_DNR;
6119 ns = nvme_ns(n, nsid);
6120 if (unlikely(!ns)) {
6121 return NVME_INVALID_FIELD | NVME_DNR;
6124 } else if (nsid && nsid != NVME_NSID_BROADCAST) {
6125 if (!nvme_nsid_valid(n, nsid)) {
6126 return NVME_INVALID_NSID | NVME_DNR;
6129 return NVME_FEAT_NOT_NS_SPEC | NVME_DNR;
6132 if (!(nvme_feature_cap[fid] & NVME_FEAT_CAP_CHANGE)) {
6133 return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
6136 switch (fid) {
6137 case NVME_TEMPERATURE_THRESHOLD:
6138 if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
6139 break;
6142 switch (NVME_TEMP_THSEL(dw11)) {
6143 case NVME_TEMP_THSEL_OVER:
6144 n->features.temp_thresh_hi = NVME_TEMP_TMPTH(dw11);
6145 break;
6146 case NVME_TEMP_THSEL_UNDER:
6147 n->features.temp_thresh_low = NVME_TEMP_TMPTH(dw11);
6148 break;
6149 default:
6150 return NVME_INVALID_FIELD | NVME_DNR;
6153 if ((n->temperature >= n->features.temp_thresh_hi) ||
6154 (n->temperature <= n->features.temp_thresh_low)) {
6155 nvme_smart_event(n, NVME_SMART_TEMPERATURE);
6158 break;
6159 case NVME_ERROR_RECOVERY:
6160 if (nsid == NVME_NSID_BROADCAST) {
6161 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6162 ns = nvme_ns(n, i);
6164 if (!ns) {
6165 continue;
6168 if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat)) {
6169 ns->features.err_rec = dw11;
6173 break;
6176 assert(ns);
6177 if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat)) {
6178 ns->features.err_rec = dw11;
6180 break;
6181 case NVME_VOLATILE_WRITE_CACHE:
6182 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6183 ns = nvme_ns(n, i);
6184 if (!ns) {
6185 continue;
6188 if (!(dw11 & 0x1) && blk_enable_write_cache(ns->blkconf.blk)) {
6189 blk_flush(ns->blkconf.blk);
6192 blk_set_enable_write_cache(ns->blkconf.blk, dw11 & 1);
6195 break;
6197 case NVME_NUMBER_OF_QUEUES:
6198 if (n->qs_created) {
6199 return NVME_CMD_SEQ_ERROR | NVME_DNR;
6203 * NVMe v1.3, Section 5.21.1.7: FFFFh is not an allowed value for NCQR
6204 * and NSQR.
6206 if ((dw11 & 0xffff) == 0xffff || ((dw11 >> 16) & 0xffff) == 0xffff) {
6207 return NVME_INVALID_FIELD | NVME_DNR;
6210 trace_pci_nvme_setfeat_numq((dw11 & 0xffff) + 1,
6211 ((dw11 >> 16) & 0xffff) + 1,
6212 n->conf_ioqpairs,
6213 n->conf_ioqpairs);
6214 req->cqe.result = cpu_to_le32((n->conf_ioqpairs - 1) |
6215 ((n->conf_ioqpairs - 1) << 16));
6216 break;
6217 case NVME_ASYNCHRONOUS_EVENT_CONF:
6218 n->features.async_config = dw11;
6219 break;
6220 case NVME_TIMESTAMP:
6221 return nvme_set_feature_timestamp(n, req);
6222 case NVME_HOST_BEHAVIOR_SUPPORT:
6223 status = nvme_h2c(n, (uint8_t *)&n->features.hbs,
6224 sizeof(n->features.hbs), req);
6225 if (status) {
6226 return status;
6229 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6230 ns = nvme_ns(n, i);
6232 if (!ns) {
6233 continue;
6236 ns->id_ns.nlbaf = ns->nlbaf - 1;
6237 if (!n->features.hbs.lbafee) {
6238 ns->id_ns.nlbaf = MIN(ns->id_ns.nlbaf, 15);
6242 return status;
6243 case NVME_COMMAND_SET_PROFILE:
6244 if (dw11 & 0x1ff) {
6245 trace_pci_nvme_err_invalid_iocsci(dw11 & 0x1ff);
6246 return NVME_CMD_SET_CMB_REJECTED | NVME_DNR;
6248 break;
6249 case NVME_FDP_MODE:
6250 /* spec: abort with cmd seq err if there's one or more NS' in endgrp */
6251 return NVME_CMD_SEQ_ERROR | NVME_DNR;
6252 case NVME_FDP_EVENTS:
6253 return nvme_set_feature_fdp_events(n, ns, req);
6254 default:
6255 return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
6257 return NVME_SUCCESS;
6260 static uint16_t nvme_aer(NvmeCtrl *n, NvmeRequest *req)
6262 trace_pci_nvme_aer(nvme_cid(req));
6264 if (n->outstanding_aers > n->params.aerl) {
6265 trace_pci_nvme_aer_aerl_exceeded();
6266 return NVME_AER_LIMIT_EXCEEDED;
6269 n->aer_reqs[n->outstanding_aers] = req;
6270 n->outstanding_aers++;
6272 if (!QTAILQ_EMPTY(&n->aer_queue)) {
6273 nvme_process_aers(n);
6276 return NVME_NO_COMPLETE;
6279 static void nvme_update_dmrsl(NvmeCtrl *n)
6281 int nsid;
6283 for (nsid = 1; nsid <= NVME_MAX_NAMESPACES; nsid++) {
6284 NvmeNamespace *ns = nvme_ns(n, nsid);
6285 if (!ns) {
6286 continue;
6289 n->dmrsl = MIN_NON_ZERO(n->dmrsl,
6290 BDRV_REQUEST_MAX_BYTES / nvme_l2b(ns, 1));
6294 static void nvme_select_iocs_ns(NvmeCtrl *n, NvmeNamespace *ns)
6296 uint32_t cc = ldl_le_p(&n->bar.cc);
6298 ns->iocs = nvme_cse_iocs_none;
6299 switch (ns->csi) {
6300 case NVME_CSI_NVM:
6301 if (NVME_CC_CSS(cc) != NVME_CC_CSS_ADMIN_ONLY) {
6302 ns->iocs = nvme_cse_iocs_nvm;
6304 break;
6305 case NVME_CSI_ZONED:
6306 if (NVME_CC_CSS(cc) == NVME_CC_CSS_CSI) {
6307 ns->iocs = nvme_cse_iocs_zoned;
6308 } else if (NVME_CC_CSS(cc) == NVME_CC_CSS_NVM) {
6309 ns->iocs = nvme_cse_iocs_nvm;
6311 break;
6315 static uint16_t nvme_ns_attachment(NvmeCtrl *n, NvmeRequest *req)
6317 NvmeNamespace *ns;
6318 NvmeCtrl *ctrl;
6319 uint16_t list[NVME_CONTROLLER_LIST_SIZE] = {};
6320 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
6321 uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6322 uint8_t sel = dw10 & 0xf;
6323 uint16_t *nr_ids = &list[0];
6324 uint16_t *ids = &list[1];
6325 uint16_t ret;
6326 int i;
6328 trace_pci_nvme_ns_attachment(nvme_cid(req), dw10 & 0xf);
6330 if (!nvme_nsid_valid(n, nsid)) {
6331 return NVME_INVALID_NSID | NVME_DNR;
6334 ns = nvme_subsys_ns(n->subsys, nsid);
6335 if (!ns) {
6336 return NVME_INVALID_FIELD | NVME_DNR;
6339 ret = nvme_h2c(n, (uint8_t *)list, 4096, req);
6340 if (ret) {
6341 return ret;
6344 if (!*nr_ids) {
6345 return NVME_NS_CTRL_LIST_INVALID | NVME_DNR;
6348 *nr_ids = MIN(*nr_ids, NVME_CONTROLLER_LIST_SIZE - 1);
6349 for (i = 0; i < *nr_ids; i++) {
6350 ctrl = nvme_subsys_ctrl(n->subsys, ids[i]);
6351 if (!ctrl) {
6352 return NVME_NS_CTRL_LIST_INVALID | NVME_DNR;
6355 switch (sel) {
6356 case NVME_NS_ATTACHMENT_ATTACH:
6357 if (nvme_ns(ctrl, nsid)) {
6358 return NVME_NS_ALREADY_ATTACHED | NVME_DNR;
6361 if (ns->attached && !ns->params.shared) {
6362 return NVME_NS_PRIVATE | NVME_DNR;
6365 nvme_attach_ns(ctrl, ns);
6366 nvme_select_iocs_ns(ctrl, ns);
6368 break;
6370 case NVME_NS_ATTACHMENT_DETACH:
6371 if (!nvme_ns(ctrl, nsid)) {
6372 return NVME_NS_NOT_ATTACHED | NVME_DNR;
6375 ctrl->namespaces[nsid] = NULL;
6376 ns->attached--;
6378 nvme_update_dmrsl(ctrl);
6380 break;
6382 default:
6383 return NVME_INVALID_FIELD | NVME_DNR;
6387 * Add namespace id to the changed namespace id list for event clearing
6388 * via Get Log Page command.
6390 if (!test_and_set_bit(nsid, ctrl->changed_nsids)) {
6391 nvme_enqueue_event(ctrl, NVME_AER_TYPE_NOTICE,
6392 NVME_AER_INFO_NOTICE_NS_ATTR_CHANGED,
6393 NVME_LOG_CHANGED_NSLIST);
6397 return NVME_SUCCESS;
6400 typedef struct NvmeFormatAIOCB {
6401 BlockAIOCB common;
6402 BlockAIOCB *aiocb;
6403 NvmeRequest *req;
6404 int ret;
6406 NvmeNamespace *ns;
6407 uint32_t nsid;
6408 bool broadcast;
6409 int64_t offset;
6411 uint8_t lbaf;
6412 uint8_t mset;
6413 uint8_t pi;
6414 uint8_t pil;
6415 } NvmeFormatAIOCB;
6417 static void nvme_format_cancel(BlockAIOCB *aiocb)
6419 NvmeFormatAIOCB *iocb = container_of(aiocb, NvmeFormatAIOCB, common);
6421 iocb->ret = -ECANCELED;
6423 if (iocb->aiocb) {
6424 blk_aio_cancel_async(iocb->aiocb);
6425 iocb->aiocb = NULL;
6429 static const AIOCBInfo nvme_format_aiocb_info = {
6430 .aiocb_size = sizeof(NvmeFormatAIOCB),
6431 .cancel_async = nvme_format_cancel,
6432 .get_aio_context = nvme_get_aio_context,
6435 static void nvme_format_set(NvmeNamespace *ns, uint8_t lbaf, uint8_t mset,
6436 uint8_t pi, uint8_t pil)
6438 uint8_t lbafl = lbaf & 0xf;
6439 uint8_t lbafu = lbaf >> 4;
6441 trace_pci_nvme_format_set(ns->params.nsid, lbaf, mset, pi, pil);
6443 ns->id_ns.dps = (pil << 3) | pi;
6444 ns->id_ns.flbas = (lbafu << 5) | (mset << 4) | lbafl;
6446 nvme_ns_init_format(ns);
6449 static void nvme_do_format(NvmeFormatAIOCB *iocb);
6451 static void nvme_format_ns_cb(void *opaque, int ret)
6453 NvmeFormatAIOCB *iocb = opaque;
6454 NvmeNamespace *ns = iocb->ns;
6455 int bytes;
6457 if (iocb->ret < 0) {
6458 goto done;
6459 } else if (ret < 0) {
6460 iocb->ret = ret;
6461 goto done;
6464 assert(ns);
6466 if (iocb->offset < ns->size) {
6467 bytes = MIN(BDRV_REQUEST_MAX_BYTES, ns->size - iocb->offset);
6469 iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, iocb->offset,
6470 bytes, BDRV_REQ_MAY_UNMAP,
6471 nvme_format_ns_cb, iocb);
6473 iocb->offset += bytes;
6474 return;
6477 nvme_format_set(ns, iocb->lbaf, iocb->mset, iocb->pi, iocb->pil);
6478 ns->status = 0x0;
6479 iocb->ns = NULL;
6480 iocb->offset = 0;
6482 done:
6483 nvme_do_format(iocb);
6486 static uint16_t nvme_format_check(NvmeNamespace *ns, uint8_t lbaf, uint8_t pi)
6488 if (ns->params.zoned) {
6489 return NVME_INVALID_FORMAT | NVME_DNR;
6492 if (lbaf > ns->id_ns.nlbaf) {
6493 return NVME_INVALID_FORMAT | NVME_DNR;
6496 if (pi && (ns->id_ns.lbaf[lbaf].ms < nvme_pi_tuple_size(ns))) {
6497 return NVME_INVALID_FORMAT | NVME_DNR;
6500 if (pi && pi > NVME_ID_NS_DPS_TYPE_3) {
6501 return NVME_INVALID_FIELD | NVME_DNR;
6504 return NVME_SUCCESS;
6507 static void nvme_do_format(NvmeFormatAIOCB *iocb)
6509 NvmeRequest *req = iocb->req;
6510 NvmeCtrl *n = nvme_ctrl(req);
6511 uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6512 uint8_t lbaf = dw10 & 0xf;
6513 uint8_t pi = (dw10 >> 5) & 0x7;
6514 uint16_t status;
6515 int i;
6517 if (iocb->ret < 0) {
6518 goto done;
6521 if (iocb->broadcast) {
6522 for (i = iocb->nsid + 1; i <= NVME_MAX_NAMESPACES; i++) {
6523 iocb->ns = nvme_ns(n, i);
6524 if (iocb->ns) {
6525 iocb->nsid = i;
6526 break;
6531 if (!iocb->ns) {
6532 goto done;
6535 status = nvme_format_check(iocb->ns, lbaf, pi);
6536 if (status) {
6537 req->status = status;
6538 goto done;
6541 iocb->ns->status = NVME_FORMAT_IN_PROGRESS;
6542 nvme_format_ns_cb(iocb, 0);
6543 return;
6545 done:
6546 iocb->common.cb(iocb->common.opaque, iocb->ret);
6547 qemu_aio_unref(iocb);
6550 static uint16_t nvme_format(NvmeCtrl *n, NvmeRequest *req)
6552 NvmeFormatAIOCB *iocb;
6553 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
6554 uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6555 uint8_t lbaf = dw10 & 0xf;
6556 uint8_t mset = (dw10 >> 4) & 0x1;
6557 uint8_t pi = (dw10 >> 5) & 0x7;
6558 uint8_t pil = (dw10 >> 8) & 0x1;
6559 uint8_t lbafu = (dw10 >> 12) & 0x3;
6560 uint16_t status;
6562 iocb = qemu_aio_get(&nvme_format_aiocb_info, NULL, nvme_misc_cb, req);
6564 iocb->req = req;
6565 iocb->ret = 0;
6566 iocb->ns = NULL;
6567 iocb->nsid = 0;
6568 iocb->lbaf = lbaf;
6569 iocb->mset = mset;
6570 iocb->pi = pi;
6571 iocb->pil = pil;
6572 iocb->broadcast = (nsid == NVME_NSID_BROADCAST);
6573 iocb->offset = 0;
6575 if (n->features.hbs.lbafee) {
6576 iocb->lbaf |= lbafu << 4;
6579 if (!iocb->broadcast) {
6580 if (!nvme_nsid_valid(n, nsid)) {
6581 status = NVME_INVALID_NSID | NVME_DNR;
6582 goto out;
6585 iocb->ns = nvme_ns(n, nsid);
6586 if (!iocb->ns) {
6587 status = NVME_INVALID_FIELD | NVME_DNR;
6588 goto out;
6592 req->aiocb = &iocb->common;
6593 nvme_do_format(iocb);
6595 return NVME_NO_COMPLETE;
6597 out:
6598 qemu_aio_unref(iocb);
6600 return status;
6603 static void nvme_get_virt_res_num(NvmeCtrl *n, uint8_t rt, int *num_total,
6604 int *num_prim, int *num_sec)
6606 *num_total = le32_to_cpu(rt ?
6607 n->pri_ctrl_cap.vifrt : n->pri_ctrl_cap.vqfrt);
6608 *num_prim = le16_to_cpu(rt ?
6609 n->pri_ctrl_cap.virfap : n->pri_ctrl_cap.vqrfap);
6610 *num_sec = le16_to_cpu(rt ? n->pri_ctrl_cap.virfa : n->pri_ctrl_cap.vqrfa);
6613 static uint16_t nvme_assign_virt_res_to_prim(NvmeCtrl *n, NvmeRequest *req,
6614 uint16_t cntlid, uint8_t rt,
6615 int nr)
6617 int num_total, num_prim, num_sec;
6619 if (cntlid != n->cntlid) {
6620 return NVME_INVALID_CTRL_ID | NVME_DNR;
6623 nvme_get_virt_res_num(n, rt, &num_total, &num_prim, &num_sec);
6625 if (nr > num_total) {
6626 return NVME_INVALID_NUM_RESOURCES | NVME_DNR;
6629 if (nr > num_total - num_sec) {
6630 return NVME_INVALID_RESOURCE_ID | NVME_DNR;
6633 if (rt) {
6634 n->next_pri_ctrl_cap.virfap = cpu_to_le16(nr);
6635 } else {
6636 n->next_pri_ctrl_cap.vqrfap = cpu_to_le16(nr);
6639 req->cqe.result = cpu_to_le32(nr);
6640 return req->status;
6643 static void nvme_update_virt_res(NvmeCtrl *n, NvmeSecCtrlEntry *sctrl,
6644 uint8_t rt, int nr)
6646 int prev_nr, prev_total;
6648 if (rt) {
6649 prev_nr = le16_to_cpu(sctrl->nvi);
6650 prev_total = le32_to_cpu(n->pri_ctrl_cap.virfa);
6651 sctrl->nvi = cpu_to_le16(nr);
6652 n->pri_ctrl_cap.virfa = cpu_to_le32(prev_total + nr - prev_nr);
6653 } else {
6654 prev_nr = le16_to_cpu(sctrl->nvq);
6655 prev_total = le32_to_cpu(n->pri_ctrl_cap.vqrfa);
6656 sctrl->nvq = cpu_to_le16(nr);
6657 n->pri_ctrl_cap.vqrfa = cpu_to_le32(prev_total + nr - prev_nr);
6661 static uint16_t nvme_assign_virt_res_to_sec(NvmeCtrl *n, NvmeRequest *req,
6662 uint16_t cntlid, uint8_t rt, int nr)
6664 int num_total, num_prim, num_sec, num_free, diff, limit;
6665 NvmeSecCtrlEntry *sctrl;
6667 sctrl = nvme_sctrl_for_cntlid(n, cntlid);
6668 if (!sctrl) {
6669 return NVME_INVALID_CTRL_ID | NVME_DNR;
6672 if (sctrl->scs) {
6673 return NVME_INVALID_SEC_CTRL_STATE | NVME_DNR;
6676 limit = le16_to_cpu(rt ? n->pri_ctrl_cap.vifrsm : n->pri_ctrl_cap.vqfrsm);
6677 if (nr > limit) {
6678 return NVME_INVALID_NUM_RESOURCES | NVME_DNR;
6681 nvme_get_virt_res_num(n, rt, &num_total, &num_prim, &num_sec);
6682 num_free = num_total - num_prim - num_sec;
6683 diff = nr - le16_to_cpu(rt ? sctrl->nvi : sctrl->nvq);
6685 if (diff > num_free) {
6686 return NVME_INVALID_RESOURCE_ID | NVME_DNR;
6689 nvme_update_virt_res(n, sctrl, rt, nr);
6690 req->cqe.result = cpu_to_le32(nr);
6692 return req->status;
6695 static uint16_t nvme_virt_set_state(NvmeCtrl *n, uint16_t cntlid, bool online)
6697 PCIDevice *pci = PCI_DEVICE(n);
6698 NvmeCtrl *sn = NULL;
6699 NvmeSecCtrlEntry *sctrl;
6700 int vf_index;
6702 sctrl = nvme_sctrl_for_cntlid(n, cntlid);
6703 if (!sctrl) {
6704 return NVME_INVALID_CTRL_ID | NVME_DNR;
6707 if (!pci_is_vf(pci)) {
6708 vf_index = le16_to_cpu(sctrl->vfn) - 1;
6709 sn = NVME(pcie_sriov_get_vf_at_index(pci, vf_index));
6712 if (online) {
6713 if (!sctrl->nvi || (le16_to_cpu(sctrl->nvq) < 2) || !sn) {
6714 return NVME_INVALID_SEC_CTRL_STATE | NVME_DNR;
6717 if (!sctrl->scs) {
6718 sctrl->scs = 0x1;
6719 nvme_ctrl_reset(sn, NVME_RESET_FUNCTION);
6721 } else {
6722 nvme_update_virt_res(n, sctrl, NVME_VIRT_RES_INTERRUPT, 0);
6723 nvme_update_virt_res(n, sctrl, NVME_VIRT_RES_QUEUE, 0);
6725 if (sctrl->scs) {
6726 sctrl->scs = 0x0;
6727 if (sn) {
6728 nvme_ctrl_reset(sn, NVME_RESET_FUNCTION);
6733 return NVME_SUCCESS;
6736 static uint16_t nvme_virt_mngmt(NvmeCtrl *n, NvmeRequest *req)
6738 uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6739 uint32_t dw11 = le32_to_cpu(req->cmd.cdw11);
6740 uint8_t act = dw10 & 0xf;
6741 uint8_t rt = (dw10 >> 8) & 0x7;
6742 uint16_t cntlid = (dw10 >> 16) & 0xffff;
6743 int nr = dw11 & 0xffff;
6745 trace_pci_nvme_virt_mngmt(nvme_cid(req), act, cntlid, rt ? "VI" : "VQ", nr);
6747 if (rt != NVME_VIRT_RES_QUEUE && rt != NVME_VIRT_RES_INTERRUPT) {
6748 return NVME_INVALID_RESOURCE_ID | NVME_DNR;
6751 switch (act) {
6752 case NVME_VIRT_MNGMT_ACTION_SEC_ASSIGN:
6753 return nvme_assign_virt_res_to_sec(n, req, cntlid, rt, nr);
6754 case NVME_VIRT_MNGMT_ACTION_PRM_ALLOC:
6755 return nvme_assign_virt_res_to_prim(n, req, cntlid, rt, nr);
6756 case NVME_VIRT_MNGMT_ACTION_SEC_ONLINE:
6757 return nvme_virt_set_state(n, cntlid, true);
6758 case NVME_VIRT_MNGMT_ACTION_SEC_OFFLINE:
6759 return nvme_virt_set_state(n, cntlid, false);
6760 default:
6761 return NVME_INVALID_FIELD | NVME_DNR;
6765 static uint16_t nvme_dbbuf_config(NvmeCtrl *n, const NvmeRequest *req)
6767 PCIDevice *pci = PCI_DEVICE(n);
6768 uint64_t dbs_addr = le64_to_cpu(req->cmd.dptr.prp1);
6769 uint64_t eis_addr = le64_to_cpu(req->cmd.dptr.prp2);
6770 int i;
6772 /* Address should be page aligned */
6773 if (dbs_addr & (n->page_size - 1) || eis_addr & (n->page_size - 1)) {
6774 return NVME_INVALID_FIELD | NVME_DNR;
6777 /* Save shadow buffer base addr for use during queue creation */
6778 n->dbbuf_dbs = dbs_addr;
6779 n->dbbuf_eis = eis_addr;
6780 n->dbbuf_enabled = true;
6782 for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
6783 NvmeSQueue *sq = n->sq[i];
6784 NvmeCQueue *cq = n->cq[i];
6786 if (sq) {
6788 * CAP.DSTRD is 0, so offset of ith sq db_addr is (i<<3)
6789 * nvme_process_db() uses this hard-coded way to calculate
6790 * doorbell offsets. Be consistent with that here.
6792 sq->db_addr = dbs_addr + (i << 3);
6793 sq->ei_addr = eis_addr + (i << 3);
6794 pci_dma_write(pci, sq->db_addr, &sq->tail, sizeof(sq->tail));
6796 if (n->params.ioeventfd && sq->sqid != 0) {
6797 if (!nvme_init_sq_ioeventfd(sq)) {
6798 sq->ioeventfd_enabled = true;
6803 if (cq) {
6804 /* CAP.DSTRD is 0, so offset of ith cq db_addr is (i<<3)+(1<<2) */
6805 cq->db_addr = dbs_addr + (i << 3) + (1 << 2);
6806 cq->ei_addr = eis_addr + (i << 3) + (1 << 2);
6807 pci_dma_write(pci, cq->db_addr, &cq->head, sizeof(cq->head));
6809 if (n->params.ioeventfd && cq->cqid != 0) {
6810 if (!nvme_init_cq_ioeventfd(cq)) {
6811 cq->ioeventfd_enabled = true;
6817 trace_pci_nvme_dbbuf_config(dbs_addr, eis_addr);
6819 return NVME_SUCCESS;
6822 static uint16_t nvme_directive_send(NvmeCtrl *n, NvmeRequest *req)
6824 return NVME_INVALID_FIELD | NVME_DNR;
6827 static uint16_t nvme_directive_receive(NvmeCtrl *n, NvmeRequest *req)
6829 NvmeNamespace *ns;
6830 uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6831 uint32_t dw11 = le32_to_cpu(req->cmd.cdw11);
6832 uint32_t nsid = le32_to_cpu(req->cmd.nsid);
6833 uint8_t doper, dtype;
6834 uint32_t numd, trans_len;
6835 NvmeDirectiveIdentify id = {
6836 .supported = 1 << NVME_DIRECTIVE_IDENTIFY,
6837 .enabled = 1 << NVME_DIRECTIVE_IDENTIFY,
6840 numd = dw10 + 1;
6841 doper = dw11 & 0xff;
6842 dtype = (dw11 >> 8) & 0xff;
6844 trans_len = MIN(sizeof(NvmeDirectiveIdentify), numd << 2);
6846 if (nsid == NVME_NSID_BROADCAST || dtype != NVME_DIRECTIVE_IDENTIFY ||
6847 doper != NVME_DIRECTIVE_RETURN_PARAMS) {
6848 return NVME_INVALID_FIELD | NVME_DNR;
6851 ns = nvme_ns(n, nsid);
6852 if (!ns) {
6853 return NVME_INVALID_FIELD | NVME_DNR;
6856 switch (dtype) {
6857 case NVME_DIRECTIVE_IDENTIFY:
6858 switch (doper) {
6859 case NVME_DIRECTIVE_RETURN_PARAMS:
6860 if (ns->endgrp->fdp.enabled) {
6861 id.supported |= 1 << NVME_DIRECTIVE_DATA_PLACEMENT;
6862 id.enabled |= 1 << NVME_DIRECTIVE_DATA_PLACEMENT;
6863 id.persistent |= 1 << NVME_DIRECTIVE_DATA_PLACEMENT;
6866 return nvme_c2h(n, (uint8_t *)&id, trans_len, req);
6868 default:
6869 return NVME_INVALID_FIELD | NVME_DNR;
6872 default:
6873 return NVME_INVALID_FIELD;
6877 static uint16_t nvme_admin_cmd(NvmeCtrl *n, NvmeRequest *req)
6879 trace_pci_nvme_admin_cmd(nvme_cid(req), nvme_sqid(req), req->cmd.opcode,
6880 nvme_adm_opc_str(req->cmd.opcode));
6882 if (!(nvme_cse_acs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
6883 trace_pci_nvme_err_invalid_admin_opc(req->cmd.opcode);
6884 return NVME_INVALID_OPCODE | NVME_DNR;
6887 /* SGLs shall not be used for Admin commands in NVMe over PCIe */
6888 if (NVME_CMD_FLAGS_PSDT(req->cmd.flags) != NVME_PSDT_PRP) {
6889 return NVME_INVALID_FIELD | NVME_DNR;
6892 if (NVME_CMD_FLAGS_FUSE(req->cmd.flags)) {
6893 return NVME_INVALID_FIELD;
6896 switch (req->cmd.opcode) {
6897 case NVME_ADM_CMD_DELETE_SQ:
6898 return nvme_del_sq(n, req);
6899 case NVME_ADM_CMD_CREATE_SQ:
6900 return nvme_create_sq(n, req);
6901 case NVME_ADM_CMD_GET_LOG_PAGE:
6902 return nvme_get_log(n, req);
6903 case NVME_ADM_CMD_DELETE_CQ:
6904 return nvme_del_cq(n, req);
6905 case NVME_ADM_CMD_CREATE_CQ:
6906 return nvme_create_cq(n, req);
6907 case NVME_ADM_CMD_IDENTIFY:
6908 return nvme_identify(n, req);
6909 case NVME_ADM_CMD_ABORT:
6910 return nvme_abort(n, req);
6911 case NVME_ADM_CMD_SET_FEATURES:
6912 return nvme_set_feature(n, req);
6913 case NVME_ADM_CMD_GET_FEATURES:
6914 return nvme_get_feature(n, req);
6915 case NVME_ADM_CMD_ASYNC_EV_REQ:
6916 return nvme_aer(n, req);
6917 case NVME_ADM_CMD_NS_ATTACHMENT:
6918 return nvme_ns_attachment(n, req);
6919 case NVME_ADM_CMD_VIRT_MNGMT:
6920 return nvme_virt_mngmt(n, req);
6921 case NVME_ADM_CMD_DBBUF_CONFIG:
6922 return nvme_dbbuf_config(n, req);
6923 case NVME_ADM_CMD_FORMAT_NVM:
6924 return nvme_format(n, req);
6925 case NVME_ADM_CMD_DIRECTIVE_SEND:
6926 return nvme_directive_send(n, req);
6927 case NVME_ADM_CMD_DIRECTIVE_RECV:
6928 return nvme_directive_receive(n, req);
6929 default:
6930 assert(false);
6933 return NVME_INVALID_OPCODE | NVME_DNR;
6936 static void nvme_update_sq_eventidx(const NvmeSQueue *sq)
6938 uint32_t v = cpu_to_le32(sq->tail);
6940 trace_pci_nvme_update_sq_eventidx(sq->sqid, sq->tail);
6942 pci_dma_write(PCI_DEVICE(sq->ctrl), sq->ei_addr, &v, sizeof(v));
6945 static void nvme_update_sq_tail(NvmeSQueue *sq)
6947 uint32_t v;
6949 pci_dma_read(PCI_DEVICE(sq->ctrl), sq->db_addr, &v, sizeof(v));
6951 sq->tail = le32_to_cpu(v);
6953 trace_pci_nvme_update_sq_tail(sq->sqid, sq->tail);
6956 static void nvme_process_sq(void *opaque)
6958 NvmeSQueue *sq = opaque;
6959 NvmeCtrl *n = sq->ctrl;
6960 NvmeCQueue *cq = n->cq[sq->cqid];
6962 uint16_t status;
6963 hwaddr addr;
6964 NvmeCmd cmd;
6965 NvmeRequest *req;
6967 if (n->dbbuf_enabled) {
6968 nvme_update_sq_tail(sq);
6971 while (!(nvme_sq_empty(sq) || QTAILQ_EMPTY(&sq->req_list))) {
6972 addr = sq->dma_addr + sq->head * n->sqe_size;
6973 if (nvme_addr_read(n, addr, (void *)&cmd, sizeof(cmd))) {
6974 trace_pci_nvme_err_addr_read(addr);
6975 trace_pci_nvme_err_cfs();
6976 stl_le_p(&n->bar.csts, NVME_CSTS_FAILED);
6977 break;
6979 nvme_inc_sq_head(sq);
6981 req = QTAILQ_FIRST(&sq->req_list);
6982 QTAILQ_REMOVE(&sq->req_list, req, entry);
6983 QTAILQ_INSERT_TAIL(&sq->out_req_list, req, entry);
6984 nvme_req_clear(req);
6985 req->cqe.cid = cmd.cid;
6986 memcpy(&req->cmd, &cmd, sizeof(NvmeCmd));
6988 status = sq->sqid ? nvme_io_cmd(n, req) :
6989 nvme_admin_cmd(n, req);
6990 if (status != NVME_NO_COMPLETE) {
6991 req->status = status;
6992 nvme_enqueue_req_completion(cq, req);
6995 if (n->dbbuf_enabled) {
6996 nvme_update_sq_eventidx(sq);
6997 nvme_update_sq_tail(sq);
7002 static void nvme_update_msixcap_ts(PCIDevice *pci_dev, uint32_t table_size)
7004 uint8_t *config;
7006 if (!msix_present(pci_dev)) {
7007 return;
7010 assert(table_size > 0 && table_size <= pci_dev->msix_entries_nr);
7012 config = pci_dev->config + pci_dev->msix_cap;
7013 pci_set_word_by_mask(config + PCI_MSIX_FLAGS, PCI_MSIX_FLAGS_QSIZE,
7014 table_size - 1);
7017 static void nvme_activate_virt_res(NvmeCtrl *n)
7019 PCIDevice *pci_dev = PCI_DEVICE(n);
7020 NvmePriCtrlCap *cap = &n->pri_ctrl_cap;
7021 NvmeSecCtrlEntry *sctrl;
7023 /* -1 to account for the admin queue */
7024 if (pci_is_vf(pci_dev)) {
7025 sctrl = nvme_sctrl(n);
7026 cap->vqprt = sctrl->nvq;
7027 cap->viprt = sctrl->nvi;
7028 n->conf_ioqpairs = sctrl->nvq ? le16_to_cpu(sctrl->nvq) - 1 : 0;
7029 n->conf_msix_qsize = sctrl->nvi ? le16_to_cpu(sctrl->nvi) : 1;
7030 } else {
7031 cap->vqrfap = n->next_pri_ctrl_cap.vqrfap;
7032 cap->virfap = n->next_pri_ctrl_cap.virfap;
7033 n->conf_ioqpairs = le16_to_cpu(cap->vqprt) +
7034 le16_to_cpu(cap->vqrfap) - 1;
7035 n->conf_msix_qsize = le16_to_cpu(cap->viprt) +
7036 le16_to_cpu(cap->virfap);
7040 static void nvme_ctrl_reset(NvmeCtrl *n, NvmeResetType rst)
7042 PCIDevice *pci_dev = PCI_DEVICE(n);
7043 NvmeSecCtrlEntry *sctrl;
7044 NvmeNamespace *ns;
7045 int i;
7047 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
7048 ns = nvme_ns(n, i);
7049 if (!ns) {
7050 continue;
7053 nvme_ns_drain(ns);
7056 for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
7057 if (n->sq[i] != NULL) {
7058 nvme_free_sq(n->sq[i], n);
7061 for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
7062 if (n->cq[i] != NULL) {
7063 nvme_free_cq(n->cq[i], n);
7067 while (!QTAILQ_EMPTY(&n->aer_queue)) {
7068 NvmeAsyncEvent *event = QTAILQ_FIRST(&n->aer_queue);
7069 QTAILQ_REMOVE(&n->aer_queue, event, entry);
7070 g_free(event);
7073 if (n->params.sriov_max_vfs) {
7074 if (!pci_is_vf(pci_dev)) {
7075 for (i = 0; i < n->sec_ctrl_list.numcntl; i++) {
7076 sctrl = &n->sec_ctrl_list.sec[i];
7077 nvme_virt_set_state(n, le16_to_cpu(sctrl->scid), false);
7080 if (rst != NVME_RESET_CONTROLLER) {
7081 pcie_sriov_pf_disable_vfs(pci_dev);
7085 if (rst != NVME_RESET_CONTROLLER) {
7086 nvme_activate_virt_res(n);
7090 n->aer_queued = 0;
7091 n->aer_mask = 0;
7092 n->outstanding_aers = 0;
7093 n->qs_created = false;
7095 nvme_update_msixcap_ts(pci_dev, n->conf_msix_qsize);
7097 if (pci_is_vf(pci_dev)) {
7098 sctrl = nvme_sctrl(n);
7100 stl_le_p(&n->bar.csts, sctrl->scs ? 0 : NVME_CSTS_FAILED);
7101 } else {
7102 stl_le_p(&n->bar.csts, 0);
7105 stl_le_p(&n->bar.intms, 0);
7106 stl_le_p(&n->bar.intmc, 0);
7107 stl_le_p(&n->bar.cc, 0);
7109 n->dbbuf_dbs = 0;
7110 n->dbbuf_eis = 0;
7111 n->dbbuf_enabled = false;
7114 static void nvme_ctrl_shutdown(NvmeCtrl *n)
7116 NvmeNamespace *ns;
7117 int i;
7119 if (n->pmr.dev) {
7120 memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
7123 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
7124 ns = nvme_ns(n, i);
7125 if (!ns) {
7126 continue;
7129 nvme_ns_shutdown(ns);
7133 static void nvme_select_iocs(NvmeCtrl *n)
7135 NvmeNamespace *ns;
7136 int i;
7138 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
7139 ns = nvme_ns(n, i);
7140 if (!ns) {
7141 continue;
7144 nvme_select_iocs_ns(n, ns);
7148 static int nvme_start_ctrl(NvmeCtrl *n)
7150 uint64_t cap = ldq_le_p(&n->bar.cap);
7151 uint32_t cc = ldl_le_p(&n->bar.cc);
7152 uint32_t aqa = ldl_le_p(&n->bar.aqa);
7153 uint64_t asq = ldq_le_p(&n->bar.asq);
7154 uint64_t acq = ldq_le_p(&n->bar.acq);
7155 uint32_t page_bits = NVME_CC_MPS(cc) + 12;
7156 uint32_t page_size = 1 << page_bits;
7157 NvmeSecCtrlEntry *sctrl = nvme_sctrl(n);
7159 if (pci_is_vf(PCI_DEVICE(n)) && !sctrl->scs) {
7160 trace_pci_nvme_err_startfail_virt_state(le16_to_cpu(sctrl->nvi),
7161 le16_to_cpu(sctrl->nvq));
7162 return -1;
7164 if (unlikely(n->cq[0])) {
7165 trace_pci_nvme_err_startfail_cq();
7166 return -1;
7168 if (unlikely(n->sq[0])) {
7169 trace_pci_nvme_err_startfail_sq();
7170 return -1;
7172 if (unlikely(asq & (page_size - 1))) {
7173 trace_pci_nvme_err_startfail_asq_misaligned(asq);
7174 return -1;
7176 if (unlikely(acq & (page_size - 1))) {
7177 trace_pci_nvme_err_startfail_acq_misaligned(acq);
7178 return -1;
7180 if (unlikely(!(NVME_CAP_CSS(cap) & (1 << NVME_CC_CSS(cc))))) {
7181 trace_pci_nvme_err_startfail_css(NVME_CC_CSS(cc));
7182 return -1;
7184 if (unlikely(NVME_CC_MPS(cc) < NVME_CAP_MPSMIN(cap))) {
7185 trace_pci_nvme_err_startfail_page_too_small(
7186 NVME_CC_MPS(cc),
7187 NVME_CAP_MPSMIN(cap));
7188 return -1;
7190 if (unlikely(NVME_CC_MPS(cc) >
7191 NVME_CAP_MPSMAX(cap))) {
7192 trace_pci_nvme_err_startfail_page_too_large(
7193 NVME_CC_MPS(cc),
7194 NVME_CAP_MPSMAX(cap));
7195 return -1;
7197 if (unlikely(NVME_CC_IOCQES(cc) <
7198 NVME_CTRL_CQES_MIN(n->id_ctrl.cqes))) {
7199 trace_pci_nvme_err_startfail_cqent_too_small(
7200 NVME_CC_IOCQES(cc),
7201 NVME_CTRL_CQES_MIN(cap));
7202 return -1;
7204 if (unlikely(NVME_CC_IOCQES(cc) >
7205 NVME_CTRL_CQES_MAX(n->id_ctrl.cqes))) {
7206 trace_pci_nvme_err_startfail_cqent_too_large(
7207 NVME_CC_IOCQES(cc),
7208 NVME_CTRL_CQES_MAX(cap));
7209 return -1;
7211 if (unlikely(NVME_CC_IOSQES(cc) <
7212 NVME_CTRL_SQES_MIN(n->id_ctrl.sqes))) {
7213 trace_pci_nvme_err_startfail_sqent_too_small(
7214 NVME_CC_IOSQES(cc),
7215 NVME_CTRL_SQES_MIN(cap));
7216 return -1;
7218 if (unlikely(NVME_CC_IOSQES(cc) >
7219 NVME_CTRL_SQES_MAX(n->id_ctrl.sqes))) {
7220 trace_pci_nvme_err_startfail_sqent_too_large(
7221 NVME_CC_IOSQES(cc),
7222 NVME_CTRL_SQES_MAX(cap));
7223 return -1;
7225 if (unlikely(!NVME_AQA_ASQS(aqa))) {
7226 trace_pci_nvme_err_startfail_asqent_sz_zero();
7227 return -1;
7229 if (unlikely(!NVME_AQA_ACQS(aqa))) {
7230 trace_pci_nvme_err_startfail_acqent_sz_zero();
7231 return -1;
7234 n->page_bits = page_bits;
7235 n->page_size = page_size;
7236 n->max_prp_ents = n->page_size / sizeof(uint64_t);
7237 n->cqe_size = 1 << NVME_CC_IOCQES(cc);
7238 n->sqe_size = 1 << NVME_CC_IOSQES(cc);
7239 nvme_init_cq(&n->admin_cq, n, acq, 0, 0, NVME_AQA_ACQS(aqa) + 1, 1);
7240 nvme_init_sq(&n->admin_sq, n, asq, 0, 0, NVME_AQA_ASQS(aqa) + 1);
7242 nvme_set_timestamp(n, 0ULL);
7244 nvme_select_iocs(n);
7246 return 0;
7249 static void nvme_cmb_enable_regs(NvmeCtrl *n)
7251 uint32_t cmbloc = ldl_le_p(&n->bar.cmbloc);
7252 uint32_t cmbsz = ldl_le_p(&n->bar.cmbsz);
7254 NVME_CMBLOC_SET_CDPCILS(cmbloc, 1);
7255 NVME_CMBLOC_SET_CDPMLS(cmbloc, 1);
7256 NVME_CMBLOC_SET_BIR(cmbloc, NVME_CMB_BIR);
7257 stl_le_p(&n->bar.cmbloc, cmbloc);
7259 NVME_CMBSZ_SET_SQS(cmbsz, 1);
7260 NVME_CMBSZ_SET_CQS(cmbsz, 0);
7261 NVME_CMBSZ_SET_LISTS(cmbsz, 1);
7262 NVME_CMBSZ_SET_RDS(cmbsz, 1);
7263 NVME_CMBSZ_SET_WDS(cmbsz, 1);
7264 NVME_CMBSZ_SET_SZU(cmbsz, 2); /* MBs */
7265 NVME_CMBSZ_SET_SZ(cmbsz, n->params.cmb_size_mb);
7266 stl_le_p(&n->bar.cmbsz, cmbsz);
7269 static void nvme_write_bar(NvmeCtrl *n, hwaddr offset, uint64_t data,
7270 unsigned size)
7272 PCIDevice *pci = PCI_DEVICE(n);
7273 uint64_t cap = ldq_le_p(&n->bar.cap);
7274 uint32_t cc = ldl_le_p(&n->bar.cc);
7275 uint32_t intms = ldl_le_p(&n->bar.intms);
7276 uint32_t csts = ldl_le_p(&n->bar.csts);
7277 uint32_t pmrsts = ldl_le_p(&n->bar.pmrsts);
7279 if (unlikely(offset & (sizeof(uint32_t) - 1))) {
7280 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_misaligned32,
7281 "MMIO write not 32-bit aligned,"
7282 " offset=0x%"PRIx64"", offset);
7283 /* should be ignored, fall through for now */
7286 if (unlikely(size < sizeof(uint32_t))) {
7287 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_toosmall,
7288 "MMIO write smaller than 32-bits,"
7289 " offset=0x%"PRIx64", size=%u",
7290 offset, size);
7291 /* should be ignored, fall through for now */
7294 switch (offset) {
7295 case NVME_REG_INTMS:
7296 if (unlikely(msix_enabled(pci))) {
7297 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
7298 "undefined access to interrupt mask set"
7299 " when MSI-X is enabled");
7300 /* should be ignored, fall through for now */
7302 intms |= data;
7303 stl_le_p(&n->bar.intms, intms);
7304 n->bar.intmc = n->bar.intms;
7305 trace_pci_nvme_mmio_intm_set(data & 0xffffffff, intms);
7306 nvme_irq_check(n);
7307 break;
7308 case NVME_REG_INTMC:
7309 if (unlikely(msix_enabled(pci))) {
7310 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
7311 "undefined access to interrupt mask clr"
7312 " when MSI-X is enabled");
7313 /* should be ignored, fall through for now */
7315 intms &= ~data;
7316 stl_le_p(&n->bar.intms, intms);
7317 n->bar.intmc = n->bar.intms;
7318 trace_pci_nvme_mmio_intm_clr(data & 0xffffffff, intms);
7319 nvme_irq_check(n);
7320 break;
7321 case NVME_REG_CC:
7322 stl_le_p(&n->bar.cc, data);
7324 trace_pci_nvme_mmio_cfg(data & 0xffffffff);
7326 if (NVME_CC_SHN(data) && !(NVME_CC_SHN(cc))) {
7327 trace_pci_nvme_mmio_shutdown_set();
7328 nvme_ctrl_shutdown(n);
7329 csts &= ~(CSTS_SHST_MASK << CSTS_SHST_SHIFT);
7330 csts |= NVME_CSTS_SHST_COMPLETE;
7331 } else if (!NVME_CC_SHN(data) && NVME_CC_SHN(cc)) {
7332 trace_pci_nvme_mmio_shutdown_cleared();
7333 csts &= ~(CSTS_SHST_MASK << CSTS_SHST_SHIFT);
7336 if (NVME_CC_EN(data) && !NVME_CC_EN(cc)) {
7337 if (unlikely(nvme_start_ctrl(n))) {
7338 trace_pci_nvme_err_startfail();
7339 csts = NVME_CSTS_FAILED;
7340 } else {
7341 trace_pci_nvme_mmio_start_success();
7342 csts = NVME_CSTS_READY;
7344 } else if (!NVME_CC_EN(data) && NVME_CC_EN(cc)) {
7345 trace_pci_nvme_mmio_stopped();
7346 nvme_ctrl_reset(n, NVME_RESET_CONTROLLER);
7348 break;
7351 stl_le_p(&n->bar.csts, csts);
7353 break;
7354 case NVME_REG_CSTS:
7355 if (data & (1 << 4)) {
7356 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ssreset_w1c_unsupported,
7357 "attempted to W1C CSTS.NSSRO"
7358 " but CAP.NSSRS is zero (not supported)");
7359 } else if (data != 0) {
7360 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ro_csts,
7361 "attempted to set a read only bit"
7362 " of controller status");
7364 break;
7365 case NVME_REG_NSSR:
7366 if (data == 0x4e564d65) {
7367 trace_pci_nvme_ub_mmiowr_ssreset_unsupported();
7368 } else {
7369 /* The spec says that writes of other values have no effect */
7370 return;
7372 break;
7373 case NVME_REG_AQA:
7374 stl_le_p(&n->bar.aqa, data);
7375 trace_pci_nvme_mmio_aqattr(data & 0xffffffff);
7376 break;
7377 case NVME_REG_ASQ:
7378 stn_le_p(&n->bar.asq, size, data);
7379 trace_pci_nvme_mmio_asqaddr(data);
7380 break;
7381 case NVME_REG_ASQ + 4:
7382 stl_le_p((uint8_t *)&n->bar.asq + 4, data);
7383 trace_pci_nvme_mmio_asqaddr_hi(data, ldq_le_p(&n->bar.asq));
7384 break;
7385 case NVME_REG_ACQ:
7386 trace_pci_nvme_mmio_acqaddr(data);
7387 stn_le_p(&n->bar.acq, size, data);
7388 break;
7389 case NVME_REG_ACQ + 4:
7390 stl_le_p((uint8_t *)&n->bar.acq + 4, data);
7391 trace_pci_nvme_mmio_acqaddr_hi(data, ldq_le_p(&n->bar.acq));
7392 break;
7393 case NVME_REG_CMBLOC:
7394 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbloc_reserved,
7395 "invalid write to reserved CMBLOC"
7396 " when CMBSZ is zero, ignored");
7397 return;
7398 case NVME_REG_CMBSZ:
7399 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbsz_readonly,
7400 "invalid write to read only CMBSZ, ignored");
7401 return;
7402 case NVME_REG_CMBMSC:
7403 if (!NVME_CAP_CMBS(cap)) {
7404 return;
7407 stn_le_p(&n->bar.cmbmsc, size, data);
7408 n->cmb.cmse = false;
7410 if (NVME_CMBMSC_CRE(data)) {
7411 nvme_cmb_enable_regs(n);
7413 if (NVME_CMBMSC_CMSE(data)) {
7414 uint64_t cmbmsc = ldq_le_p(&n->bar.cmbmsc);
7415 hwaddr cba = NVME_CMBMSC_CBA(cmbmsc) << CMBMSC_CBA_SHIFT;
7416 if (cba + int128_get64(n->cmb.mem.size) < cba) {
7417 uint32_t cmbsts = ldl_le_p(&n->bar.cmbsts);
7418 NVME_CMBSTS_SET_CBAI(cmbsts, 1);
7419 stl_le_p(&n->bar.cmbsts, cmbsts);
7420 return;
7423 n->cmb.cba = cba;
7424 n->cmb.cmse = true;
7426 } else {
7427 n->bar.cmbsz = 0;
7428 n->bar.cmbloc = 0;
7431 return;
7432 case NVME_REG_CMBMSC + 4:
7433 stl_le_p((uint8_t *)&n->bar.cmbmsc + 4, data);
7434 return;
7436 case NVME_REG_PMRCAP:
7437 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrcap_readonly,
7438 "invalid write to PMRCAP register, ignored");
7439 return;
7440 case NVME_REG_PMRCTL:
7441 if (!NVME_CAP_PMRS(cap)) {
7442 return;
7445 stl_le_p(&n->bar.pmrctl, data);
7446 if (NVME_PMRCTL_EN(data)) {
7447 memory_region_set_enabled(&n->pmr.dev->mr, true);
7448 pmrsts = 0;
7449 } else {
7450 memory_region_set_enabled(&n->pmr.dev->mr, false);
7451 NVME_PMRSTS_SET_NRDY(pmrsts, 1);
7452 n->pmr.cmse = false;
7454 stl_le_p(&n->bar.pmrsts, pmrsts);
7455 return;
7456 case NVME_REG_PMRSTS:
7457 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrsts_readonly,
7458 "invalid write to PMRSTS register, ignored");
7459 return;
7460 case NVME_REG_PMREBS:
7461 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrebs_readonly,
7462 "invalid write to PMREBS register, ignored");
7463 return;
7464 case NVME_REG_PMRSWTP:
7465 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrswtp_readonly,
7466 "invalid write to PMRSWTP register, ignored");
7467 return;
7468 case NVME_REG_PMRMSCL:
7469 if (!NVME_CAP_PMRS(cap)) {
7470 return;
7473 stl_le_p(&n->bar.pmrmscl, data);
7474 n->pmr.cmse = false;
7476 if (NVME_PMRMSCL_CMSE(data)) {
7477 uint64_t pmrmscu = ldl_le_p(&n->bar.pmrmscu);
7478 hwaddr cba = pmrmscu << 32 |
7479 (NVME_PMRMSCL_CBA(data) << PMRMSCL_CBA_SHIFT);
7480 if (cba + int128_get64(n->pmr.dev->mr.size) < cba) {
7481 NVME_PMRSTS_SET_CBAI(pmrsts, 1);
7482 stl_le_p(&n->bar.pmrsts, pmrsts);
7483 return;
7486 n->pmr.cmse = true;
7487 n->pmr.cba = cba;
7490 return;
7491 case NVME_REG_PMRMSCU:
7492 if (!NVME_CAP_PMRS(cap)) {
7493 return;
7496 stl_le_p(&n->bar.pmrmscu, data);
7497 return;
7498 default:
7499 NVME_GUEST_ERR(pci_nvme_ub_mmiowr_invalid,
7500 "invalid MMIO write,"
7501 " offset=0x%"PRIx64", data=%"PRIx64"",
7502 offset, data);
7503 break;
7507 static uint64_t nvme_mmio_read(void *opaque, hwaddr addr, unsigned size)
7509 NvmeCtrl *n = (NvmeCtrl *)opaque;
7510 uint8_t *ptr = (uint8_t *)&n->bar;
7512 trace_pci_nvme_mmio_read(addr, size);
7514 if (unlikely(addr & (sizeof(uint32_t) - 1))) {
7515 NVME_GUEST_ERR(pci_nvme_ub_mmiord_misaligned32,
7516 "MMIO read not 32-bit aligned,"
7517 " offset=0x%"PRIx64"", addr);
7518 /* should RAZ, fall through for now */
7519 } else if (unlikely(size < sizeof(uint32_t))) {
7520 NVME_GUEST_ERR(pci_nvme_ub_mmiord_toosmall,
7521 "MMIO read smaller than 32-bits,"
7522 " offset=0x%"PRIx64"", addr);
7523 /* should RAZ, fall through for now */
7526 if (addr > sizeof(n->bar) - size) {
7527 NVME_GUEST_ERR(pci_nvme_ub_mmiord_invalid_ofs,
7528 "MMIO read beyond last register,"
7529 " offset=0x%"PRIx64", returning 0", addr);
7531 return 0;
7534 if (pci_is_vf(PCI_DEVICE(n)) && !nvme_sctrl(n)->scs &&
7535 addr != NVME_REG_CSTS) {
7536 trace_pci_nvme_err_ignored_mmio_vf_offline(addr, size);
7537 return 0;
7541 * When PMRWBM bit 1 is set then read from
7542 * from PMRSTS should ensure prior writes
7543 * made it to persistent media
7545 if (addr == NVME_REG_PMRSTS &&
7546 (NVME_PMRCAP_PMRWBM(ldl_le_p(&n->bar.pmrcap)) & 0x02)) {
7547 memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
7550 return ldn_le_p(ptr + addr, size);
7553 static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)
7555 PCIDevice *pci = PCI_DEVICE(n);
7556 uint32_t qid;
7558 if (unlikely(addr & ((1 << 2) - 1))) {
7559 NVME_GUEST_ERR(pci_nvme_ub_db_wr_misaligned,
7560 "doorbell write not 32-bit aligned,"
7561 " offset=0x%"PRIx64", ignoring", addr);
7562 return;
7565 if (((addr - 0x1000) >> 2) & 1) {
7566 /* Completion queue doorbell write */
7568 uint16_t new_head = val & 0xffff;
7569 int start_sqs;
7570 NvmeCQueue *cq;
7572 qid = (addr - (0x1000 + (1 << 2))) >> 3;
7573 if (unlikely(nvme_check_cqid(n, qid))) {
7574 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cq,
7575 "completion queue doorbell write"
7576 " for nonexistent queue,"
7577 " sqid=%"PRIu32", ignoring", qid);
7580 * NVM Express v1.3d, Section 4.1 state: "If host software writes
7581 * an invalid value to the Submission Queue Tail Doorbell or
7582 * Completion Queue Head Doorbell regiter and an Asynchronous Event
7583 * Request command is outstanding, then an asynchronous event is
7584 * posted to the Admin Completion Queue with a status code of
7585 * Invalid Doorbell Write Value."
7587 * Also note that the spec includes the "Invalid Doorbell Register"
7588 * status code, but nowhere does it specify when to use it.
7589 * However, it seems reasonable to use it here in a similar
7590 * fashion.
7592 if (n->outstanding_aers) {
7593 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7594 NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
7595 NVME_LOG_ERROR_INFO);
7598 return;
7601 cq = n->cq[qid];
7602 if (unlikely(new_head >= cq->size)) {
7603 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cqhead,
7604 "completion queue doorbell write value"
7605 " beyond queue size, sqid=%"PRIu32","
7606 " new_head=%"PRIu16", ignoring",
7607 qid, new_head);
7609 if (n->outstanding_aers) {
7610 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7611 NVME_AER_INFO_ERR_INVALID_DB_VALUE,
7612 NVME_LOG_ERROR_INFO);
7615 return;
7618 trace_pci_nvme_mmio_doorbell_cq(cq->cqid, new_head);
7620 start_sqs = nvme_cq_full(cq) ? 1 : 0;
7621 cq->head = new_head;
7622 if (!qid && n->dbbuf_enabled) {
7623 pci_dma_write(pci, cq->db_addr, &cq->head, sizeof(cq->head));
7625 if (start_sqs) {
7626 NvmeSQueue *sq;
7627 QTAILQ_FOREACH(sq, &cq->sq_list, entry) {
7628 qemu_bh_schedule(sq->bh);
7630 qemu_bh_schedule(cq->bh);
7633 if (cq->tail == cq->head) {
7634 if (cq->irq_enabled) {
7635 n->cq_pending--;
7638 nvme_irq_deassert(n, cq);
7640 } else {
7641 /* Submission queue doorbell write */
7643 uint16_t new_tail = val & 0xffff;
7644 NvmeSQueue *sq;
7646 qid = (addr - 0x1000) >> 3;
7647 if (unlikely(nvme_check_sqid(n, qid))) {
7648 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sq,
7649 "submission queue doorbell write"
7650 " for nonexistent queue,"
7651 " sqid=%"PRIu32", ignoring", qid);
7653 if (n->outstanding_aers) {
7654 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7655 NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
7656 NVME_LOG_ERROR_INFO);
7659 return;
7662 sq = n->sq[qid];
7663 if (unlikely(new_tail >= sq->size)) {
7664 NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sqtail,
7665 "submission queue doorbell write value"
7666 " beyond queue size, sqid=%"PRIu32","
7667 " new_tail=%"PRIu16", ignoring",
7668 qid, new_tail);
7670 if (n->outstanding_aers) {
7671 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7672 NVME_AER_INFO_ERR_INVALID_DB_VALUE,
7673 NVME_LOG_ERROR_INFO);
7676 return;
7679 trace_pci_nvme_mmio_doorbell_sq(sq->sqid, new_tail);
7681 sq->tail = new_tail;
7682 if (!qid && n->dbbuf_enabled) {
7684 * The spec states "the host shall also update the controller's
7685 * corresponding doorbell property to match the value of that entry
7686 * in the Shadow Doorbell buffer."
7688 * Since this context is currently a VM trap, we can safely enforce
7689 * the requirement from the device side in case the host is
7690 * misbehaving.
7692 * Note, we shouldn't have to do this, but various drivers
7693 * including ones that run on Linux, are not updating Admin Queues,
7694 * so we can't trust reading it for an appropriate sq tail.
7696 pci_dma_write(pci, sq->db_addr, &sq->tail, sizeof(sq->tail));
7699 qemu_bh_schedule(sq->bh);
7703 static void nvme_mmio_write(void *opaque, hwaddr addr, uint64_t data,
7704 unsigned size)
7706 NvmeCtrl *n = (NvmeCtrl *)opaque;
7708 trace_pci_nvme_mmio_write(addr, data, size);
7710 if (pci_is_vf(PCI_DEVICE(n)) && !nvme_sctrl(n)->scs &&
7711 addr != NVME_REG_CSTS) {
7712 trace_pci_nvme_err_ignored_mmio_vf_offline(addr, size);
7713 return;
7716 if (addr < sizeof(n->bar)) {
7717 nvme_write_bar(n, addr, data, size);
7718 } else {
7719 nvme_process_db(n, addr, data);
7723 static const MemoryRegionOps nvme_mmio_ops = {
7724 .read = nvme_mmio_read,
7725 .write = nvme_mmio_write,
7726 .endianness = DEVICE_LITTLE_ENDIAN,
7727 .impl = {
7728 .min_access_size = 2,
7729 .max_access_size = 8,
7733 static void nvme_cmb_write(void *opaque, hwaddr addr, uint64_t data,
7734 unsigned size)
7736 NvmeCtrl *n = (NvmeCtrl *)opaque;
7737 stn_le_p(&n->cmb.buf[addr], size, data);
7740 static uint64_t nvme_cmb_read(void *opaque, hwaddr addr, unsigned size)
7742 NvmeCtrl *n = (NvmeCtrl *)opaque;
7743 return ldn_le_p(&n->cmb.buf[addr], size);
7746 static const MemoryRegionOps nvme_cmb_ops = {
7747 .read = nvme_cmb_read,
7748 .write = nvme_cmb_write,
7749 .endianness = DEVICE_LITTLE_ENDIAN,
7750 .impl = {
7751 .min_access_size = 1,
7752 .max_access_size = 8,
7756 static bool nvme_check_params(NvmeCtrl *n, Error **errp)
7758 NvmeParams *params = &n->params;
7760 if (params->num_queues) {
7761 warn_report("num_queues is deprecated; please use max_ioqpairs "
7762 "instead");
7764 params->max_ioqpairs = params->num_queues - 1;
7767 if (n->namespace.blkconf.blk && n->subsys) {
7768 error_setg(errp, "subsystem support is unavailable with legacy "
7769 "namespace ('drive' property)");
7770 return false;
7773 if (params->max_ioqpairs < 1 ||
7774 params->max_ioqpairs > NVME_MAX_IOQPAIRS) {
7775 error_setg(errp, "max_ioqpairs must be between 1 and %d",
7776 NVME_MAX_IOQPAIRS);
7777 return false;
7780 if (params->msix_qsize < 1 ||
7781 params->msix_qsize > PCI_MSIX_FLAGS_QSIZE + 1) {
7782 error_setg(errp, "msix_qsize must be between 1 and %d",
7783 PCI_MSIX_FLAGS_QSIZE + 1);
7784 return false;
7787 if (!params->serial) {
7788 error_setg(errp, "serial property not set");
7789 return false;
7792 if (n->pmr.dev) {
7793 if (host_memory_backend_is_mapped(n->pmr.dev)) {
7794 error_setg(errp, "can't use already busy memdev: %s",
7795 object_get_canonical_path_component(OBJECT(n->pmr.dev)));
7796 return false;
7799 if (!is_power_of_2(n->pmr.dev->size)) {
7800 error_setg(errp, "pmr backend size needs to be power of 2 in size");
7801 return false;
7804 host_memory_backend_set_mapped(n->pmr.dev, true);
7807 if (n->params.zasl > n->params.mdts) {
7808 error_setg(errp, "zoned.zasl (Zone Append Size Limit) must be less "
7809 "than or equal to mdts (Maximum Data Transfer Size)");
7810 return false;
7813 if (!n->params.vsl) {
7814 error_setg(errp, "vsl must be non-zero");
7815 return false;
7818 if (params->sriov_max_vfs) {
7819 if (!n->subsys) {
7820 error_setg(errp, "subsystem is required for the use of SR-IOV");
7821 return false;
7824 if (params->sriov_max_vfs > NVME_MAX_VFS) {
7825 error_setg(errp, "sriov_max_vfs must be between 0 and %d",
7826 NVME_MAX_VFS);
7827 return false;
7830 if (params->cmb_size_mb) {
7831 error_setg(errp, "CMB is not supported with SR-IOV");
7832 return false;
7835 if (n->pmr.dev) {
7836 error_setg(errp, "PMR is not supported with SR-IOV");
7837 return false;
7840 if (!params->sriov_vq_flexible || !params->sriov_vi_flexible) {
7841 error_setg(errp, "both sriov_vq_flexible and sriov_vi_flexible"
7842 " must be set for the use of SR-IOV");
7843 return false;
7846 if (params->sriov_vq_flexible < params->sriov_max_vfs * 2) {
7847 error_setg(errp, "sriov_vq_flexible must be greater than or equal"
7848 " to %d (sriov_max_vfs * 2)", params->sriov_max_vfs * 2);
7849 return false;
7852 if (params->max_ioqpairs < params->sriov_vq_flexible + 2) {
7853 error_setg(errp, "(max_ioqpairs - sriov_vq_flexible) must be"
7854 " greater than or equal to 2");
7855 return false;
7858 if (params->sriov_vi_flexible < params->sriov_max_vfs) {
7859 error_setg(errp, "sriov_vi_flexible must be greater than or equal"
7860 " to %d (sriov_max_vfs)", params->sriov_max_vfs);
7861 return false;
7864 if (params->msix_qsize < params->sriov_vi_flexible + 1) {
7865 error_setg(errp, "(msix_qsize - sriov_vi_flexible) must be"
7866 " greater than or equal to 1");
7867 return false;
7870 if (params->sriov_max_vi_per_vf &&
7871 (params->sriov_max_vi_per_vf - 1) % NVME_VF_RES_GRANULARITY) {
7872 error_setg(errp, "sriov_max_vi_per_vf must meet:"
7873 " (sriov_max_vi_per_vf - 1) %% %d == 0 and"
7874 " sriov_max_vi_per_vf >= 1", NVME_VF_RES_GRANULARITY);
7875 return false;
7878 if (params->sriov_max_vq_per_vf &&
7879 (params->sriov_max_vq_per_vf < 2 ||
7880 (params->sriov_max_vq_per_vf - 1) % NVME_VF_RES_GRANULARITY)) {
7881 error_setg(errp, "sriov_max_vq_per_vf must meet:"
7882 " (sriov_max_vq_per_vf - 1) %% %d == 0 and"
7883 " sriov_max_vq_per_vf >= 2", NVME_VF_RES_GRANULARITY);
7884 return false;
7888 return true;
7891 static void nvme_init_state(NvmeCtrl *n)
7893 NvmePriCtrlCap *cap = &n->pri_ctrl_cap;
7894 NvmeSecCtrlList *list = &n->sec_ctrl_list;
7895 NvmeSecCtrlEntry *sctrl;
7896 PCIDevice *pci = PCI_DEVICE(n);
7897 uint8_t max_vfs;
7898 int i;
7900 if (pci_is_vf(pci)) {
7901 sctrl = nvme_sctrl(n);
7902 max_vfs = 0;
7903 n->conf_ioqpairs = sctrl->nvq ? le16_to_cpu(sctrl->nvq) - 1 : 0;
7904 n->conf_msix_qsize = sctrl->nvi ? le16_to_cpu(sctrl->nvi) : 1;
7905 } else {
7906 max_vfs = n->params.sriov_max_vfs;
7907 n->conf_ioqpairs = n->params.max_ioqpairs;
7908 n->conf_msix_qsize = n->params.msix_qsize;
7911 n->sq = g_new0(NvmeSQueue *, n->params.max_ioqpairs + 1);
7912 n->cq = g_new0(NvmeCQueue *, n->params.max_ioqpairs + 1);
7913 n->temperature = NVME_TEMPERATURE;
7914 n->features.temp_thresh_hi = NVME_TEMPERATURE_WARNING;
7915 n->starttime_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
7916 n->aer_reqs = g_new0(NvmeRequest *, n->params.aerl + 1);
7917 QTAILQ_INIT(&n->aer_queue);
7919 list->numcntl = cpu_to_le16(max_vfs);
7920 for (i = 0; i < max_vfs; i++) {
7921 sctrl = &list->sec[i];
7922 sctrl->pcid = cpu_to_le16(n->cntlid);
7923 sctrl->vfn = cpu_to_le16(i + 1);
7926 cap->cntlid = cpu_to_le16(n->cntlid);
7927 cap->crt = NVME_CRT_VQ | NVME_CRT_VI;
7929 if (pci_is_vf(pci)) {
7930 cap->vqprt = cpu_to_le16(1 + n->conf_ioqpairs);
7931 } else {
7932 cap->vqprt = cpu_to_le16(1 + n->params.max_ioqpairs -
7933 n->params.sriov_vq_flexible);
7934 cap->vqfrt = cpu_to_le32(n->params.sriov_vq_flexible);
7935 cap->vqrfap = cap->vqfrt;
7936 cap->vqgran = cpu_to_le16(NVME_VF_RES_GRANULARITY);
7937 cap->vqfrsm = n->params.sriov_max_vq_per_vf ?
7938 cpu_to_le16(n->params.sriov_max_vq_per_vf) :
7939 cap->vqfrt / MAX(max_vfs, 1);
7942 if (pci_is_vf(pci)) {
7943 cap->viprt = cpu_to_le16(n->conf_msix_qsize);
7944 } else {
7945 cap->viprt = cpu_to_le16(n->params.msix_qsize -
7946 n->params.sriov_vi_flexible);
7947 cap->vifrt = cpu_to_le32(n->params.sriov_vi_flexible);
7948 cap->virfap = cap->vifrt;
7949 cap->vigran = cpu_to_le16(NVME_VF_RES_GRANULARITY);
7950 cap->vifrsm = n->params.sriov_max_vi_per_vf ?
7951 cpu_to_le16(n->params.sriov_max_vi_per_vf) :
7952 cap->vifrt / MAX(max_vfs, 1);
7956 static void nvme_init_cmb(NvmeCtrl *n, PCIDevice *pci_dev)
7958 uint64_t cmb_size = n->params.cmb_size_mb * MiB;
7959 uint64_t cap = ldq_le_p(&n->bar.cap);
7961 n->cmb.buf = g_malloc0(cmb_size);
7962 memory_region_init_io(&n->cmb.mem, OBJECT(n), &nvme_cmb_ops, n,
7963 "nvme-cmb", cmb_size);
7964 pci_register_bar(pci_dev, NVME_CMB_BIR,
7965 PCI_BASE_ADDRESS_SPACE_MEMORY |
7966 PCI_BASE_ADDRESS_MEM_TYPE_64 |
7967 PCI_BASE_ADDRESS_MEM_PREFETCH, &n->cmb.mem);
7969 NVME_CAP_SET_CMBS(cap, 1);
7970 stq_le_p(&n->bar.cap, cap);
7972 if (n->params.legacy_cmb) {
7973 nvme_cmb_enable_regs(n);
7974 n->cmb.cmse = true;
7978 static void nvme_init_pmr(NvmeCtrl *n, PCIDevice *pci_dev)
7980 uint32_t pmrcap = ldl_le_p(&n->bar.pmrcap);
7982 NVME_PMRCAP_SET_RDS(pmrcap, 1);
7983 NVME_PMRCAP_SET_WDS(pmrcap, 1);
7984 NVME_PMRCAP_SET_BIR(pmrcap, NVME_PMR_BIR);
7985 /* Turn on bit 1 support */
7986 NVME_PMRCAP_SET_PMRWBM(pmrcap, 0x02);
7987 NVME_PMRCAP_SET_CMSS(pmrcap, 1);
7988 stl_le_p(&n->bar.pmrcap, pmrcap);
7990 pci_register_bar(pci_dev, NVME_PMR_BIR,
7991 PCI_BASE_ADDRESS_SPACE_MEMORY |
7992 PCI_BASE_ADDRESS_MEM_TYPE_64 |
7993 PCI_BASE_ADDRESS_MEM_PREFETCH, &n->pmr.dev->mr);
7995 memory_region_set_enabled(&n->pmr.dev->mr, false);
7998 static uint64_t nvme_bar_size(unsigned total_queues, unsigned total_irqs,
7999 unsigned *msix_table_offset,
8000 unsigned *msix_pba_offset)
8002 uint64_t bar_size, msix_table_size, msix_pba_size;
8004 bar_size = sizeof(NvmeBar) + 2 * total_queues * NVME_DB_SIZE;
8005 bar_size = QEMU_ALIGN_UP(bar_size, 4 * KiB);
8007 if (msix_table_offset) {
8008 *msix_table_offset = bar_size;
8011 msix_table_size = PCI_MSIX_ENTRY_SIZE * total_irqs;
8012 bar_size += msix_table_size;
8013 bar_size = QEMU_ALIGN_UP(bar_size, 4 * KiB);
8015 if (msix_pba_offset) {
8016 *msix_pba_offset = bar_size;
8019 msix_pba_size = QEMU_ALIGN_UP(total_irqs, 64) / 8;
8020 bar_size += msix_pba_size;
8022 bar_size = pow2ceil(bar_size);
8023 return bar_size;
8026 static void nvme_init_sriov(NvmeCtrl *n, PCIDevice *pci_dev, uint16_t offset)
8028 uint16_t vf_dev_id = n->params.use_intel_id ?
8029 PCI_DEVICE_ID_INTEL_NVME : PCI_DEVICE_ID_REDHAT_NVME;
8030 NvmePriCtrlCap *cap = &n->pri_ctrl_cap;
8031 uint64_t bar_size = nvme_bar_size(le16_to_cpu(cap->vqfrsm),
8032 le16_to_cpu(cap->vifrsm),
8033 NULL, NULL);
8035 pcie_sriov_pf_init(pci_dev, offset, "nvme", vf_dev_id,
8036 n->params.sriov_max_vfs, n->params.sriov_max_vfs,
8037 NVME_VF_OFFSET, NVME_VF_STRIDE);
8039 pcie_sriov_pf_init_vf_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |
8040 PCI_BASE_ADDRESS_MEM_TYPE_64, bar_size);
8043 static int nvme_add_pm_capability(PCIDevice *pci_dev, uint8_t offset)
8045 Error *err = NULL;
8046 int ret;
8048 ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, offset,
8049 PCI_PM_SIZEOF, &err);
8050 if (err) {
8051 error_report_err(err);
8052 return ret;
8055 pci_set_word(pci_dev->config + offset + PCI_PM_PMC,
8056 PCI_PM_CAP_VER_1_2);
8057 pci_set_word(pci_dev->config + offset + PCI_PM_CTRL,
8058 PCI_PM_CTRL_NO_SOFT_RESET);
8059 pci_set_word(pci_dev->wmask + offset + PCI_PM_CTRL,
8060 PCI_PM_CTRL_STATE_MASK);
8062 return 0;
8065 static bool nvme_init_pci(NvmeCtrl *n, PCIDevice *pci_dev, Error **errp)
8067 ERRP_GUARD();
8068 uint8_t *pci_conf = pci_dev->config;
8069 uint64_t bar_size;
8070 unsigned msix_table_offset, msix_pba_offset;
8071 int ret;
8073 pci_conf[PCI_INTERRUPT_PIN] = 1;
8074 pci_config_set_prog_interface(pci_conf, 0x2);
8076 if (n->params.use_intel_id) {
8077 pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
8078 pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_NVME);
8079 } else {
8080 pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REDHAT);
8081 pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REDHAT_NVME);
8084 pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_EXPRESS);
8085 nvme_add_pm_capability(pci_dev, 0x60);
8086 pcie_endpoint_cap_init(pci_dev, 0x80);
8087 pcie_cap_flr_init(pci_dev);
8088 if (n->params.sriov_max_vfs) {
8089 pcie_ari_init(pci_dev, 0x100, 1);
8092 /* add one to max_ioqpairs to account for the admin queue pair */
8093 bar_size = nvme_bar_size(n->params.max_ioqpairs + 1, n->params.msix_qsize,
8094 &msix_table_offset, &msix_pba_offset);
8096 memory_region_init(&n->bar0, OBJECT(n), "nvme-bar0", bar_size);
8097 memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, "nvme",
8098 msix_table_offset);
8099 memory_region_add_subregion(&n->bar0, 0, &n->iomem);
8101 if (pci_is_vf(pci_dev)) {
8102 pcie_sriov_vf_register_bar(pci_dev, 0, &n->bar0);
8103 } else {
8104 pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |
8105 PCI_BASE_ADDRESS_MEM_TYPE_64, &n->bar0);
8107 ret = msix_init(pci_dev, n->params.msix_qsize,
8108 &n->bar0, 0, msix_table_offset,
8109 &n->bar0, 0, msix_pba_offset, 0, errp);
8110 if (ret == -ENOTSUP) {
8111 /* report that msix is not supported, but do not error out */
8112 warn_report_err(*errp);
8113 *errp = NULL;
8114 } else if (ret < 0) {
8115 /* propagate error to caller */
8116 return false;
8119 nvme_update_msixcap_ts(pci_dev, n->conf_msix_qsize);
8121 if (n->params.cmb_size_mb) {
8122 nvme_init_cmb(n, pci_dev);
8125 if (n->pmr.dev) {
8126 nvme_init_pmr(n, pci_dev);
8129 if (!pci_is_vf(pci_dev) && n->params.sriov_max_vfs) {
8130 nvme_init_sriov(n, pci_dev, 0x120);
8133 return true;
8136 static void nvme_init_subnqn(NvmeCtrl *n)
8138 NvmeSubsystem *subsys = n->subsys;
8139 NvmeIdCtrl *id = &n->id_ctrl;
8141 if (!subsys) {
8142 snprintf((char *)id->subnqn, sizeof(id->subnqn),
8143 "nqn.2019-08.org.qemu:%s", n->params.serial);
8144 } else {
8145 pstrcpy((char *)id->subnqn, sizeof(id->subnqn), (char*)subsys->subnqn);
8149 static void nvme_init_ctrl(NvmeCtrl *n, PCIDevice *pci_dev)
8151 NvmeIdCtrl *id = &n->id_ctrl;
8152 uint8_t *pci_conf = pci_dev->config;
8153 uint64_t cap = ldq_le_p(&n->bar.cap);
8154 NvmeSecCtrlEntry *sctrl = nvme_sctrl(n);
8155 uint32_t ctratt;
8157 id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID));
8158 id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID));
8159 strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' ');
8160 strpadcpy((char *)id->fr, sizeof(id->fr), QEMU_VERSION, ' ');
8161 strpadcpy((char *)id->sn, sizeof(id->sn), n->params.serial, ' ');
8163 id->cntlid = cpu_to_le16(n->cntlid);
8165 id->oaes = cpu_to_le32(NVME_OAES_NS_ATTR);
8166 ctratt = NVME_CTRATT_ELBAS;
8168 id->rab = 6;
8170 if (n->params.use_intel_id) {
8171 id->ieee[0] = 0xb3;
8172 id->ieee[1] = 0x02;
8173 id->ieee[2] = 0x00;
8174 } else {
8175 id->ieee[0] = 0x00;
8176 id->ieee[1] = 0x54;
8177 id->ieee[2] = 0x52;
8180 id->mdts = n->params.mdts;
8181 id->ver = cpu_to_le32(NVME_SPEC_VER);
8182 id->oacs =
8183 cpu_to_le16(NVME_OACS_NS_MGMT | NVME_OACS_FORMAT | NVME_OACS_DBBUF |
8184 NVME_OACS_DIRECTIVES);
8185 id->cntrltype = 0x1;
8188 * Because the controller always completes the Abort command immediately,
8189 * there can never be more than one concurrently executing Abort command,
8190 * so this value is never used for anything. Note that there can easily be
8191 * many Abort commands in the queues, but they are not considered
8192 * "executing" until processed by nvme_abort.
8194 * The specification recommends a value of 3 for Abort Command Limit (four
8195 * concurrently outstanding Abort commands), so lets use that though it is
8196 * inconsequential.
8198 id->acl = 3;
8199 id->aerl = n->params.aerl;
8200 id->frmw = (NVME_NUM_FW_SLOTS << 1) | NVME_FRMW_SLOT1_RO;
8201 id->lpa = NVME_LPA_NS_SMART | NVME_LPA_CSE | NVME_LPA_EXTENDED;
8203 /* recommended default value (~70 C) */
8204 id->wctemp = cpu_to_le16(NVME_TEMPERATURE_WARNING);
8205 id->cctemp = cpu_to_le16(NVME_TEMPERATURE_CRITICAL);
8207 id->sqes = (0x6 << 4) | 0x6;
8208 id->cqes = (0x4 << 4) | 0x4;
8209 id->nn = cpu_to_le32(NVME_MAX_NAMESPACES);
8210 id->oncs = cpu_to_le16(NVME_ONCS_WRITE_ZEROES | NVME_ONCS_TIMESTAMP |
8211 NVME_ONCS_FEATURES | NVME_ONCS_DSM |
8212 NVME_ONCS_COMPARE | NVME_ONCS_COPY);
8215 * NOTE: If this device ever supports a command set that does NOT use 0x0
8216 * as a Flush-equivalent operation, support for the broadcast NSID in Flush
8217 * should probably be removed.
8219 * See comment in nvme_io_cmd.
8221 id->vwc = NVME_VWC_NSID_BROADCAST_SUPPORT | NVME_VWC_PRESENT;
8223 id->ocfs = cpu_to_le16(NVME_OCFS_COPY_FORMAT_0 | NVME_OCFS_COPY_FORMAT_1);
8224 id->sgls = cpu_to_le32(NVME_CTRL_SGLS_SUPPORT_NO_ALIGN);
8226 nvme_init_subnqn(n);
8228 id->psd[0].mp = cpu_to_le16(0x9c4);
8229 id->psd[0].enlat = cpu_to_le32(0x10);
8230 id->psd[0].exlat = cpu_to_le32(0x4);
8232 if (n->subsys) {
8233 id->cmic |= NVME_CMIC_MULTI_CTRL;
8234 ctratt |= NVME_CTRATT_ENDGRPS;
8236 id->endgidmax = cpu_to_le16(0x1);
8238 if (n->subsys->endgrp.fdp.enabled) {
8239 ctratt |= NVME_CTRATT_FDPS;
8243 id->ctratt = cpu_to_le32(ctratt);
8245 NVME_CAP_SET_MQES(cap, 0x7ff);
8246 NVME_CAP_SET_CQR(cap, 1);
8247 NVME_CAP_SET_TO(cap, 0xf);
8248 NVME_CAP_SET_CSS(cap, NVME_CAP_CSS_NVM);
8249 NVME_CAP_SET_CSS(cap, NVME_CAP_CSS_CSI_SUPP);
8250 NVME_CAP_SET_CSS(cap, NVME_CAP_CSS_ADMIN_ONLY);
8251 NVME_CAP_SET_MPSMAX(cap, 4);
8252 NVME_CAP_SET_CMBS(cap, n->params.cmb_size_mb ? 1 : 0);
8253 NVME_CAP_SET_PMRS(cap, n->pmr.dev ? 1 : 0);
8254 stq_le_p(&n->bar.cap, cap);
8256 stl_le_p(&n->bar.vs, NVME_SPEC_VER);
8257 n->bar.intmc = n->bar.intms = 0;
8259 if (pci_is_vf(pci_dev) && !sctrl->scs) {
8260 stl_le_p(&n->bar.csts, NVME_CSTS_FAILED);
8264 static int nvme_init_subsys(NvmeCtrl *n, Error **errp)
8266 int cntlid;
8268 if (!n->subsys) {
8269 return 0;
8272 cntlid = nvme_subsys_register_ctrl(n, errp);
8273 if (cntlid < 0) {
8274 return -1;
8277 n->cntlid = cntlid;
8279 return 0;
8282 void nvme_attach_ns(NvmeCtrl *n, NvmeNamespace *ns)
8284 uint32_t nsid = ns->params.nsid;
8285 assert(nsid && nsid <= NVME_MAX_NAMESPACES);
8287 n->namespaces[nsid] = ns;
8288 ns->attached++;
8290 n->dmrsl = MIN_NON_ZERO(n->dmrsl,
8291 BDRV_REQUEST_MAX_BYTES / nvme_l2b(ns, 1));
8294 static void nvme_realize(PCIDevice *pci_dev, Error **errp)
8296 NvmeCtrl *n = NVME(pci_dev);
8297 DeviceState *dev = DEVICE(pci_dev);
8298 NvmeNamespace *ns;
8299 NvmeCtrl *pn = NVME(pcie_sriov_get_pf(pci_dev));
8301 if (pci_is_vf(pci_dev)) {
8303 * VFs derive settings from the parent. PF's lifespan exceeds
8304 * that of VF's, so it's safe to share params.serial.
8306 memcpy(&n->params, &pn->params, sizeof(NvmeParams));
8307 n->subsys = pn->subsys;
8310 if (!nvme_check_params(n, errp)) {
8311 return;
8314 qbus_init(&n->bus, sizeof(NvmeBus), TYPE_NVME_BUS, dev, dev->id);
8316 if (nvme_init_subsys(n, errp)) {
8317 return;
8319 nvme_init_state(n);
8320 if (!nvme_init_pci(n, pci_dev, errp)) {
8321 return;
8323 nvme_init_ctrl(n, pci_dev);
8325 /* setup a namespace if the controller drive property was given */
8326 if (n->namespace.blkconf.blk) {
8327 ns = &n->namespace;
8328 ns->params.nsid = 1;
8330 if (nvme_ns_setup(ns, errp)) {
8331 return;
8334 nvme_attach_ns(n, ns);
8338 static void nvme_exit(PCIDevice *pci_dev)
8340 NvmeCtrl *n = NVME(pci_dev);
8341 NvmeNamespace *ns;
8342 int i;
8344 nvme_ctrl_reset(n, NVME_RESET_FUNCTION);
8346 if (n->subsys) {
8347 for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
8348 ns = nvme_ns(n, i);
8349 if (ns) {
8350 ns->attached--;
8354 nvme_subsys_unregister_ctrl(n->subsys, n);
8357 g_free(n->cq);
8358 g_free(n->sq);
8359 g_free(n->aer_reqs);
8361 if (n->params.cmb_size_mb) {
8362 g_free(n->cmb.buf);
8365 if (n->pmr.dev) {
8366 host_memory_backend_set_mapped(n->pmr.dev, false);
8369 if (!pci_is_vf(pci_dev) && n->params.sriov_max_vfs) {
8370 pcie_sriov_pf_exit(pci_dev);
8373 msix_uninit(pci_dev, &n->bar0, &n->bar0);
8374 memory_region_del_subregion(&n->bar0, &n->iomem);
8377 static Property nvme_props[] = {
8378 DEFINE_BLOCK_PROPERTIES(NvmeCtrl, namespace.blkconf),
8379 DEFINE_PROP_LINK("pmrdev", NvmeCtrl, pmr.dev, TYPE_MEMORY_BACKEND,
8380 HostMemoryBackend *),
8381 DEFINE_PROP_LINK("subsys", NvmeCtrl, subsys, TYPE_NVME_SUBSYS,
8382 NvmeSubsystem *),
8383 DEFINE_PROP_STRING("serial", NvmeCtrl, params.serial),
8384 DEFINE_PROP_UINT32("cmb_size_mb", NvmeCtrl, params.cmb_size_mb, 0),
8385 DEFINE_PROP_UINT32("num_queues", NvmeCtrl, params.num_queues, 0),
8386 DEFINE_PROP_UINT32("max_ioqpairs", NvmeCtrl, params.max_ioqpairs, 64),
8387 DEFINE_PROP_UINT16("msix_qsize", NvmeCtrl, params.msix_qsize, 65),
8388 DEFINE_PROP_UINT8("aerl", NvmeCtrl, params.aerl, 3),
8389 DEFINE_PROP_UINT32("aer_max_queued", NvmeCtrl, params.aer_max_queued, 64),
8390 DEFINE_PROP_UINT8("mdts", NvmeCtrl, params.mdts, 7),
8391 DEFINE_PROP_UINT8("vsl", NvmeCtrl, params.vsl, 7),
8392 DEFINE_PROP_BOOL("use-intel-id", NvmeCtrl, params.use_intel_id, false),
8393 DEFINE_PROP_BOOL("legacy-cmb", NvmeCtrl, params.legacy_cmb, false),
8394 DEFINE_PROP_BOOL("ioeventfd", NvmeCtrl, params.ioeventfd, false),
8395 DEFINE_PROP_UINT8("zoned.zasl", NvmeCtrl, params.zasl, 0),
8396 DEFINE_PROP_BOOL("zoned.auto_transition", NvmeCtrl,
8397 params.auto_transition_zones, true),
8398 DEFINE_PROP_UINT8("sriov_max_vfs", NvmeCtrl, params.sriov_max_vfs, 0),
8399 DEFINE_PROP_UINT16("sriov_vq_flexible", NvmeCtrl,
8400 params.sriov_vq_flexible, 0),
8401 DEFINE_PROP_UINT16("sriov_vi_flexible", NvmeCtrl,
8402 params.sriov_vi_flexible, 0),
8403 DEFINE_PROP_UINT8("sriov_max_vi_per_vf", NvmeCtrl,
8404 params.sriov_max_vi_per_vf, 0),
8405 DEFINE_PROP_UINT8("sriov_max_vq_per_vf", NvmeCtrl,
8406 params.sriov_max_vq_per_vf, 0),
8407 DEFINE_PROP_END_OF_LIST(),
8410 static void nvme_get_smart_warning(Object *obj, Visitor *v, const char *name,
8411 void *opaque, Error **errp)
8413 NvmeCtrl *n = NVME(obj);
8414 uint8_t value = n->smart_critical_warning;
8416 visit_type_uint8(v, name, &value, errp);
8419 static void nvme_set_smart_warning(Object *obj, Visitor *v, const char *name,
8420 void *opaque, Error **errp)
8422 NvmeCtrl *n = NVME(obj);
8423 uint8_t value, old_value, cap = 0, index, event;
8425 if (!visit_type_uint8(v, name, &value, errp)) {
8426 return;
8429 cap = NVME_SMART_SPARE | NVME_SMART_TEMPERATURE | NVME_SMART_RELIABILITY
8430 | NVME_SMART_MEDIA_READ_ONLY | NVME_SMART_FAILED_VOLATILE_MEDIA;
8431 if (NVME_CAP_PMRS(ldq_le_p(&n->bar.cap))) {
8432 cap |= NVME_SMART_PMR_UNRELIABLE;
8435 if ((value & cap) != value) {
8436 error_setg(errp, "unsupported smart critical warning bits: 0x%x",
8437 value & ~cap);
8438 return;
8441 old_value = n->smart_critical_warning;
8442 n->smart_critical_warning = value;
8444 /* only inject new bits of smart critical warning */
8445 for (index = 0; index < NVME_SMART_WARN_MAX; index++) {
8446 event = 1 << index;
8447 if (value & ~old_value & event)
8448 nvme_smart_event(n, event);
8452 static void nvme_pci_reset(DeviceState *qdev)
8454 PCIDevice *pci_dev = PCI_DEVICE(qdev);
8455 NvmeCtrl *n = NVME(pci_dev);
8457 trace_pci_nvme_pci_reset();
8458 nvme_ctrl_reset(n, NVME_RESET_FUNCTION);
8461 static void nvme_sriov_pre_write_ctrl(PCIDevice *dev, uint32_t address,
8462 uint32_t val, int len)
8464 NvmeCtrl *n = NVME(dev);
8465 NvmeSecCtrlEntry *sctrl;
8466 uint16_t sriov_cap = dev->exp.sriov_cap;
8467 uint32_t off = address - sriov_cap;
8468 int i, num_vfs;
8470 if (!sriov_cap) {
8471 return;
8474 if (range_covers_byte(off, len, PCI_SRIOV_CTRL)) {
8475 if (!(val & PCI_SRIOV_CTRL_VFE)) {
8476 num_vfs = pci_get_word(dev->config + sriov_cap + PCI_SRIOV_NUM_VF);
8477 for (i = 0; i < num_vfs; i++) {
8478 sctrl = &n->sec_ctrl_list.sec[i];
8479 nvme_virt_set_state(n, le16_to_cpu(sctrl->scid), false);
8485 static void nvme_pci_write_config(PCIDevice *dev, uint32_t address,
8486 uint32_t val, int len)
8488 nvme_sriov_pre_write_ctrl(dev, address, val, len);
8489 pci_default_write_config(dev, address, val, len);
8490 pcie_cap_flr_write_config(dev, address, val, len);
8493 static const VMStateDescription nvme_vmstate = {
8494 .name = "nvme",
8495 .unmigratable = 1,
8498 static void nvme_class_init(ObjectClass *oc, void *data)
8500 DeviceClass *dc = DEVICE_CLASS(oc);
8501 PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc);
8503 pc->realize = nvme_realize;
8504 pc->config_write = nvme_pci_write_config;
8505 pc->exit = nvme_exit;
8506 pc->class_id = PCI_CLASS_STORAGE_EXPRESS;
8507 pc->revision = 2;
8509 set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
8510 dc->desc = "Non-Volatile Memory Express";
8511 device_class_set_props(dc, nvme_props);
8512 dc->vmsd = &nvme_vmstate;
8513 dc->reset = nvme_pci_reset;
8516 static void nvme_instance_init(Object *obj)
8518 NvmeCtrl *n = NVME(obj);
8520 device_add_bootindex_property(obj, &n->namespace.blkconf.bootindex,
8521 "bootindex", "/namespace@1,0",
8522 DEVICE(obj));
8524 object_property_add(obj, "smart_critical_warning", "uint8",
8525 nvme_get_smart_warning,
8526 nvme_set_smart_warning, NULL, NULL);
8529 static const TypeInfo nvme_info = {
8530 .name = TYPE_NVME,
8531 .parent = TYPE_PCI_DEVICE,
8532 .instance_size = sizeof(NvmeCtrl),
8533 .instance_init = nvme_instance_init,
8534 .class_init = nvme_class_init,
8535 .interfaces = (InterfaceInfo[]) {
8536 { INTERFACE_PCIE_DEVICE },
8541 static const TypeInfo nvme_bus_info = {
8542 .name = TYPE_NVME_BUS,
8543 .parent = TYPE_BUS,
8544 .instance_size = sizeof(NvmeBus),
8547 static void nvme_register_types(void)
8549 type_register_static(&nvme_info);
8550 type_register_static(&nvme_bus_info);
8553 type_init(nvme_register_types)