xref: /openbmc/qemu/hw/nvme/ctrl.c (revision 0af3dfa5)
1 /*
2  * QEMU NVM Express Controller
3  *
4  * Copyright (c) 2012, Intel Corporation
5  *
6  * Written by Keith Busch <keith.busch@intel.com>
7  *
8  * This code is licensed under the GNU GPL v2 or later.
9  */
10 
11 /**
12  * Reference Specs: http://www.nvmexpress.org, 1.4, 1.3, 1.2, 1.1, 1.0e
13  *
14  *  https://nvmexpress.org/developers/nvme-specification/
15  *
16  *
17  * Notes on coding style
18  * ---------------------
19  * While QEMU coding style prefers lowercase hexadecimals in constants, the
20  * NVMe subsystem use this format from the NVMe specifications in the comments
21  * (i.e. 'h' suffix instead of '0x' prefix).
22  *
23  * Usage
24  * -----
25  * See docs/system/nvme.rst for extensive documentation.
26  *
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>,shared=<true|false[optional]>, \
47  *              detached=<true|false[optional]>, \
48  *              zoned.zone_size=<N[optional]>, \
49  *              zoned.zone_capacity=<N[optional]>, \
50  *              zoned.descr_ext_size=<N[optional]>, \
51  *              zoned.max_active=<N[optional]>, \
52  *              zoned.max_open=<N[optional]>, \
53  *              zoned.cross_read=<true|false[optional]>
54  *
55  * Note cmb_size_mb denotes size of CMB in MB. CMB is assumed to be at
56  * offset 0 in BAR2 and supports only WDS, RDS and SQS for now. By default, the
57  * device will use the "v1.4 CMB scheme" - use the `legacy-cmb` parameter to
58  * always enable the CMBLOC and CMBSZ registers (v1.3 behavior).
59  *
60  * Enabling pmr emulation can be achieved by pointing to memory-backend-file.
61  * For example:
62  * -object memory-backend-file,id=<mem_id>,share=on,mem-path=<file_path>, \
63  *  size=<size> .... -device nvme,...,pmrdev=<mem_id>
64  *
65  * The PMR will use BAR 4/5 exclusively.
66  *
67  * To place controller(s) and namespace(s) to a subsystem, then provide
68  * nvme-subsys device as above.
69  *
70  * nvme subsystem device parameters
71  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
72  * - `nqn`
73  *   This parameter provides the `<nqn_id>` part of the string
74  *   `nqn.2019-08.org.qemu:<nqn_id>` which will be reported in the SUBNQN field
75  *   of subsystem controllers. Note that `<nqn_id>` should be unique per
76  *   subsystem, but this is not enforced by QEMU. If not specified, it will
77  *   default to the value of the `id` parameter (`<subsys_id>`).
78  *
79  * nvme device parameters
80  * ~~~~~~~~~~~~~~~~~~~~~~
81  * - `subsys`
82  *   Specifying this parameter attaches the controller to the subsystem and
83  *   the SUBNQN field in the controller will report the NQN of the subsystem
84  *   device. This also enables multi controller capability represented in
85  *   Identify Controller data structure in CMIC (Controller Multi-path I/O and
86  *   Namespace Sharing Capabilities).
87  *
88  * - `aerl`
89  *   The Asynchronous Event Request Limit (AERL). Indicates the maximum number
90  *   of concurrently outstanding Asynchronous Event Request commands support
91  *   by the controller. This is a 0's based value.
92  *
93  * - `aer_max_queued`
94  *   This is the maximum number of events that the device will enqueue for
95  *   completion when there are no outstanding AERs. When the maximum number of
96  *   enqueued events are reached, subsequent events will be dropped.
97  *
98  * - `mdts`
99  *   Indicates the maximum data transfer size for a command that transfers data
100  *   between host-accessible memory and the controller. The value is specified
101  *   as a power of two (2^n) and is in units of the minimum memory page size
102  *   (CAP.MPSMIN). The default value is 7 (i.e. 512 KiB).
103  *
104  * - `vsl`
105  *   Indicates the maximum data size limit for the Verify command. Like `mdts`,
106  *   this value is specified as a power of two (2^n) and is in units of the
107  *   minimum memory page size (CAP.MPSMIN). The default value is 7 (i.e. 512
108  *   KiB).
109  *
110  * - `zoned.zasl`
111  *   Indicates the maximum data transfer size for the Zone Append command. Like
112  *   `mdts`, the value is specified as a power of two (2^n) and is in units of
113  *   the minimum memory page size (CAP.MPSMIN). The default value is 0 (i.e.
114  *   defaulting to the value of `mdts`).
115  *
116  * - `zoned.auto_transition`
117  *   Indicates if zones in zone state implicitly opened can be automatically
118  *   transitioned to zone state closed for resource management purposes.
119  *   Defaults to 'on'.
120  *
121  * - `sriov_max_vfs`
122  *   Indicates the maximum number of PCIe virtual functions supported
123  *   by the controller. The default value is 0. Specifying a non-zero value
124  *   enables reporting of both SR-IOV and ARI capabilities by the NVMe device.
125  *   Virtual function controllers will not report SR-IOV capability.
126  *
127  *   NOTE: Single Root I/O Virtualization support is experimental.
128  *   All the related parameters may be subject to change.
129  *
130  * - `sriov_vq_flexible`
131  *   Indicates the total number of flexible queue resources assignable to all
132  *   the secondary controllers. Implicitly sets the number of primary
133  *   controller's private resources to `(max_ioqpairs - sriov_vq_flexible)`.
134  *
135  * - `sriov_vi_flexible`
136  *   Indicates the total number of flexible interrupt resources assignable to
137  *   all the secondary controllers. Implicitly sets the number of primary
138  *   controller's private resources to `(msix_qsize - sriov_vi_flexible)`.
139  *
140  * - `sriov_max_vi_per_vf`
141  *   Indicates the maximum number of virtual interrupt resources assignable
142  *   to a secondary controller. The default 0 resolves to
143  *   `(sriov_vi_flexible / sriov_max_vfs)`.
144  *
145  * - `sriov_max_vq_per_vf`
146  *   Indicates the maximum number of virtual queue resources assignable to
147  *   a secondary controller. The default 0 resolves to
148  *   `(sriov_vq_flexible / sriov_max_vfs)`.
149  *
150  * nvme namespace device parameters
151  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152  * - `shared`
153  *   When the parent nvme device (as defined explicitly by the 'bus' parameter
154  *   or implicitly by the most recently defined NvmeBus) is linked to an
155  *   nvme-subsys device, the namespace will be attached to all controllers in
156  *   the subsystem. If set to 'off' (the default), the namespace will remain a
157  *   private namespace and may only be attached to a single controller at a
158  *   time.
159  *
160  * - `detached`
161  *   This parameter is only valid together with the `subsys` parameter. If left
162  *   at the default value (`false/off`), the namespace will be attached to all
163  *   controllers in the NVMe subsystem at boot-up. If set to `true/on`, the
164  *   namespace will be available in the subsystem but not attached to any
165  *   controllers.
166  *
167  * Setting `zoned` to true selects Zoned Command Set at the namespace.
168  * In this case, the following namespace properties are available to configure
169  * zoned operation:
170  *     zoned.zone_size=<zone size in bytes, default: 128MiB>
171  *         The number may be followed by K, M, G as in kilo-, mega- or giga-.
172  *
173  *     zoned.zone_capacity=<zone capacity in bytes, default: zone size>
174  *         The value 0 (default) forces zone capacity to be the same as zone
175  *         size. The value of this property may not exceed zone size.
176  *
177  *     zoned.descr_ext_size=<zone descriptor extension size, default 0>
178  *         This value needs to be specified in 64B units. If it is zero,
179  *         namespace(s) will not support zone descriptor extensions.
180  *
181  *     zoned.max_active=<Maximum Active Resources (zones), default: 0>
182  *         The default value means there is no limit to the number of
183  *         concurrently active zones.
184  *
185  *     zoned.max_open=<Maximum Open Resources (zones), default: 0>
186  *         The default value means there is no limit to the number of
187  *         concurrently open zones.
188  *
189  *     zoned.cross_read=<enable RAZB, default: false>
190  *         Setting this property to true enables Read Across Zone Boundaries.
191  */
192 
193 #include "qemu/osdep.h"
194 #include "qemu/cutils.h"
195 #include "qemu/error-report.h"
196 #include "qemu/log.h"
197 #include "qemu/units.h"
198 #include "qemu/range.h"
199 #include "qapi/error.h"
200 #include "qapi/visitor.h"
201 #include "sysemu/sysemu.h"
202 #include "sysemu/block-backend.h"
203 #include "sysemu/hostmem.h"
204 #include "hw/pci/msix.h"
205 #include "hw/pci/pcie_sriov.h"
206 #include "migration/vmstate.h"
207 
208 #include "nvme.h"
209 #include "dif.h"
210 #include "trace.h"
211 
212 #define NVME_MAX_IOQPAIRS 0xffff
213 #define NVME_DB_SIZE  4
214 #define NVME_SPEC_VER 0x00010400
215 #define NVME_CMB_BIR 2
216 #define NVME_PMR_BIR 4
217 #define NVME_TEMPERATURE 0x143
218 #define NVME_TEMPERATURE_WARNING 0x157
219 #define NVME_TEMPERATURE_CRITICAL 0x175
220 #define NVME_NUM_FW_SLOTS 1
221 #define NVME_DEFAULT_MAX_ZA_SIZE (128 * KiB)
222 #define NVME_VF_RES_GRANULARITY 1
223 #define NVME_VF_OFFSET 0x1
224 #define NVME_VF_STRIDE 1
225 
226 #define NVME_GUEST_ERR(trace, fmt, ...) \
227     do { \
228         (trace_##trace)(__VA_ARGS__); \
229         qemu_log_mask(LOG_GUEST_ERROR, #trace \
230             " in %s: " fmt "\n", __func__, ## __VA_ARGS__); \
231     } while (0)
232 
233 static const bool nvme_feature_support[NVME_FID_MAX] = {
234     [NVME_ARBITRATION]              = true,
235     [NVME_POWER_MANAGEMENT]         = true,
236     [NVME_TEMPERATURE_THRESHOLD]    = true,
237     [NVME_ERROR_RECOVERY]           = true,
238     [NVME_VOLATILE_WRITE_CACHE]     = true,
239     [NVME_NUMBER_OF_QUEUES]         = true,
240     [NVME_INTERRUPT_COALESCING]     = true,
241     [NVME_INTERRUPT_VECTOR_CONF]    = true,
242     [NVME_WRITE_ATOMICITY]          = true,
243     [NVME_ASYNCHRONOUS_EVENT_CONF]  = true,
244     [NVME_TIMESTAMP]                = true,
245     [NVME_HOST_BEHAVIOR_SUPPORT]    = true,
246     [NVME_COMMAND_SET_PROFILE]      = true,
247     [NVME_FDP_MODE]                 = true,
248     [NVME_FDP_EVENTS]               = true,
249 };
250 
251 static const uint32_t nvme_feature_cap[NVME_FID_MAX] = {
252     [NVME_TEMPERATURE_THRESHOLD]    = NVME_FEAT_CAP_CHANGE,
253     [NVME_ERROR_RECOVERY]           = NVME_FEAT_CAP_CHANGE | NVME_FEAT_CAP_NS,
254     [NVME_VOLATILE_WRITE_CACHE]     = NVME_FEAT_CAP_CHANGE,
255     [NVME_NUMBER_OF_QUEUES]         = NVME_FEAT_CAP_CHANGE,
256     [NVME_ASYNCHRONOUS_EVENT_CONF]  = NVME_FEAT_CAP_CHANGE,
257     [NVME_TIMESTAMP]                = NVME_FEAT_CAP_CHANGE,
258     [NVME_HOST_BEHAVIOR_SUPPORT]    = NVME_FEAT_CAP_CHANGE,
259     [NVME_COMMAND_SET_PROFILE]      = NVME_FEAT_CAP_CHANGE,
260     [NVME_FDP_MODE]                 = NVME_FEAT_CAP_CHANGE,
261     [NVME_FDP_EVENTS]               = NVME_FEAT_CAP_CHANGE | NVME_FEAT_CAP_NS,
262 };
263 
264 static const uint32_t nvme_cse_acs[256] = {
265     [NVME_ADM_CMD_DELETE_SQ]        = NVME_CMD_EFF_CSUPP,
266     [NVME_ADM_CMD_CREATE_SQ]        = NVME_CMD_EFF_CSUPP,
267     [NVME_ADM_CMD_GET_LOG_PAGE]     = NVME_CMD_EFF_CSUPP,
268     [NVME_ADM_CMD_DELETE_CQ]        = NVME_CMD_EFF_CSUPP,
269     [NVME_ADM_CMD_CREATE_CQ]        = NVME_CMD_EFF_CSUPP,
270     [NVME_ADM_CMD_IDENTIFY]         = NVME_CMD_EFF_CSUPP,
271     [NVME_ADM_CMD_ABORT]            = NVME_CMD_EFF_CSUPP,
272     [NVME_ADM_CMD_SET_FEATURES]     = NVME_CMD_EFF_CSUPP,
273     [NVME_ADM_CMD_GET_FEATURES]     = NVME_CMD_EFF_CSUPP,
274     [NVME_ADM_CMD_ASYNC_EV_REQ]     = NVME_CMD_EFF_CSUPP,
275     [NVME_ADM_CMD_NS_ATTACHMENT]    = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_NIC,
276     [NVME_ADM_CMD_VIRT_MNGMT]       = NVME_CMD_EFF_CSUPP,
277     [NVME_ADM_CMD_DBBUF_CONFIG]     = NVME_CMD_EFF_CSUPP,
278     [NVME_ADM_CMD_FORMAT_NVM]       = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
279     [NVME_ADM_CMD_DIRECTIVE_RECV]   = NVME_CMD_EFF_CSUPP,
280     [NVME_ADM_CMD_DIRECTIVE_SEND]   = NVME_CMD_EFF_CSUPP,
281 };
282 
283 static const uint32_t nvme_cse_iocs_none[256];
284 
285 static const uint32_t nvme_cse_iocs_nvm[256] = {
286     [NVME_CMD_FLUSH]                = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
287     [NVME_CMD_WRITE_ZEROES]         = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
288     [NVME_CMD_WRITE]                = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
289     [NVME_CMD_READ]                 = NVME_CMD_EFF_CSUPP,
290     [NVME_CMD_DSM]                  = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
291     [NVME_CMD_VERIFY]               = NVME_CMD_EFF_CSUPP,
292     [NVME_CMD_COPY]                 = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
293     [NVME_CMD_COMPARE]              = NVME_CMD_EFF_CSUPP,
294     [NVME_CMD_IO_MGMT_RECV]         = NVME_CMD_EFF_CSUPP,
295     [NVME_CMD_IO_MGMT_SEND]         = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
296 };
297 
298 static const uint32_t nvme_cse_iocs_zoned[256] = {
299     [NVME_CMD_FLUSH]                = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
300     [NVME_CMD_WRITE_ZEROES]         = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
301     [NVME_CMD_WRITE]                = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
302     [NVME_CMD_READ]                 = NVME_CMD_EFF_CSUPP,
303     [NVME_CMD_DSM]                  = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
304     [NVME_CMD_VERIFY]               = NVME_CMD_EFF_CSUPP,
305     [NVME_CMD_COPY]                 = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
306     [NVME_CMD_COMPARE]              = NVME_CMD_EFF_CSUPP,
307     [NVME_CMD_ZONE_APPEND]          = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
308     [NVME_CMD_ZONE_MGMT_SEND]       = NVME_CMD_EFF_CSUPP | NVME_CMD_EFF_LBCC,
309     [NVME_CMD_ZONE_MGMT_RECV]       = NVME_CMD_EFF_CSUPP,
310 };
311 
312 static void nvme_process_sq(void *opaque);
313 static void nvme_ctrl_reset(NvmeCtrl *n, NvmeResetType rst);
314 static inline uint64_t nvme_get_timestamp(const NvmeCtrl *n);
315 
316 static uint16_t nvme_sqid(NvmeRequest *req)
317 {
318     return le16_to_cpu(req->sq->sqid);
319 }
320 
321 static inline uint16_t nvme_make_pid(NvmeNamespace *ns, uint16_t rg,
322                                      uint16_t ph)
323 {
324     uint16_t rgif = ns->endgrp->fdp.rgif;
325 
326     if (!rgif) {
327         return ph;
328     }
329 
330     return (rg << (16 - rgif)) | ph;
331 }
332 
333 static inline bool nvme_ph_valid(NvmeNamespace *ns, uint16_t ph)
334 {
335     return ph < ns->fdp.nphs;
336 }
337 
338 static inline bool nvme_rg_valid(NvmeEnduranceGroup *endgrp, uint16_t rg)
339 {
340     return rg < endgrp->fdp.nrg;
341 }
342 
343 static inline uint16_t nvme_pid2ph(NvmeNamespace *ns, uint16_t pid)
344 {
345     uint16_t rgif = ns->endgrp->fdp.rgif;
346 
347     if (!rgif) {
348         return pid;
349     }
350 
351     return pid & ((1 << (15 - rgif)) - 1);
352 }
353 
354 static inline uint16_t nvme_pid2rg(NvmeNamespace *ns, uint16_t pid)
355 {
356     uint16_t rgif = ns->endgrp->fdp.rgif;
357 
358     if (!rgif) {
359         return 0;
360     }
361 
362     return pid >> (16 - rgif);
363 }
364 
365 static inline bool nvme_parse_pid(NvmeNamespace *ns, uint16_t pid,
366                                   uint16_t *ph, uint16_t *rg)
367 {
368     *rg = nvme_pid2rg(ns, pid);
369     *ph = nvme_pid2ph(ns, pid);
370 
371     return nvme_ph_valid(ns, *ph) && nvme_rg_valid(ns->endgrp, *rg);
372 }
373 
374 static void nvme_assign_zone_state(NvmeNamespace *ns, NvmeZone *zone,
375                                    NvmeZoneState state)
376 {
377     if (QTAILQ_IN_USE(zone, entry)) {
378         switch (nvme_get_zone_state(zone)) {
379         case NVME_ZONE_STATE_EXPLICITLY_OPEN:
380             QTAILQ_REMOVE(&ns->exp_open_zones, zone, entry);
381             break;
382         case NVME_ZONE_STATE_IMPLICITLY_OPEN:
383             QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
384             break;
385         case NVME_ZONE_STATE_CLOSED:
386             QTAILQ_REMOVE(&ns->closed_zones, zone, entry);
387             break;
388         case NVME_ZONE_STATE_FULL:
389             QTAILQ_REMOVE(&ns->full_zones, zone, entry);
390         default:
391             ;
392         }
393     }
394 
395     nvme_set_zone_state(zone, state);
396 
397     switch (state) {
398     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
399         QTAILQ_INSERT_TAIL(&ns->exp_open_zones, zone, entry);
400         break;
401     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
402         QTAILQ_INSERT_TAIL(&ns->imp_open_zones, zone, entry);
403         break;
404     case NVME_ZONE_STATE_CLOSED:
405         QTAILQ_INSERT_TAIL(&ns->closed_zones, zone, entry);
406         break;
407     case NVME_ZONE_STATE_FULL:
408         QTAILQ_INSERT_TAIL(&ns->full_zones, zone, entry);
409     case NVME_ZONE_STATE_READ_ONLY:
410         break;
411     default:
412         zone->d.za = 0;
413     }
414 }
415 
416 static uint16_t nvme_zns_check_resources(NvmeNamespace *ns, uint32_t act,
417                                          uint32_t opn, uint32_t zrwa)
418 {
419     if (ns->params.max_active_zones != 0 &&
420         ns->nr_active_zones + act > ns->params.max_active_zones) {
421         trace_pci_nvme_err_insuff_active_res(ns->params.max_active_zones);
422         return NVME_ZONE_TOO_MANY_ACTIVE | NVME_DNR;
423     }
424 
425     if (ns->params.max_open_zones != 0 &&
426         ns->nr_open_zones + opn > ns->params.max_open_zones) {
427         trace_pci_nvme_err_insuff_open_res(ns->params.max_open_zones);
428         return NVME_ZONE_TOO_MANY_OPEN | NVME_DNR;
429     }
430 
431     if (zrwa > ns->zns.numzrwa) {
432         return NVME_NOZRWA | NVME_DNR;
433     }
434 
435     return NVME_SUCCESS;
436 }
437 
438 /*
439  * Check if we can open a zone without exceeding open/active limits.
440  * AOR stands for "Active and Open Resources" (see TP 4053 section 2.5).
441  */
442 static uint16_t nvme_aor_check(NvmeNamespace *ns, uint32_t act, uint32_t opn)
443 {
444     return nvme_zns_check_resources(ns, act, opn, 0);
445 }
446 
447 static NvmeFdpEvent *nvme_fdp_alloc_event(NvmeCtrl *n, NvmeFdpEventBuffer *ebuf)
448 {
449     NvmeFdpEvent *ret = NULL;
450     bool is_full = ebuf->next == ebuf->start && ebuf->nelems;
451 
452     ret = &ebuf->events[ebuf->next++];
453     if (unlikely(ebuf->next == NVME_FDP_MAX_EVENTS)) {
454         ebuf->next = 0;
455     }
456     if (is_full) {
457         ebuf->start = ebuf->next;
458     } else {
459         ebuf->nelems++;
460     }
461 
462     memset(ret, 0, sizeof(NvmeFdpEvent));
463     ret->timestamp = nvme_get_timestamp(n);
464 
465     return ret;
466 }
467 
468 static inline int log_event(NvmeRuHandle *ruh, uint8_t event_type)
469 {
470     return (ruh->event_filter >> nvme_fdp_evf_shifts[event_type]) & 0x1;
471 }
472 
473 static bool nvme_update_ruh(NvmeCtrl *n, NvmeNamespace *ns, uint16_t pid)
474 {
475     NvmeEnduranceGroup *endgrp = ns->endgrp;
476     NvmeRuHandle *ruh;
477     NvmeReclaimUnit *ru;
478     NvmeFdpEvent *e = NULL;
479     uint16_t ph, rg, ruhid;
480 
481     if (!nvme_parse_pid(ns, pid, &ph, &rg)) {
482         return false;
483     }
484 
485     ruhid = ns->fdp.phs[ph];
486 
487     ruh = &endgrp->fdp.ruhs[ruhid];
488     ru = &ruh->rus[rg];
489 
490     if (ru->ruamw) {
491         if (log_event(ruh, FDP_EVT_RU_NOT_FULLY_WRITTEN)) {
492             e = nvme_fdp_alloc_event(n, &endgrp->fdp.host_events);
493             e->type = FDP_EVT_RU_NOT_FULLY_WRITTEN;
494             e->flags = FDPEF_PIV | FDPEF_NSIDV | FDPEF_LV;
495             e->pid = cpu_to_le16(pid);
496             e->nsid = cpu_to_le32(ns->params.nsid);
497             e->rgid = cpu_to_le16(rg);
498             e->ruhid = cpu_to_le16(ruhid);
499         }
500 
501         /* log (eventual) GC overhead of prematurely swapping the RU */
502         nvme_fdp_stat_inc(&endgrp->fdp.mbmw, nvme_l2b(ns, ru->ruamw));
503     }
504 
505     ru->ruamw = ruh->ruamw;
506 
507     return true;
508 }
509 
510 static bool nvme_addr_is_cmb(NvmeCtrl *n, hwaddr addr)
511 {
512     hwaddr hi, lo;
513 
514     if (!n->cmb.cmse) {
515         return false;
516     }
517 
518     lo = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
519     hi = lo + int128_get64(n->cmb.mem.size);
520 
521     return addr >= lo && addr < hi;
522 }
523 
524 static inline void *nvme_addr_to_cmb(NvmeCtrl *n, hwaddr addr)
525 {
526     hwaddr base = n->params.legacy_cmb ? n->cmb.mem.addr : n->cmb.cba;
527     return &n->cmb.buf[addr - base];
528 }
529 
530 static bool nvme_addr_is_pmr(NvmeCtrl *n, hwaddr addr)
531 {
532     hwaddr hi;
533 
534     if (!n->pmr.cmse) {
535         return false;
536     }
537 
538     hi = n->pmr.cba + int128_get64(n->pmr.dev->mr.size);
539 
540     return addr >= n->pmr.cba && addr < hi;
541 }
542 
543 static inline void *nvme_addr_to_pmr(NvmeCtrl *n, hwaddr addr)
544 {
545     return memory_region_get_ram_ptr(&n->pmr.dev->mr) + (addr - n->pmr.cba);
546 }
547 
548 static inline bool nvme_addr_is_iomem(NvmeCtrl *n, hwaddr addr)
549 {
550     hwaddr hi, lo;
551 
552     /*
553      * The purpose of this check is to guard against invalid "local" access to
554      * the iomem (i.e. controller registers). Thus, we check against the range
555      * covered by the 'bar0' MemoryRegion since that is currently composed of
556      * two subregions (the NVMe "MBAR" and the MSI-X table/pba). Note, however,
557      * that if the device model is ever changed to allow the CMB to be located
558      * in BAR0 as well, then this must be changed.
559      */
560     lo = n->bar0.addr;
561     hi = lo + int128_get64(n->bar0.size);
562 
563     return addr >= lo && addr < hi;
564 }
565 
566 static int nvme_addr_read(NvmeCtrl *n, hwaddr addr, void *buf, int size)
567 {
568     hwaddr hi = addr + size - 1;
569     if (hi < addr) {
570         return 1;
571     }
572 
573     if (n->bar.cmbsz && nvme_addr_is_cmb(n, addr) && nvme_addr_is_cmb(n, hi)) {
574         memcpy(buf, nvme_addr_to_cmb(n, addr), size);
575         return 0;
576     }
577 
578     if (nvme_addr_is_pmr(n, addr) && nvme_addr_is_pmr(n, hi)) {
579         memcpy(buf, nvme_addr_to_pmr(n, addr), size);
580         return 0;
581     }
582 
583     return pci_dma_read(PCI_DEVICE(n), addr, buf, size);
584 }
585 
586 static int nvme_addr_write(NvmeCtrl *n, hwaddr addr, const void *buf, int size)
587 {
588     hwaddr hi = addr + size - 1;
589     if (hi < addr) {
590         return 1;
591     }
592 
593     if (n->bar.cmbsz && nvme_addr_is_cmb(n, addr) && nvme_addr_is_cmb(n, hi)) {
594         memcpy(nvme_addr_to_cmb(n, addr), buf, size);
595         return 0;
596     }
597 
598     if (nvme_addr_is_pmr(n, addr) && nvme_addr_is_pmr(n, hi)) {
599         memcpy(nvme_addr_to_pmr(n, addr), buf, size);
600         return 0;
601     }
602 
603     return pci_dma_write(PCI_DEVICE(n), addr, buf, size);
604 }
605 
606 static bool nvme_nsid_valid(NvmeCtrl *n, uint32_t nsid)
607 {
608     return nsid &&
609         (nsid == NVME_NSID_BROADCAST || nsid <= NVME_MAX_NAMESPACES);
610 }
611 
612 static int nvme_check_sqid(NvmeCtrl *n, uint16_t sqid)
613 {
614     return sqid < n->conf_ioqpairs + 1 && n->sq[sqid] != NULL ? 0 : -1;
615 }
616 
617 static int nvme_check_cqid(NvmeCtrl *n, uint16_t cqid)
618 {
619     return cqid < n->conf_ioqpairs + 1 && n->cq[cqid] != NULL ? 0 : -1;
620 }
621 
622 static void nvme_inc_cq_tail(NvmeCQueue *cq)
623 {
624     cq->tail++;
625     if (cq->tail >= cq->size) {
626         cq->tail = 0;
627         cq->phase = !cq->phase;
628     }
629 }
630 
631 static void nvme_inc_sq_head(NvmeSQueue *sq)
632 {
633     sq->head = (sq->head + 1) % sq->size;
634 }
635 
636 static uint8_t nvme_cq_full(NvmeCQueue *cq)
637 {
638     return (cq->tail + 1) % cq->size == cq->head;
639 }
640 
641 static uint8_t nvme_sq_empty(NvmeSQueue *sq)
642 {
643     return sq->head == sq->tail;
644 }
645 
646 static void nvme_irq_check(NvmeCtrl *n)
647 {
648     PCIDevice *pci = PCI_DEVICE(n);
649     uint32_t intms = ldl_le_p(&n->bar.intms);
650 
651     if (msix_enabled(pci)) {
652         return;
653     }
654     if (~intms & n->irq_status) {
655         pci_irq_assert(pci);
656     } else {
657         pci_irq_deassert(pci);
658     }
659 }
660 
661 static void nvme_irq_assert(NvmeCtrl *n, NvmeCQueue *cq)
662 {
663     PCIDevice *pci = PCI_DEVICE(n);
664 
665     if (cq->irq_enabled) {
666         if (msix_enabled(pci)) {
667             trace_pci_nvme_irq_msix(cq->vector);
668             msix_notify(pci, cq->vector);
669         } else {
670             trace_pci_nvme_irq_pin();
671             assert(cq->vector < 32);
672             n->irq_status |= 1 << cq->vector;
673             nvme_irq_check(n);
674         }
675     } else {
676         trace_pci_nvme_irq_masked();
677     }
678 }
679 
680 static void nvme_irq_deassert(NvmeCtrl *n, NvmeCQueue *cq)
681 {
682     if (cq->irq_enabled) {
683         if (msix_enabled(PCI_DEVICE(n))) {
684             return;
685         } else {
686             assert(cq->vector < 32);
687             if (!n->cq_pending) {
688                 n->irq_status &= ~(1 << cq->vector);
689             }
690             nvme_irq_check(n);
691         }
692     }
693 }
694 
695 static void nvme_req_clear(NvmeRequest *req)
696 {
697     req->ns = NULL;
698     req->opaque = NULL;
699     req->aiocb = NULL;
700     memset(&req->cqe, 0x0, sizeof(req->cqe));
701     req->status = NVME_SUCCESS;
702 }
703 
704 static inline void nvme_sg_init(NvmeCtrl *n, NvmeSg *sg, bool dma)
705 {
706     if (dma) {
707         pci_dma_sglist_init(&sg->qsg, PCI_DEVICE(n), 0);
708         sg->flags = NVME_SG_DMA;
709     } else {
710         qemu_iovec_init(&sg->iov, 0);
711     }
712 
713     sg->flags |= NVME_SG_ALLOC;
714 }
715 
716 static inline void nvme_sg_unmap(NvmeSg *sg)
717 {
718     if (!(sg->flags & NVME_SG_ALLOC)) {
719         return;
720     }
721 
722     if (sg->flags & NVME_SG_DMA) {
723         qemu_sglist_destroy(&sg->qsg);
724     } else {
725         qemu_iovec_destroy(&sg->iov);
726     }
727 
728     memset(sg, 0x0, sizeof(*sg));
729 }
730 
731 /*
732  * When metadata is transferred as extended LBAs, the DPTR mapped into `sg`
733  * holds both data and metadata. This function splits the data and metadata
734  * into two separate QSG/IOVs.
735  */
736 static void nvme_sg_split(NvmeSg *sg, NvmeNamespace *ns, NvmeSg *data,
737                           NvmeSg *mdata)
738 {
739     NvmeSg *dst = data;
740     uint32_t trans_len, count = ns->lbasz;
741     uint64_t offset = 0;
742     bool dma = sg->flags & NVME_SG_DMA;
743     size_t sge_len;
744     size_t sg_len = dma ? sg->qsg.size : sg->iov.size;
745     int sg_idx = 0;
746 
747     assert(sg->flags & NVME_SG_ALLOC);
748 
749     while (sg_len) {
750         sge_len = dma ? sg->qsg.sg[sg_idx].len : sg->iov.iov[sg_idx].iov_len;
751 
752         trans_len = MIN(sg_len, count);
753         trans_len = MIN(trans_len, sge_len - offset);
754 
755         if (dst) {
756             if (dma) {
757                 qemu_sglist_add(&dst->qsg, sg->qsg.sg[sg_idx].base + offset,
758                                 trans_len);
759             } else {
760                 qemu_iovec_add(&dst->iov,
761                                sg->iov.iov[sg_idx].iov_base + offset,
762                                trans_len);
763             }
764         }
765 
766         sg_len -= trans_len;
767         count -= trans_len;
768         offset += trans_len;
769 
770         if (count == 0) {
771             dst = (dst == data) ? mdata : data;
772             count = (dst == data) ? ns->lbasz : ns->lbaf.ms;
773         }
774 
775         if (sge_len == offset) {
776             offset = 0;
777             sg_idx++;
778         }
779     }
780 }
781 
782 static uint16_t nvme_map_addr_cmb(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
783                                   size_t len)
784 {
785     if (!len) {
786         return NVME_SUCCESS;
787     }
788 
789     trace_pci_nvme_map_addr_cmb(addr, len);
790 
791     if (!nvme_addr_is_cmb(n, addr) || !nvme_addr_is_cmb(n, addr + len - 1)) {
792         return NVME_DATA_TRAS_ERROR;
793     }
794 
795     qemu_iovec_add(iov, nvme_addr_to_cmb(n, addr), len);
796 
797     return NVME_SUCCESS;
798 }
799 
800 static uint16_t nvme_map_addr_pmr(NvmeCtrl *n, QEMUIOVector *iov, hwaddr addr,
801                                   size_t len)
802 {
803     if (!len) {
804         return NVME_SUCCESS;
805     }
806 
807     if (!nvme_addr_is_pmr(n, addr) || !nvme_addr_is_pmr(n, addr + len - 1)) {
808         return NVME_DATA_TRAS_ERROR;
809     }
810 
811     qemu_iovec_add(iov, nvme_addr_to_pmr(n, addr), len);
812 
813     return NVME_SUCCESS;
814 }
815 
816 static uint16_t nvme_map_addr(NvmeCtrl *n, NvmeSg *sg, hwaddr addr, size_t len)
817 {
818     bool cmb = false, pmr = false;
819 
820     if (!len) {
821         return NVME_SUCCESS;
822     }
823 
824     trace_pci_nvme_map_addr(addr, len);
825 
826     if (nvme_addr_is_iomem(n, addr)) {
827         return NVME_DATA_TRAS_ERROR;
828     }
829 
830     if (nvme_addr_is_cmb(n, addr)) {
831         cmb = true;
832     } else if (nvme_addr_is_pmr(n, addr)) {
833         pmr = true;
834     }
835 
836     if (cmb || pmr) {
837         if (sg->flags & NVME_SG_DMA) {
838             return NVME_INVALID_USE_OF_CMB | NVME_DNR;
839         }
840 
841         if (sg->iov.niov + 1 > IOV_MAX) {
842             goto max_mappings_exceeded;
843         }
844 
845         if (cmb) {
846             return nvme_map_addr_cmb(n, &sg->iov, addr, len);
847         } else {
848             return nvme_map_addr_pmr(n, &sg->iov, addr, len);
849         }
850     }
851 
852     if (!(sg->flags & NVME_SG_DMA)) {
853         return NVME_INVALID_USE_OF_CMB | NVME_DNR;
854     }
855 
856     if (sg->qsg.nsg + 1 > IOV_MAX) {
857         goto max_mappings_exceeded;
858     }
859 
860     qemu_sglist_add(&sg->qsg, addr, len);
861 
862     return NVME_SUCCESS;
863 
864 max_mappings_exceeded:
865     NVME_GUEST_ERR(pci_nvme_ub_too_many_mappings,
866                    "number of mappings exceed 1024");
867     return NVME_INTERNAL_DEV_ERROR | NVME_DNR;
868 }
869 
870 static inline bool nvme_addr_is_dma(NvmeCtrl *n, hwaddr addr)
871 {
872     return !(nvme_addr_is_cmb(n, addr) || nvme_addr_is_pmr(n, addr));
873 }
874 
875 static uint16_t nvme_map_prp(NvmeCtrl *n, NvmeSg *sg, uint64_t prp1,
876                              uint64_t prp2, uint32_t len)
877 {
878     hwaddr trans_len = n->page_size - (prp1 % n->page_size);
879     trans_len = MIN(len, trans_len);
880     int num_prps = (len >> n->page_bits) + 1;
881     uint16_t status;
882     int ret;
883 
884     trace_pci_nvme_map_prp(trans_len, len, prp1, prp2, num_prps);
885 
886     nvme_sg_init(n, sg, nvme_addr_is_dma(n, prp1));
887 
888     status = nvme_map_addr(n, sg, prp1, trans_len);
889     if (status) {
890         goto unmap;
891     }
892 
893     len -= trans_len;
894     if (len) {
895         if (len > n->page_size) {
896             g_autofree uint64_t *prp_list = g_new(uint64_t, n->max_prp_ents);
897             uint32_t nents, prp_trans;
898             int i = 0;
899 
900             /*
901              * The first PRP list entry, pointed to by PRP2 may contain offset.
902              * Hence, we need to calculate the number of entries in based on
903              * that offset.
904              */
905             nents = (n->page_size - (prp2 & (n->page_size - 1))) >> 3;
906             prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);
907             ret = nvme_addr_read(n, prp2, (void *)prp_list, prp_trans);
908             if (ret) {
909                 trace_pci_nvme_err_addr_read(prp2);
910                 status = NVME_DATA_TRAS_ERROR;
911                 goto unmap;
912             }
913             while (len != 0) {
914                 uint64_t prp_ent = le64_to_cpu(prp_list[i]);
915 
916                 if (i == nents - 1 && len > n->page_size) {
917                     if (unlikely(prp_ent & (n->page_size - 1))) {
918                         trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
919                         status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
920                         goto unmap;
921                     }
922 
923                     i = 0;
924                     nents = (len + n->page_size - 1) >> n->page_bits;
925                     nents = MIN(nents, n->max_prp_ents);
926                     prp_trans = nents * sizeof(uint64_t);
927                     ret = nvme_addr_read(n, prp_ent, (void *)prp_list,
928                                          prp_trans);
929                     if (ret) {
930                         trace_pci_nvme_err_addr_read(prp_ent);
931                         status = NVME_DATA_TRAS_ERROR;
932                         goto unmap;
933                     }
934                     prp_ent = le64_to_cpu(prp_list[i]);
935                 }
936 
937                 if (unlikely(prp_ent & (n->page_size - 1))) {
938                     trace_pci_nvme_err_invalid_prplist_ent(prp_ent);
939                     status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
940                     goto unmap;
941                 }
942 
943                 trans_len = MIN(len, n->page_size);
944                 status = nvme_map_addr(n, sg, prp_ent, trans_len);
945                 if (status) {
946                     goto unmap;
947                 }
948 
949                 len -= trans_len;
950                 i++;
951             }
952         } else {
953             if (unlikely(prp2 & (n->page_size - 1))) {
954                 trace_pci_nvme_err_invalid_prp2_align(prp2);
955                 status = NVME_INVALID_PRP_OFFSET | NVME_DNR;
956                 goto unmap;
957             }
958             status = nvme_map_addr(n, sg, prp2, len);
959             if (status) {
960                 goto unmap;
961             }
962         }
963     }
964 
965     return NVME_SUCCESS;
966 
967 unmap:
968     nvme_sg_unmap(sg);
969     return status;
970 }
971 
972 /*
973  * Map 'nsgld' data descriptors from 'segment'. The function will subtract the
974  * number of bytes mapped in len.
975  */
976 static uint16_t nvme_map_sgl_data(NvmeCtrl *n, NvmeSg *sg,
977                                   NvmeSglDescriptor *segment, uint64_t nsgld,
978                                   size_t *len, NvmeCmd *cmd)
979 {
980     dma_addr_t addr, trans_len;
981     uint32_t dlen;
982     uint16_t status;
983 
984     for (int i = 0; i < nsgld; i++) {
985         uint8_t type = NVME_SGL_TYPE(segment[i].type);
986 
987         switch (type) {
988         case NVME_SGL_DESCR_TYPE_DATA_BLOCK:
989             break;
990         case NVME_SGL_DESCR_TYPE_SEGMENT:
991         case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
992             return NVME_INVALID_NUM_SGL_DESCRS | NVME_DNR;
993         default:
994             return NVME_SGL_DESCR_TYPE_INVALID | NVME_DNR;
995         }
996 
997         dlen = le32_to_cpu(segment[i].len);
998 
999         if (!dlen) {
1000             continue;
1001         }
1002 
1003         if (*len == 0) {
1004             /*
1005              * All data has been mapped, but the SGL contains additional
1006              * segments and/or descriptors. The controller might accept
1007              * ignoring the rest of the SGL.
1008              */
1009             uint32_t sgls = le32_to_cpu(n->id_ctrl.sgls);
1010             if (sgls & NVME_CTRL_SGLS_EXCESS_LENGTH) {
1011                 break;
1012             }
1013 
1014             trace_pci_nvme_err_invalid_sgl_excess_length(dlen);
1015             return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1016         }
1017 
1018         trans_len = MIN(*len, dlen);
1019 
1020         addr = le64_to_cpu(segment[i].addr);
1021 
1022         if (UINT64_MAX - addr < dlen) {
1023             return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1024         }
1025 
1026         status = nvme_map_addr(n, sg, addr, trans_len);
1027         if (status) {
1028             return status;
1029         }
1030 
1031         *len -= trans_len;
1032     }
1033 
1034     return NVME_SUCCESS;
1035 }
1036 
1037 static uint16_t nvme_map_sgl(NvmeCtrl *n, NvmeSg *sg, NvmeSglDescriptor sgl,
1038                              size_t len, NvmeCmd *cmd)
1039 {
1040     /*
1041      * Read the segment in chunks of 256 descriptors (one 4k page) to avoid
1042      * dynamically allocating a potentially huge SGL. The spec allows the SGL
1043      * to be larger (as in number of bytes required to describe the SGL
1044      * descriptors and segment chain) than the command transfer size, so it is
1045      * not bounded by MDTS.
1046      */
1047 #define SEG_CHUNK_SIZE 256
1048 
1049     NvmeSglDescriptor segment[SEG_CHUNK_SIZE], *sgld, *last_sgld;
1050     uint64_t nsgld;
1051     uint32_t seg_len;
1052     uint16_t status;
1053     hwaddr addr;
1054     int ret;
1055 
1056     sgld = &sgl;
1057     addr = le64_to_cpu(sgl.addr);
1058 
1059     trace_pci_nvme_map_sgl(NVME_SGL_TYPE(sgl.type), len);
1060 
1061     nvme_sg_init(n, sg, nvme_addr_is_dma(n, addr));
1062 
1063     /*
1064      * If the entire transfer can be described with a single data block it can
1065      * be mapped directly.
1066      */
1067     if (NVME_SGL_TYPE(sgl.type) == NVME_SGL_DESCR_TYPE_DATA_BLOCK) {
1068         status = nvme_map_sgl_data(n, sg, sgld, 1, &len, cmd);
1069         if (status) {
1070             goto unmap;
1071         }
1072 
1073         goto out;
1074     }
1075 
1076     for (;;) {
1077         switch (NVME_SGL_TYPE(sgld->type)) {
1078         case NVME_SGL_DESCR_TYPE_SEGMENT:
1079         case NVME_SGL_DESCR_TYPE_LAST_SEGMENT:
1080             break;
1081         default:
1082             return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
1083         }
1084 
1085         seg_len = le32_to_cpu(sgld->len);
1086 
1087         /* check the length of the (Last) Segment descriptor */
1088         if (!seg_len || seg_len & 0xf) {
1089             return NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
1090         }
1091 
1092         if (UINT64_MAX - addr < seg_len) {
1093             return NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1094         }
1095 
1096         nsgld = seg_len / sizeof(NvmeSglDescriptor);
1097 
1098         while (nsgld > SEG_CHUNK_SIZE) {
1099             if (nvme_addr_read(n, addr, segment, sizeof(segment))) {
1100                 trace_pci_nvme_err_addr_read(addr);
1101                 status = NVME_DATA_TRAS_ERROR;
1102                 goto unmap;
1103             }
1104 
1105             status = nvme_map_sgl_data(n, sg, segment, SEG_CHUNK_SIZE,
1106                                        &len, cmd);
1107             if (status) {
1108                 goto unmap;
1109             }
1110 
1111             nsgld -= SEG_CHUNK_SIZE;
1112             addr += SEG_CHUNK_SIZE * sizeof(NvmeSglDescriptor);
1113         }
1114 
1115         ret = nvme_addr_read(n, addr, segment, nsgld *
1116                              sizeof(NvmeSglDescriptor));
1117         if (ret) {
1118             trace_pci_nvme_err_addr_read(addr);
1119             status = NVME_DATA_TRAS_ERROR;
1120             goto unmap;
1121         }
1122 
1123         last_sgld = &segment[nsgld - 1];
1124 
1125         /*
1126          * If the segment ends with a Data Block, then we are done.
1127          */
1128         if (NVME_SGL_TYPE(last_sgld->type) == NVME_SGL_DESCR_TYPE_DATA_BLOCK) {
1129             status = nvme_map_sgl_data(n, sg, segment, nsgld, &len, cmd);
1130             if (status) {
1131                 goto unmap;
1132             }
1133 
1134             goto out;
1135         }
1136 
1137         /*
1138          * If the last descriptor was not a Data Block, then the current
1139          * segment must not be a Last Segment.
1140          */
1141         if (NVME_SGL_TYPE(sgld->type) == NVME_SGL_DESCR_TYPE_LAST_SEGMENT) {
1142             status = NVME_INVALID_SGL_SEG_DESCR | NVME_DNR;
1143             goto unmap;
1144         }
1145 
1146         sgld = last_sgld;
1147         addr = le64_to_cpu(sgld->addr);
1148 
1149         /*
1150          * Do not map the last descriptor; it will be a Segment or Last Segment
1151          * descriptor and is handled by the next iteration.
1152          */
1153         status = nvme_map_sgl_data(n, sg, segment, nsgld - 1, &len, cmd);
1154         if (status) {
1155             goto unmap;
1156         }
1157     }
1158 
1159 out:
1160     /* if there is any residual left in len, the SGL was too short */
1161     if (len) {
1162         status = NVME_DATA_SGL_LEN_INVALID | NVME_DNR;
1163         goto unmap;
1164     }
1165 
1166     return NVME_SUCCESS;
1167 
1168 unmap:
1169     nvme_sg_unmap(sg);
1170     return status;
1171 }
1172 
1173 uint16_t nvme_map_dptr(NvmeCtrl *n, NvmeSg *sg, size_t len,
1174                        NvmeCmd *cmd)
1175 {
1176     uint64_t prp1, prp2;
1177 
1178     switch (NVME_CMD_FLAGS_PSDT(cmd->flags)) {
1179     case NVME_PSDT_PRP:
1180         prp1 = le64_to_cpu(cmd->dptr.prp1);
1181         prp2 = le64_to_cpu(cmd->dptr.prp2);
1182 
1183         return nvme_map_prp(n, sg, prp1, prp2, len);
1184     case NVME_PSDT_SGL_MPTR_CONTIGUOUS:
1185     case NVME_PSDT_SGL_MPTR_SGL:
1186         return nvme_map_sgl(n, sg, cmd->dptr.sgl, len, cmd);
1187     default:
1188         return NVME_INVALID_FIELD;
1189     }
1190 }
1191 
1192 static uint16_t nvme_map_mptr(NvmeCtrl *n, NvmeSg *sg, size_t len,
1193                               NvmeCmd *cmd)
1194 {
1195     int psdt = NVME_CMD_FLAGS_PSDT(cmd->flags);
1196     hwaddr mptr = le64_to_cpu(cmd->mptr);
1197     uint16_t status;
1198 
1199     if (psdt == NVME_PSDT_SGL_MPTR_SGL) {
1200         NvmeSglDescriptor sgl;
1201 
1202         if (nvme_addr_read(n, mptr, &sgl, sizeof(sgl))) {
1203             return NVME_DATA_TRAS_ERROR;
1204         }
1205 
1206         status = nvme_map_sgl(n, sg, sgl, len, cmd);
1207         if (status && (status & 0x7ff) == NVME_DATA_SGL_LEN_INVALID) {
1208             status = NVME_MD_SGL_LEN_INVALID | NVME_DNR;
1209         }
1210 
1211         return status;
1212     }
1213 
1214     nvme_sg_init(n, sg, nvme_addr_is_dma(n, mptr));
1215     status = nvme_map_addr(n, sg, mptr, len);
1216     if (status) {
1217         nvme_sg_unmap(sg);
1218     }
1219 
1220     return status;
1221 }
1222 
1223 static uint16_t nvme_map_data(NvmeCtrl *n, uint32_t nlb, NvmeRequest *req)
1224 {
1225     NvmeNamespace *ns = req->ns;
1226     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1227     bool pi = !!NVME_ID_NS_DPS_TYPE(ns->id_ns.dps);
1228     bool pract = !!(le16_to_cpu(rw->control) & NVME_RW_PRINFO_PRACT);
1229     size_t len = nvme_l2b(ns, nlb);
1230     uint16_t status;
1231 
1232     if (nvme_ns_ext(ns) &&
1233         !(pi && pract && ns->lbaf.ms == nvme_pi_tuple_size(ns))) {
1234         NvmeSg sg;
1235 
1236         len += nvme_m2b(ns, nlb);
1237 
1238         status = nvme_map_dptr(n, &sg, len, &req->cmd);
1239         if (status) {
1240             return status;
1241         }
1242 
1243         nvme_sg_init(n, &req->sg, sg.flags & NVME_SG_DMA);
1244         nvme_sg_split(&sg, ns, &req->sg, NULL);
1245         nvme_sg_unmap(&sg);
1246 
1247         return NVME_SUCCESS;
1248     }
1249 
1250     return nvme_map_dptr(n, &req->sg, len, &req->cmd);
1251 }
1252 
1253 static uint16_t nvme_map_mdata(NvmeCtrl *n, uint32_t nlb, NvmeRequest *req)
1254 {
1255     NvmeNamespace *ns = req->ns;
1256     size_t len = nvme_m2b(ns, nlb);
1257     uint16_t status;
1258 
1259     if (nvme_ns_ext(ns)) {
1260         NvmeSg sg;
1261 
1262         len += nvme_l2b(ns, nlb);
1263 
1264         status = nvme_map_dptr(n, &sg, len, &req->cmd);
1265         if (status) {
1266             return status;
1267         }
1268 
1269         nvme_sg_init(n, &req->sg, sg.flags & NVME_SG_DMA);
1270         nvme_sg_split(&sg, ns, NULL, &req->sg);
1271         nvme_sg_unmap(&sg);
1272 
1273         return NVME_SUCCESS;
1274     }
1275 
1276     return nvme_map_mptr(n, &req->sg, len, &req->cmd);
1277 }
1278 
1279 static uint16_t nvme_tx_interleaved(NvmeCtrl *n, NvmeSg *sg, uint8_t *ptr,
1280                                     uint32_t len, uint32_t bytes,
1281                                     int32_t skip_bytes, int64_t offset,
1282                                     NvmeTxDirection dir)
1283 {
1284     hwaddr addr;
1285     uint32_t trans_len, count = bytes;
1286     bool dma = sg->flags & NVME_SG_DMA;
1287     int64_t sge_len;
1288     int sg_idx = 0;
1289     int ret;
1290 
1291     assert(sg->flags & NVME_SG_ALLOC);
1292 
1293     while (len) {
1294         sge_len = dma ? sg->qsg.sg[sg_idx].len : sg->iov.iov[sg_idx].iov_len;
1295 
1296         if (sge_len - offset < 0) {
1297             offset -= sge_len;
1298             sg_idx++;
1299             continue;
1300         }
1301 
1302         if (sge_len == offset) {
1303             offset = 0;
1304             sg_idx++;
1305             continue;
1306         }
1307 
1308         trans_len = MIN(len, count);
1309         trans_len = MIN(trans_len, sge_len - offset);
1310 
1311         if (dma) {
1312             addr = sg->qsg.sg[sg_idx].base + offset;
1313         } else {
1314             addr = (hwaddr)(uintptr_t)sg->iov.iov[sg_idx].iov_base + offset;
1315         }
1316 
1317         if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1318             ret = nvme_addr_read(n, addr, ptr, trans_len);
1319         } else {
1320             ret = nvme_addr_write(n, addr, ptr, trans_len);
1321         }
1322 
1323         if (ret) {
1324             return NVME_DATA_TRAS_ERROR;
1325         }
1326 
1327         ptr += trans_len;
1328         len -= trans_len;
1329         count -= trans_len;
1330         offset += trans_len;
1331 
1332         if (count == 0) {
1333             count = bytes;
1334             offset += skip_bytes;
1335         }
1336     }
1337 
1338     return NVME_SUCCESS;
1339 }
1340 
1341 static uint16_t nvme_tx(NvmeCtrl *n, NvmeSg *sg, void *ptr, uint32_t len,
1342                         NvmeTxDirection dir)
1343 {
1344     assert(sg->flags & NVME_SG_ALLOC);
1345 
1346     if (sg->flags & NVME_SG_DMA) {
1347         const MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
1348         dma_addr_t residual;
1349 
1350         if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1351             dma_buf_write(ptr, len, &residual, &sg->qsg, attrs);
1352         } else {
1353             dma_buf_read(ptr, len, &residual, &sg->qsg, attrs);
1354         }
1355 
1356         if (unlikely(residual)) {
1357             trace_pci_nvme_err_invalid_dma();
1358             return NVME_INVALID_FIELD | NVME_DNR;
1359         }
1360     } else {
1361         size_t bytes;
1362 
1363         if (dir == NVME_TX_DIRECTION_TO_DEVICE) {
1364             bytes = qemu_iovec_to_buf(&sg->iov, 0, ptr, len);
1365         } else {
1366             bytes = qemu_iovec_from_buf(&sg->iov, 0, ptr, len);
1367         }
1368 
1369         if (unlikely(bytes != len)) {
1370             trace_pci_nvme_err_invalid_dma();
1371             return NVME_INVALID_FIELD | NVME_DNR;
1372         }
1373     }
1374 
1375     return NVME_SUCCESS;
1376 }
1377 
1378 static inline uint16_t nvme_c2h(NvmeCtrl *n, void *ptr, uint32_t len,
1379                                 NvmeRequest *req)
1380 {
1381     uint16_t status;
1382 
1383     status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
1384     if (status) {
1385         return status;
1386     }
1387 
1388     return nvme_tx(n, &req->sg, ptr, len, NVME_TX_DIRECTION_FROM_DEVICE);
1389 }
1390 
1391 static inline uint16_t nvme_h2c(NvmeCtrl *n, void *ptr, uint32_t len,
1392                                 NvmeRequest *req)
1393 {
1394     uint16_t status;
1395 
1396     status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
1397     if (status) {
1398         return status;
1399     }
1400 
1401     return nvme_tx(n, &req->sg, ptr, len, NVME_TX_DIRECTION_TO_DEVICE);
1402 }
1403 
1404 uint16_t nvme_bounce_data(NvmeCtrl *n, void *ptr, uint32_t len,
1405                           NvmeTxDirection dir, NvmeRequest *req)
1406 {
1407     NvmeNamespace *ns = req->ns;
1408     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
1409     bool pi = !!NVME_ID_NS_DPS_TYPE(ns->id_ns.dps);
1410     bool pract = !!(le16_to_cpu(rw->control) & NVME_RW_PRINFO_PRACT);
1411 
1412     if (nvme_ns_ext(ns) &&
1413         !(pi && pract && ns->lbaf.ms == nvme_pi_tuple_size(ns))) {
1414         return nvme_tx_interleaved(n, &req->sg, ptr, len, ns->lbasz,
1415                                    ns->lbaf.ms, 0, dir);
1416     }
1417 
1418     return nvme_tx(n, &req->sg, ptr, len, dir);
1419 }
1420 
1421 uint16_t nvme_bounce_mdata(NvmeCtrl *n, void *ptr, uint32_t len,
1422                            NvmeTxDirection dir, NvmeRequest *req)
1423 {
1424     NvmeNamespace *ns = req->ns;
1425     uint16_t status;
1426 
1427     if (nvme_ns_ext(ns)) {
1428         return nvme_tx_interleaved(n, &req->sg, ptr, len, ns->lbaf.ms,
1429                                    ns->lbasz, ns->lbasz, dir);
1430     }
1431 
1432     nvme_sg_unmap(&req->sg);
1433 
1434     status = nvme_map_mptr(n, &req->sg, len, &req->cmd);
1435     if (status) {
1436         return status;
1437     }
1438 
1439     return nvme_tx(n, &req->sg, ptr, len, dir);
1440 }
1441 
1442 static inline void nvme_blk_read(BlockBackend *blk, int64_t offset,
1443                                  uint32_t align, BlockCompletionFunc *cb,
1444                                  NvmeRequest *req)
1445 {
1446     assert(req->sg.flags & NVME_SG_ALLOC);
1447 
1448     if (req->sg.flags & NVME_SG_DMA) {
1449         req->aiocb = dma_blk_read(blk, &req->sg.qsg, offset, align, cb, req);
1450     } else {
1451         req->aiocb = blk_aio_preadv(blk, offset, &req->sg.iov, 0, cb, req);
1452     }
1453 }
1454 
1455 static inline void nvme_blk_write(BlockBackend *blk, int64_t offset,
1456                                   uint32_t align, BlockCompletionFunc *cb,
1457                                   NvmeRequest *req)
1458 {
1459     assert(req->sg.flags & NVME_SG_ALLOC);
1460 
1461     if (req->sg.flags & NVME_SG_DMA) {
1462         req->aiocb = dma_blk_write(blk, &req->sg.qsg, offset, align, cb, req);
1463     } else {
1464         req->aiocb = blk_aio_pwritev(blk, offset, &req->sg.iov, 0, cb, req);
1465     }
1466 }
1467 
1468 static void nvme_update_cq_eventidx(const NvmeCQueue *cq)
1469 {
1470     trace_pci_nvme_update_cq_eventidx(cq->cqid, cq->head);
1471 
1472     stl_le_pci_dma(PCI_DEVICE(cq->ctrl), cq->ei_addr, cq->head,
1473                    MEMTXATTRS_UNSPECIFIED);
1474 }
1475 
1476 static void nvme_update_cq_head(NvmeCQueue *cq)
1477 {
1478     ldl_le_pci_dma(PCI_DEVICE(cq->ctrl), cq->db_addr, &cq->head,
1479                    MEMTXATTRS_UNSPECIFIED);
1480 
1481     trace_pci_nvme_update_cq_head(cq->cqid, cq->head);
1482 }
1483 
1484 static void nvme_post_cqes(void *opaque)
1485 {
1486     NvmeCQueue *cq = opaque;
1487     NvmeCtrl *n = cq->ctrl;
1488     NvmeRequest *req, *next;
1489     bool pending = cq->head != cq->tail;
1490     int ret;
1491 
1492     QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {
1493         NvmeSQueue *sq;
1494         hwaddr addr;
1495 
1496         if (n->dbbuf_enabled) {
1497             nvme_update_cq_eventidx(cq);
1498             nvme_update_cq_head(cq);
1499         }
1500 
1501         if (nvme_cq_full(cq)) {
1502             break;
1503         }
1504 
1505         sq = req->sq;
1506         req->cqe.status = cpu_to_le16((req->status << 1) | cq->phase);
1507         req->cqe.sq_id = cpu_to_le16(sq->sqid);
1508         req->cqe.sq_head = cpu_to_le16(sq->head);
1509         addr = cq->dma_addr + (cq->tail << NVME_CQES);
1510         ret = pci_dma_write(PCI_DEVICE(n), addr, (void *)&req->cqe,
1511                             sizeof(req->cqe));
1512         if (ret) {
1513             trace_pci_nvme_err_addr_write(addr);
1514             trace_pci_nvme_err_cfs();
1515             stl_le_p(&n->bar.csts, NVME_CSTS_FAILED);
1516             break;
1517         }
1518         QTAILQ_REMOVE(&cq->req_list, req, entry);
1519         nvme_inc_cq_tail(cq);
1520         nvme_sg_unmap(&req->sg);
1521         QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);
1522     }
1523     if (cq->tail != cq->head) {
1524         if (cq->irq_enabled && !pending) {
1525             n->cq_pending++;
1526         }
1527 
1528         nvme_irq_assert(n, cq);
1529     }
1530 }
1531 
1532 static void nvme_enqueue_req_completion(NvmeCQueue *cq, NvmeRequest *req)
1533 {
1534     assert(cq->cqid == req->sq->cqid);
1535     trace_pci_nvme_enqueue_req_completion(nvme_cid(req), cq->cqid,
1536                                           le32_to_cpu(req->cqe.result),
1537                                           le32_to_cpu(req->cqe.dw1),
1538                                           req->status);
1539 
1540     if (req->status) {
1541         trace_pci_nvme_err_req_status(nvme_cid(req), nvme_nsid(req->ns),
1542                                       req->status, req->cmd.opcode);
1543     }
1544 
1545     QTAILQ_REMOVE(&req->sq->out_req_list, req, entry);
1546     QTAILQ_INSERT_TAIL(&cq->req_list, req, entry);
1547 
1548     qemu_bh_schedule(cq->bh);
1549 }
1550 
1551 static void nvme_process_aers(void *opaque)
1552 {
1553     NvmeCtrl *n = opaque;
1554     NvmeAsyncEvent *event, *next;
1555 
1556     trace_pci_nvme_process_aers(n->aer_queued);
1557 
1558     QTAILQ_FOREACH_SAFE(event, &n->aer_queue, entry, next) {
1559         NvmeRequest *req;
1560         NvmeAerResult *result;
1561 
1562         /* can't post cqe if there is nothing to complete */
1563         if (!n->outstanding_aers) {
1564             trace_pci_nvme_no_outstanding_aers();
1565             break;
1566         }
1567 
1568         /* ignore if masked (cqe posted, but event not cleared) */
1569         if (n->aer_mask & (1 << event->result.event_type)) {
1570             trace_pci_nvme_aer_masked(event->result.event_type, n->aer_mask);
1571             continue;
1572         }
1573 
1574         QTAILQ_REMOVE(&n->aer_queue, event, entry);
1575         n->aer_queued--;
1576 
1577         n->aer_mask |= 1 << event->result.event_type;
1578         n->outstanding_aers--;
1579 
1580         req = n->aer_reqs[n->outstanding_aers];
1581 
1582         result = (NvmeAerResult *) &req->cqe.result;
1583         result->event_type = event->result.event_type;
1584         result->event_info = event->result.event_info;
1585         result->log_page = event->result.log_page;
1586         g_free(event);
1587 
1588         trace_pci_nvme_aer_post_cqe(result->event_type, result->event_info,
1589                                     result->log_page);
1590 
1591         nvme_enqueue_req_completion(&n->admin_cq, req);
1592     }
1593 }
1594 
1595 static void nvme_enqueue_event(NvmeCtrl *n, uint8_t event_type,
1596                                uint8_t event_info, uint8_t log_page)
1597 {
1598     NvmeAsyncEvent *event;
1599 
1600     trace_pci_nvme_enqueue_event(event_type, event_info, log_page);
1601 
1602     if (n->aer_queued == n->params.aer_max_queued) {
1603         trace_pci_nvme_enqueue_event_noqueue(n->aer_queued);
1604         return;
1605     }
1606 
1607     event = g_new(NvmeAsyncEvent, 1);
1608     event->result = (NvmeAerResult) {
1609         .event_type = event_type,
1610         .event_info = event_info,
1611         .log_page   = log_page,
1612     };
1613 
1614     QTAILQ_INSERT_TAIL(&n->aer_queue, event, entry);
1615     n->aer_queued++;
1616 
1617     nvme_process_aers(n);
1618 }
1619 
1620 static void nvme_smart_event(NvmeCtrl *n, uint8_t event)
1621 {
1622     uint8_t aer_info;
1623 
1624     /* Ref SPEC <Asynchronous Event Information 0x2013 SMART / Health Status> */
1625     if (!(NVME_AEC_SMART(n->features.async_config) & event)) {
1626         return;
1627     }
1628 
1629     switch (event) {
1630     case NVME_SMART_SPARE:
1631         aer_info = NVME_AER_INFO_SMART_SPARE_THRESH;
1632         break;
1633     case NVME_SMART_TEMPERATURE:
1634         aer_info = NVME_AER_INFO_SMART_TEMP_THRESH;
1635         break;
1636     case NVME_SMART_RELIABILITY:
1637     case NVME_SMART_MEDIA_READ_ONLY:
1638     case NVME_SMART_FAILED_VOLATILE_MEDIA:
1639     case NVME_SMART_PMR_UNRELIABLE:
1640         aer_info = NVME_AER_INFO_SMART_RELIABILITY;
1641         break;
1642     default:
1643         return;
1644     }
1645 
1646     nvme_enqueue_event(n, NVME_AER_TYPE_SMART, aer_info, NVME_LOG_SMART_INFO);
1647 }
1648 
1649 static void nvme_clear_events(NvmeCtrl *n, uint8_t event_type)
1650 {
1651     n->aer_mask &= ~(1 << event_type);
1652     if (!QTAILQ_EMPTY(&n->aer_queue)) {
1653         nvme_process_aers(n);
1654     }
1655 }
1656 
1657 static inline uint16_t nvme_check_mdts(NvmeCtrl *n, size_t len)
1658 {
1659     uint8_t mdts = n->params.mdts;
1660 
1661     if (mdts && len > n->page_size << mdts) {
1662         trace_pci_nvme_err_mdts(len);
1663         return NVME_INVALID_FIELD | NVME_DNR;
1664     }
1665 
1666     return NVME_SUCCESS;
1667 }
1668 
1669 static inline uint16_t nvme_check_bounds(NvmeNamespace *ns, uint64_t slba,
1670                                          uint32_t nlb)
1671 {
1672     uint64_t nsze = le64_to_cpu(ns->id_ns.nsze);
1673 
1674     if (unlikely(UINT64_MAX - slba < nlb || slba + nlb > nsze)) {
1675         trace_pci_nvme_err_invalid_lba_range(slba, nlb, nsze);
1676         return NVME_LBA_RANGE | NVME_DNR;
1677     }
1678 
1679     return NVME_SUCCESS;
1680 }
1681 
1682 static int nvme_block_status_all(NvmeNamespace *ns, uint64_t slba,
1683                                  uint32_t nlb, int flags)
1684 {
1685     BlockDriverState *bs = blk_bs(ns->blkconf.blk);
1686 
1687     int64_t pnum = 0, bytes = nvme_l2b(ns, nlb);
1688     int64_t offset = nvme_l2b(ns, slba);
1689     int ret;
1690 
1691     /*
1692      * `pnum` holds the number of bytes after offset that shares the same
1693      * allocation status as the byte at offset. If `pnum` is different from
1694      * `bytes`, we should check the allocation status of the next range and
1695      * continue this until all bytes have been checked.
1696      */
1697     do {
1698         bytes -= pnum;
1699 
1700         ret = bdrv_block_status(bs, offset, bytes, &pnum, NULL, NULL);
1701         if (ret < 0) {
1702             return ret;
1703         }
1704 
1705 
1706         trace_pci_nvme_block_status(offset, bytes, pnum, ret,
1707                                     !!(ret & BDRV_BLOCK_ZERO));
1708 
1709         if (!(ret & flags)) {
1710             return 1;
1711         }
1712 
1713         offset += pnum;
1714     } while (pnum != bytes);
1715 
1716     return 0;
1717 }
1718 
1719 static uint16_t nvme_check_dulbe(NvmeNamespace *ns, uint64_t slba,
1720                                  uint32_t nlb)
1721 {
1722     int ret;
1723     Error *err = NULL;
1724 
1725     ret = nvme_block_status_all(ns, slba, nlb, BDRV_BLOCK_DATA);
1726     if (ret) {
1727         if (ret < 0) {
1728             error_setg_errno(&err, -ret, "unable to get block status");
1729             error_report_err(err);
1730 
1731             return NVME_INTERNAL_DEV_ERROR;
1732         }
1733 
1734         return NVME_DULB;
1735     }
1736 
1737     return NVME_SUCCESS;
1738 }
1739 
1740 static void nvme_aio_err(NvmeRequest *req, int ret)
1741 {
1742     uint16_t status = NVME_SUCCESS;
1743     Error *local_err = NULL;
1744 
1745     switch (req->cmd.opcode) {
1746     case NVME_CMD_READ:
1747         status = NVME_UNRECOVERED_READ;
1748         break;
1749     case NVME_CMD_FLUSH:
1750     case NVME_CMD_WRITE:
1751     case NVME_CMD_WRITE_ZEROES:
1752     case NVME_CMD_ZONE_APPEND:
1753     case NVME_CMD_COPY:
1754         status = NVME_WRITE_FAULT;
1755         break;
1756     default:
1757         status = NVME_INTERNAL_DEV_ERROR;
1758         break;
1759     }
1760 
1761     trace_pci_nvme_err_aio(nvme_cid(req), strerror(-ret), status);
1762 
1763     error_setg_errno(&local_err, -ret, "aio failed");
1764     error_report_err(local_err);
1765 
1766     /*
1767      * Set the command status code to the first encountered error but allow a
1768      * subsequent Internal Device Error to trump it.
1769      */
1770     if (req->status && status != NVME_INTERNAL_DEV_ERROR) {
1771         return;
1772     }
1773 
1774     req->status = status;
1775 }
1776 
1777 static inline uint32_t nvme_zone_idx(NvmeNamespace *ns, uint64_t slba)
1778 {
1779     return ns->zone_size_log2 > 0 ? slba >> ns->zone_size_log2 :
1780                                     slba / ns->zone_size;
1781 }
1782 
1783 static inline NvmeZone *nvme_get_zone_by_slba(NvmeNamespace *ns, uint64_t slba)
1784 {
1785     uint32_t zone_idx = nvme_zone_idx(ns, slba);
1786 
1787     if (zone_idx >= ns->num_zones) {
1788         return NULL;
1789     }
1790 
1791     return &ns->zone_array[zone_idx];
1792 }
1793 
1794 static uint16_t nvme_check_zone_state_for_write(NvmeZone *zone)
1795 {
1796     uint64_t zslba = zone->d.zslba;
1797 
1798     switch (nvme_get_zone_state(zone)) {
1799     case NVME_ZONE_STATE_EMPTY:
1800     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1801     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1802     case NVME_ZONE_STATE_CLOSED:
1803         return NVME_SUCCESS;
1804     case NVME_ZONE_STATE_FULL:
1805         trace_pci_nvme_err_zone_is_full(zslba);
1806         return NVME_ZONE_FULL;
1807     case NVME_ZONE_STATE_OFFLINE:
1808         trace_pci_nvme_err_zone_is_offline(zslba);
1809         return NVME_ZONE_OFFLINE;
1810     case NVME_ZONE_STATE_READ_ONLY:
1811         trace_pci_nvme_err_zone_is_read_only(zslba);
1812         return NVME_ZONE_READ_ONLY;
1813     default:
1814         assert(false);
1815     }
1816 
1817     return NVME_INTERNAL_DEV_ERROR;
1818 }
1819 
1820 static uint16_t nvme_check_zone_write(NvmeNamespace *ns, NvmeZone *zone,
1821                                       uint64_t slba, uint32_t nlb)
1822 {
1823     uint64_t zcap = nvme_zone_wr_boundary(zone);
1824     uint16_t status;
1825 
1826     status = nvme_check_zone_state_for_write(zone);
1827     if (status) {
1828         return status;
1829     }
1830 
1831     if (zone->d.za & NVME_ZA_ZRWA_VALID) {
1832         uint64_t ezrwa = zone->w_ptr + 2 * ns->zns.zrwas;
1833 
1834         if (slba < zone->w_ptr || slba + nlb > ezrwa) {
1835             trace_pci_nvme_err_zone_invalid_write(slba, zone->w_ptr);
1836             return NVME_ZONE_INVALID_WRITE;
1837         }
1838     } else {
1839         if (unlikely(slba != zone->w_ptr)) {
1840             trace_pci_nvme_err_write_not_at_wp(slba, zone->d.zslba,
1841                                                zone->w_ptr);
1842             return NVME_ZONE_INVALID_WRITE;
1843         }
1844     }
1845 
1846     if (unlikely((slba + nlb) > zcap)) {
1847         trace_pci_nvme_err_zone_boundary(slba, nlb, zcap);
1848         return NVME_ZONE_BOUNDARY_ERROR;
1849     }
1850 
1851     return NVME_SUCCESS;
1852 }
1853 
1854 static uint16_t nvme_check_zone_state_for_read(NvmeZone *zone)
1855 {
1856     switch (nvme_get_zone_state(zone)) {
1857     case NVME_ZONE_STATE_EMPTY:
1858     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1859     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1860     case NVME_ZONE_STATE_FULL:
1861     case NVME_ZONE_STATE_CLOSED:
1862     case NVME_ZONE_STATE_READ_ONLY:
1863         return NVME_SUCCESS;
1864     case NVME_ZONE_STATE_OFFLINE:
1865         trace_pci_nvme_err_zone_is_offline(zone->d.zslba);
1866         return NVME_ZONE_OFFLINE;
1867     default:
1868         assert(false);
1869     }
1870 
1871     return NVME_INTERNAL_DEV_ERROR;
1872 }
1873 
1874 static uint16_t nvme_check_zone_read(NvmeNamespace *ns, uint64_t slba,
1875                                      uint32_t nlb)
1876 {
1877     NvmeZone *zone;
1878     uint64_t bndry, end;
1879     uint16_t status;
1880 
1881     zone = nvme_get_zone_by_slba(ns, slba);
1882     assert(zone);
1883 
1884     bndry = nvme_zone_rd_boundary(ns, zone);
1885     end = slba + nlb;
1886 
1887     status = nvme_check_zone_state_for_read(zone);
1888     if (status) {
1889         ;
1890     } else if (unlikely(end > bndry)) {
1891         if (!ns->params.cross_zone_read) {
1892             status = NVME_ZONE_BOUNDARY_ERROR;
1893         } else {
1894             /*
1895              * Read across zone boundary - check that all subsequent
1896              * zones that are being read have an appropriate state.
1897              */
1898             do {
1899                 zone++;
1900                 status = nvme_check_zone_state_for_read(zone);
1901                 if (status) {
1902                     break;
1903                 }
1904             } while (end > nvme_zone_rd_boundary(ns, zone));
1905         }
1906     }
1907 
1908     return status;
1909 }
1910 
1911 static uint16_t nvme_zrm_finish(NvmeNamespace *ns, NvmeZone *zone)
1912 {
1913     switch (nvme_get_zone_state(zone)) {
1914     case NVME_ZONE_STATE_FULL:
1915         return NVME_SUCCESS;
1916 
1917     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1918     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1919         nvme_aor_dec_open(ns);
1920         /* fallthrough */
1921     case NVME_ZONE_STATE_CLOSED:
1922         nvme_aor_dec_active(ns);
1923 
1924         if (zone->d.za & NVME_ZA_ZRWA_VALID) {
1925             zone->d.za &= ~NVME_ZA_ZRWA_VALID;
1926             if (ns->params.numzrwa) {
1927                 ns->zns.numzrwa++;
1928             }
1929         }
1930 
1931         /* fallthrough */
1932     case NVME_ZONE_STATE_EMPTY:
1933         nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_FULL);
1934         return NVME_SUCCESS;
1935 
1936     default:
1937         return NVME_ZONE_INVAL_TRANSITION;
1938     }
1939 }
1940 
1941 static uint16_t nvme_zrm_close(NvmeNamespace *ns, NvmeZone *zone)
1942 {
1943     switch (nvme_get_zone_state(zone)) {
1944     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1945     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1946         nvme_aor_dec_open(ns);
1947         nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
1948         /* fall through */
1949     case NVME_ZONE_STATE_CLOSED:
1950         return NVME_SUCCESS;
1951 
1952     default:
1953         return NVME_ZONE_INVAL_TRANSITION;
1954     }
1955 }
1956 
1957 static uint16_t nvme_zrm_reset(NvmeNamespace *ns, NvmeZone *zone)
1958 {
1959     switch (nvme_get_zone_state(zone)) {
1960     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
1961     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
1962         nvme_aor_dec_open(ns);
1963         /* fallthrough */
1964     case NVME_ZONE_STATE_CLOSED:
1965         nvme_aor_dec_active(ns);
1966 
1967         if (zone->d.za & NVME_ZA_ZRWA_VALID) {
1968             if (ns->params.numzrwa) {
1969                 ns->zns.numzrwa++;
1970             }
1971         }
1972 
1973         /* fallthrough */
1974     case NVME_ZONE_STATE_FULL:
1975         zone->w_ptr = zone->d.zslba;
1976         zone->d.wp = zone->w_ptr;
1977         nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EMPTY);
1978         /* fallthrough */
1979     case NVME_ZONE_STATE_EMPTY:
1980         return NVME_SUCCESS;
1981 
1982     default:
1983         return NVME_ZONE_INVAL_TRANSITION;
1984     }
1985 }
1986 
1987 static void nvme_zrm_auto_transition_zone(NvmeNamespace *ns)
1988 {
1989     NvmeZone *zone;
1990 
1991     if (ns->params.max_open_zones &&
1992         ns->nr_open_zones == ns->params.max_open_zones) {
1993         zone = QTAILQ_FIRST(&ns->imp_open_zones);
1994         if (zone) {
1995             /*
1996              * Automatically close this implicitly open zone.
1997              */
1998             QTAILQ_REMOVE(&ns->imp_open_zones, zone, entry);
1999             nvme_zrm_close(ns, zone);
2000         }
2001     }
2002 }
2003 
2004 enum {
2005     NVME_ZRM_AUTO = 1 << 0,
2006     NVME_ZRM_ZRWA = 1 << 1,
2007 };
2008 
2009 static uint16_t nvme_zrm_open_flags(NvmeCtrl *n, NvmeNamespace *ns,
2010                                     NvmeZone *zone, int flags)
2011 {
2012     int act = 0;
2013     uint16_t status;
2014 
2015     switch (nvme_get_zone_state(zone)) {
2016     case NVME_ZONE_STATE_EMPTY:
2017         act = 1;
2018 
2019         /* fallthrough */
2020 
2021     case NVME_ZONE_STATE_CLOSED:
2022         if (n->params.auto_transition_zones) {
2023             nvme_zrm_auto_transition_zone(ns);
2024         }
2025         status = nvme_zns_check_resources(ns, act, 1,
2026                                           (flags & NVME_ZRM_ZRWA) ? 1 : 0);
2027         if (status) {
2028             return status;
2029         }
2030 
2031         if (act) {
2032             nvme_aor_inc_active(ns);
2033         }
2034 
2035         nvme_aor_inc_open(ns);
2036 
2037         if (flags & NVME_ZRM_AUTO) {
2038             nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_IMPLICITLY_OPEN);
2039             return NVME_SUCCESS;
2040         }
2041 
2042         /* fallthrough */
2043 
2044     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
2045         if (flags & NVME_ZRM_AUTO) {
2046             return NVME_SUCCESS;
2047         }
2048 
2049         nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_EXPLICITLY_OPEN);
2050 
2051         /* fallthrough */
2052 
2053     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
2054         if (flags & NVME_ZRM_ZRWA) {
2055             ns->zns.numzrwa--;
2056 
2057             zone->d.za |= NVME_ZA_ZRWA_VALID;
2058         }
2059 
2060         return NVME_SUCCESS;
2061 
2062     default:
2063         return NVME_ZONE_INVAL_TRANSITION;
2064     }
2065 }
2066 
2067 static inline uint16_t nvme_zrm_auto(NvmeCtrl *n, NvmeNamespace *ns,
2068                                      NvmeZone *zone)
2069 {
2070     return nvme_zrm_open_flags(n, ns, zone, NVME_ZRM_AUTO);
2071 }
2072 
2073 static void nvme_advance_zone_wp(NvmeNamespace *ns, NvmeZone *zone,
2074                                  uint32_t nlb)
2075 {
2076     zone->d.wp += nlb;
2077 
2078     if (zone->d.wp == nvme_zone_wr_boundary(zone)) {
2079         nvme_zrm_finish(ns, zone);
2080     }
2081 }
2082 
2083 static void nvme_zoned_zrwa_implicit_flush(NvmeNamespace *ns, NvmeZone *zone,
2084                                            uint32_t nlbc)
2085 {
2086     uint16_t nzrwafgs = DIV_ROUND_UP(nlbc, ns->zns.zrwafg);
2087 
2088     nlbc = nzrwafgs * ns->zns.zrwafg;
2089 
2090     trace_pci_nvme_zoned_zrwa_implicit_flush(zone->d.zslba, nlbc);
2091 
2092     zone->w_ptr += nlbc;
2093 
2094     nvme_advance_zone_wp(ns, zone, nlbc);
2095 }
2096 
2097 static void nvme_finalize_zoned_write(NvmeNamespace *ns, NvmeRequest *req)
2098 {
2099     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2100     NvmeZone *zone;
2101     uint64_t slba;
2102     uint32_t nlb;
2103 
2104     slba = le64_to_cpu(rw->slba);
2105     nlb = le16_to_cpu(rw->nlb) + 1;
2106     zone = nvme_get_zone_by_slba(ns, slba);
2107     assert(zone);
2108 
2109     if (zone->d.za & NVME_ZA_ZRWA_VALID) {
2110         uint64_t ezrwa = zone->w_ptr + ns->zns.zrwas - 1;
2111         uint64_t elba = slba + nlb - 1;
2112 
2113         if (elba > ezrwa) {
2114             nvme_zoned_zrwa_implicit_flush(ns, zone, elba - ezrwa);
2115         }
2116 
2117         return;
2118     }
2119 
2120     nvme_advance_zone_wp(ns, zone, nlb);
2121 }
2122 
2123 static inline bool nvme_is_write(NvmeRequest *req)
2124 {
2125     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2126 
2127     return rw->opcode == NVME_CMD_WRITE ||
2128            rw->opcode == NVME_CMD_ZONE_APPEND ||
2129            rw->opcode == NVME_CMD_WRITE_ZEROES;
2130 }
2131 
2132 static void nvme_misc_cb(void *opaque, int ret)
2133 {
2134     NvmeRequest *req = opaque;
2135 
2136     trace_pci_nvme_misc_cb(nvme_cid(req));
2137 
2138     if (ret) {
2139         nvme_aio_err(req, ret);
2140     }
2141 
2142     nvme_enqueue_req_completion(nvme_cq(req), req);
2143 }
2144 
2145 void nvme_rw_complete_cb(void *opaque, int ret)
2146 {
2147     NvmeRequest *req = opaque;
2148     NvmeNamespace *ns = req->ns;
2149     BlockBackend *blk = ns->blkconf.blk;
2150     BlockAcctCookie *acct = &req->acct;
2151     BlockAcctStats *stats = blk_get_stats(blk);
2152 
2153     trace_pci_nvme_rw_complete_cb(nvme_cid(req), blk_name(blk));
2154 
2155     if (ret) {
2156         block_acct_failed(stats, acct);
2157         nvme_aio_err(req, ret);
2158     } else {
2159         block_acct_done(stats, acct);
2160     }
2161 
2162     if (ns->params.zoned && nvme_is_write(req)) {
2163         nvme_finalize_zoned_write(ns, req);
2164     }
2165 
2166     nvme_enqueue_req_completion(nvme_cq(req), req);
2167 }
2168 
2169 static void nvme_rw_cb(void *opaque, int ret)
2170 {
2171     NvmeRequest *req = opaque;
2172     NvmeNamespace *ns = req->ns;
2173 
2174     BlockBackend *blk = ns->blkconf.blk;
2175 
2176     trace_pci_nvme_rw_cb(nvme_cid(req), blk_name(blk));
2177 
2178     if (ret) {
2179         goto out;
2180     }
2181 
2182     if (ns->lbaf.ms) {
2183         NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2184         uint64_t slba = le64_to_cpu(rw->slba);
2185         uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
2186         uint64_t offset = nvme_moff(ns, slba);
2187 
2188         if (req->cmd.opcode == NVME_CMD_WRITE_ZEROES) {
2189             size_t mlen = nvme_m2b(ns, nlb);
2190 
2191             req->aiocb = blk_aio_pwrite_zeroes(blk, offset, mlen,
2192                                                BDRV_REQ_MAY_UNMAP,
2193                                                nvme_rw_complete_cb, req);
2194             return;
2195         }
2196 
2197         if (nvme_ns_ext(ns) || req->cmd.mptr) {
2198             uint16_t status;
2199 
2200             nvme_sg_unmap(&req->sg);
2201             status = nvme_map_mdata(nvme_ctrl(req), nlb, req);
2202             if (status) {
2203                 ret = -EFAULT;
2204                 goto out;
2205             }
2206 
2207             if (req->cmd.opcode == NVME_CMD_READ) {
2208                 return nvme_blk_read(blk, offset, 1, nvme_rw_complete_cb, req);
2209             }
2210 
2211             return nvme_blk_write(blk, offset, 1, nvme_rw_complete_cb, req);
2212         }
2213     }
2214 
2215 out:
2216     nvme_rw_complete_cb(req, ret);
2217 }
2218 
2219 static void nvme_verify_cb(void *opaque, int ret)
2220 {
2221     NvmeBounceContext *ctx = opaque;
2222     NvmeRequest *req = ctx->req;
2223     NvmeNamespace *ns = req->ns;
2224     BlockBackend *blk = ns->blkconf.blk;
2225     BlockAcctCookie *acct = &req->acct;
2226     BlockAcctStats *stats = blk_get_stats(blk);
2227     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2228     uint64_t slba = le64_to_cpu(rw->slba);
2229     uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2230     uint16_t apptag = le16_to_cpu(rw->apptag);
2231     uint16_t appmask = le16_to_cpu(rw->appmask);
2232     uint64_t reftag = le32_to_cpu(rw->reftag);
2233     uint64_t cdw3 = le32_to_cpu(rw->cdw3);
2234     uint16_t status;
2235 
2236     reftag |= cdw3 << 32;
2237 
2238     trace_pci_nvme_verify_cb(nvme_cid(req), prinfo, apptag, appmask, reftag);
2239 
2240     if (ret) {
2241         block_acct_failed(stats, acct);
2242         nvme_aio_err(req, ret);
2243         goto out;
2244     }
2245 
2246     block_acct_done(stats, acct);
2247 
2248     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2249         status = nvme_dif_mangle_mdata(ns, ctx->mdata.bounce,
2250                                        ctx->mdata.iov.size, slba);
2251         if (status) {
2252             req->status = status;
2253             goto out;
2254         }
2255 
2256         req->status = nvme_dif_check(ns, ctx->data.bounce, ctx->data.iov.size,
2257                                      ctx->mdata.bounce, ctx->mdata.iov.size,
2258                                      prinfo, slba, apptag, appmask, &reftag);
2259     }
2260 
2261 out:
2262     qemu_iovec_destroy(&ctx->data.iov);
2263     g_free(ctx->data.bounce);
2264 
2265     qemu_iovec_destroy(&ctx->mdata.iov);
2266     g_free(ctx->mdata.bounce);
2267 
2268     g_free(ctx);
2269 
2270     nvme_enqueue_req_completion(nvme_cq(req), req);
2271 }
2272 
2273 
2274 static void nvme_verify_mdata_in_cb(void *opaque, int ret)
2275 {
2276     NvmeBounceContext *ctx = opaque;
2277     NvmeRequest *req = ctx->req;
2278     NvmeNamespace *ns = req->ns;
2279     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2280     uint64_t slba = le64_to_cpu(rw->slba);
2281     uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2282     size_t mlen = nvme_m2b(ns, nlb);
2283     uint64_t offset = nvme_moff(ns, slba);
2284     BlockBackend *blk = ns->blkconf.blk;
2285 
2286     trace_pci_nvme_verify_mdata_in_cb(nvme_cid(req), blk_name(blk));
2287 
2288     if (ret) {
2289         goto out;
2290     }
2291 
2292     ctx->mdata.bounce = g_malloc(mlen);
2293 
2294     qemu_iovec_reset(&ctx->mdata.iov);
2295     qemu_iovec_add(&ctx->mdata.iov, ctx->mdata.bounce, mlen);
2296 
2297     req->aiocb = blk_aio_preadv(blk, offset, &ctx->mdata.iov, 0,
2298                                 nvme_verify_cb, ctx);
2299     return;
2300 
2301 out:
2302     nvme_verify_cb(ctx, ret);
2303 }
2304 
2305 struct nvme_compare_ctx {
2306     struct {
2307         QEMUIOVector iov;
2308         uint8_t *bounce;
2309     } data;
2310 
2311     struct {
2312         QEMUIOVector iov;
2313         uint8_t *bounce;
2314     } mdata;
2315 };
2316 
2317 static void nvme_compare_mdata_cb(void *opaque, int ret)
2318 {
2319     NvmeRequest *req = opaque;
2320     NvmeNamespace *ns = req->ns;
2321     NvmeCtrl *n = nvme_ctrl(req);
2322     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2323     uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2324     uint16_t apptag = le16_to_cpu(rw->apptag);
2325     uint16_t appmask = le16_to_cpu(rw->appmask);
2326     uint64_t reftag = le32_to_cpu(rw->reftag);
2327     uint64_t cdw3 = le32_to_cpu(rw->cdw3);
2328     struct nvme_compare_ctx *ctx = req->opaque;
2329     g_autofree uint8_t *buf = NULL;
2330     BlockBackend *blk = ns->blkconf.blk;
2331     BlockAcctCookie *acct = &req->acct;
2332     BlockAcctStats *stats = blk_get_stats(blk);
2333     uint16_t status = NVME_SUCCESS;
2334 
2335     reftag |= cdw3 << 32;
2336 
2337     trace_pci_nvme_compare_mdata_cb(nvme_cid(req));
2338 
2339     if (ret) {
2340         block_acct_failed(stats, acct);
2341         nvme_aio_err(req, ret);
2342         goto out;
2343     }
2344 
2345     buf = g_malloc(ctx->mdata.iov.size);
2346 
2347     status = nvme_bounce_mdata(n, buf, ctx->mdata.iov.size,
2348                                NVME_TX_DIRECTION_TO_DEVICE, req);
2349     if (status) {
2350         req->status = status;
2351         goto out;
2352     }
2353 
2354     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2355         uint64_t slba = le64_to_cpu(rw->slba);
2356         uint8_t *bufp;
2357         uint8_t *mbufp = ctx->mdata.bounce;
2358         uint8_t *end = mbufp + ctx->mdata.iov.size;
2359         int16_t pil = 0;
2360 
2361         status = nvme_dif_check(ns, ctx->data.bounce, ctx->data.iov.size,
2362                                 ctx->mdata.bounce, ctx->mdata.iov.size, prinfo,
2363                                 slba, apptag, appmask, &reftag);
2364         if (status) {
2365             req->status = status;
2366             goto out;
2367         }
2368 
2369         /*
2370          * When formatted with protection information, do not compare the DIF
2371          * tuple.
2372          */
2373         if (!(ns->id_ns.dps & NVME_ID_NS_DPS_FIRST_EIGHT)) {
2374             pil = ns->lbaf.ms - nvme_pi_tuple_size(ns);
2375         }
2376 
2377         for (bufp = buf; mbufp < end; bufp += ns->lbaf.ms, mbufp += ns->lbaf.ms) {
2378             if (memcmp(bufp + pil, mbufp + pil, ns->lbaf.ms - pil)) {
2379                 req->status = NVME_CMP_FAILURE | NVME_DNR;
2380                 goto out;
2381             }
2382         }
2383 
2384         goto out;
2385     }
2386 
2387     if (memcmp(buf, ctx->mdata.bounce, ctx->mdata.iov.size)) {
2388         req->status = NVME_CMP_FAILURE | NVME_DNR;
2389         goto out;
2390     }
2391 
2392     block_acct_done(stats, acct);
2393 
2394 out:
2395     qemu_iovec_destroy(&ctx->data.iov);
2396     g_free(ctx->data.bounce);
2397 
2398     qemu_iovec_destroy(&ctx->mdata.iov);
2399     g_free(ctx->mdata.bounce);
2400 
2401     g_free(ctx);
2402 
2403     nvme_enqueue_req_completion(nvme_cq(req), req);
2404 }
2405 
2406 static void nvme_compare_data_cb(void *opaque, int ret)
2407 {
2408     NvmeRequest *req = opaque;
2409     NvmeCtrl *n = nvme_ctrl(req);
2410     NvmeNamespace *ns = req->ns;
2411     BlockBackend *blk = ns->blkconf.blk;
2412     BlockAcctCookie *acct = &req->acct;
2413     BlockAcctStats *stats = blk_get_stats(blk);
2414 
2415     struct nvme_compare_ctx *ctx = req->opaque;
2416     g_autofree uint8_t *buf = NULL;
2417     uint16_t status;
2418 
2419     trace_pci_nvme_compare_data_cb(nvme_cid(req));
2420 
2421     if (ret) {
2422         block_acct_failed(stats, acct);
2423         nvme_aio_err(req, ret);
2424         goto out;
2425     }
2426 
2427     buf = g_malloc(ctx->data.iov.size);
2428 
2429     status = nvme_bounce_data(n, buf, ctx->data.iov.size,
2430                               NVME_TX_DIRECTION_TO_DEVICE, req);
2431     if (status) {
2432         req->status = status;
2433         goto out;
2434     }
2435 
2436     if (memcmp(buf, ctx->data.bounce, ctx->data.iov.size)) {
2437         req->status = NVME_CMP_FAILURE | NVME_DNR;
2438         goto out;
2439     }
2440 
2441     if (ns->lbaf.ms) {
2442         NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2443         uint64_t slba = le64_to_cpu(rw->slba);
2444         uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2445         size_t mlen = nvme_m2b(ns, nlb);
2446         uint64_t offset = nvme_moff(ns, slba);
2447 
2448         ctx->mdata.bounce = g_malloc(mlen);
2449 
2450         qemu_iovec_init(&ctx->mdata.iov, 1);
2451         qemu_iovec_add(&ctx->mdata.iov, ctx->mdata.bounce, mlen);
2452 
2453         req->aiocb = blk_aio_preadv(blk, offset, &ctx->mdata.iov, 0,
2454                                     nvme_compare_mdata_cb, req);
2455         return;
2456     }
2457 
2458     block_acct_done(stats, acct);
2459 
2460 out:
2461     qemu_iovec_destroy(&ctx->data.iov);
2462     g_free(ctx->data.bounce);
2463     g_free(ctx);
2464 
2465     nvme_enqueue_req_completion(nvme_cq(req), req);
2466 }
2467 
2468 typedef struct NvmeDSMAIOCB {
2469     BlockAIOCB common;
2470     BlockAIOCB *aiocb;
2471     NvmeRequest *req;
2472     int ret;
2473 
2474     NvmeDsmRange *range;
2475     unsigned int nr;
2476     unsigned int idx;
2477 } NvmeDSMAIOCB;
2478 
2479 static void nvme_dsm_cancel(BlockAIOCB *aiocb)
2480 {
2481     NvmeDSMAIOCB *iocb = container_of(aiocb, NvmeDSMAIOCB, common);
2482 
2483     /* break nvme_dsm_cb loop */
2484     iocb->idx = iocb->nr;
2485     iocb->ret = -ECANCELED;
2486 
2487     if (iocb->aiocb) {
2488         blk_aio_cancel_async(iocb->aiocb);
2489         iocb->aiocb = NULL;
2490     } else {
2491         /*
2492          * We only reach this if nvme_dsm_cancel() has already been called or
2493          * the command ran to completion.
2494          */
2495         assert(iocb->idx == iocb->nr);
2496     }
2497 }
2498 
2499 static const AIOCBInfo nvme_dsm_aiocb_info = {
2500     .aiocb_size   = sizeof(NvmeDSMAIOCB),
2501     .cancel_async = nvme_dsm_cancel,
2502 };
2503 
2504 static void nvme_dsm_cb(void *opaque, int ret);
2505 
2506 static void nvme_dsm_md_cb(void *opaque, int ret)
2507 {
2508     NvmeDSMAIOCB *iocb = opaque;
2509     NvmeRequest *req = iocb->req;
2510     NvmeNamespace *ns = req->ns;
2511     NvmeDsmRange *range;
2512     uint64_t slba;
2513     uint32_t nlb;
2514 
2515     if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
2516         goto done;
2517     }
2518 
2519     range = &iocb->range[iocb->idx - 1];
2520     slba = le64_to_cpu(range->slba);
2521     nlb = le32_to_cpu(range->nlb);
2522 
2523     /*
2524      * Check that all block were discarded (zeroed); otherwise we do not zero
2525      * the metadata.
2526      */
2527 
2528     ret = nvme_block_status_all(ns, slba, nlb, BDRV_BLOCK_ZERO);
2529     if (ret) {
2530         if (ret < 0) {
2531             goto done;
2532         }
2533 
2534         nvme_dsm_cb(iocb, 0);
2535         return;
2536     }
2537 
2538     iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, nvme_moff(ns, slba),
2539                                         nvme_m2b(ns, nlb), BDRV_REQ_MAY_UNMAP,
2540                                         nvme_dsm_cb, iocb);
2541     return;
2542 
2543 done:
2544     nvme_dsm_cb(iocb, ret);
2545 }
2546 
2547 static void nvme_dsm_cb(void *opaque, int ret)
2548 {
2549     NvmeDSMAIOCB *iocb = opaque;
2550     NvmeRequest *req = iocb->req;
2551     NvmeCtrl *n = nvme_ctrl(req);
2552     NvmeNamespace *ns = req->ns;
2553     NvmeDsmRange *range;
2554     uint64_t slba;
2555     uint32_t nlb;
2556 
2557     if (iocb->ret < 0) {
2558         goto done;
2559     } else if (ret < 0) {
2560         iocb->ret = ret;
2561         goto done;
2562     }
2563 
2564 next:
2565     if (iocb->idx == iocb->nr) {
2566         goto done;
2567     }
2568 
2569     range = &iocb->range[iocb->idx++];
2570     slba = le64_to_cpu(range->slba);
2571     nlb = le32_to_cpu(range->nlb);
2572 
2573     trace_pci_nvme_dsm_deallocate(slba, nlb);
2574 
2575     if (nlb > n->dmrsl) {
2576         trace_pci_nvme_dsm_single_range_limit_exceeded(nlb, n->dmrsl);
2577         goto next;
2578     }
2579 
2580     if (nvme_check_bounds(ns, slba, nlb)) {
2581         trace_pci_nvme_err_invalid_lba_range(slba, nlb,
2582                                              ns->id_ns.nsze);
2583         goto next;
2584     }
2585 
2586     iocb->aiocb = blk_aio_pdiscard(ns->blkconf.blk, nvme_l2b(ns, slba),
2587                                    nvme_l2b(ns, nlb),
2588                                    nvme_dsm_md_cb, iocb);
2589     return;
2590 
2591 done:
2592     iocb->aiocb = NULL;
2593     iocb->common.cb(iocb->common.opaque, iocb->ret);
2594     qemu_aio_unref(iocb);
2595 }
2596 
2597 static uint16_t nvme_dsm(NvmeCtrl *n, NvmeRequest *req)
2598 {
2599     NvmeNamespace *ns = req->ns;
2600     NvmeDsmCmd *dsm = (NvmeDsmCmd *) &req->cmd;
2601     uint32_t attr = le32_to_cpu(dsm->attributes);
2602     uint32_t nr = (le32_to_cpu(dsm->nr) & 0xff) + 1;
2603     uint16_t status = NVME_SUCCESS;
2604 
2605     trace_pci_nvme_dsm(nr, attr);
2606 
2607     if (attr & NVME_DSMGMT_AD) {
2608         NvmeDSMAIOCB *iocb = blk_aio_get(&nvme_dsm_aiocb_info, ns->blkconf.blk,
2609                                          nvme_misc_cb, req);
2610 
2611         iocb->req = req;
2612         iocb->ret = 0;
2613         iocb->range = g_new(NvmeDsmRange, nr);
2614         iocb->nr = nr;
2615         iocb->idx = 0;
2616 
2617         status = nvme_h2c(n, (uint8_t *)iocb->range, sizeof(NvmeDsmRange) * nr,
2618                           req);
2619         if (status) {
2620             g_free(iocb->range);
2621             qemu_aio_unref(iocb);
2622 
2623             return status;
2624         }
2625 
2626         req->aiocb = &iocb->common;
2627         nvme_dsm_cb(iocb, 0);
2628 
2629         return NVME_NO_COMPLETE;
2630     }
2631 
2632     return status;
2633 }
2634 
2635 static uint16_t nvme_verify(NvmeCtrl *n, NvmeRequest *req)
2636 {
2637     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
2638     NvmeNamespace *ns = req->ns;
2639     BlockBackend *blk = ns->blkconf.blk;
2640     uint64_t slba = le64_to_cpu(rw->slba);
2641     uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
2642     size_t len = nvme_l2b(ns, nlb);
2643     int64_t offset = nvme_l2b(ns, slba);
2644     uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
2645     uint32_t reftag = le32_to_cpu(rw->reftag);
2646     NvmeBounceContext *ctx = NULL;
2647     uint16_t status;
2648 
2649     trace_pci_nvme_verify(nvme_cid(req), nvme_nsid(ns), slba, nlb);
2650 
2651     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2652         status = nvme_check_prinfo(ns, prinfo, slba, reftag);
2653         if (status) {
2654             return status;
2655         }
2656 
2657         if (prinfo & NVME_PRINFO_PRACT) {
2658             return NVME_INVALID_PROT_INFO | NVME_DNR;
2659         }
2660     }
2661 
2662     if (len > n->page_size << n->params.vsl) {
2663         return NVME_INVALID_FIELD | NVME_DNR;
2664     }
2665 
2666     status = nvme_check_bounds(ns, slba, nlb);
2667     if (status) {
2668         return status;
2669     }
2670 
2671     if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
2672         status = nvme_check_dulbe(ns, slba, nlb);
2673         if (status) {
2674             return status;
2675         }
2676     }
2677 
2678     ctx = g_new0(NvmeBounceContext, 1);
2679     ctx->req = req;
2680 
2681     ctx->data.bounce = g_malloc(len);
2682 
2683     qemu_iovec_init(&ctx->data.iov, 1);
2684     qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, len);
2685 
2686     block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
2687                      BLOCK_ACCT_READ);
2688 
2689     req->aiocb = blk_aio_preadv(ns->blkconf.blk, offset, &ctx->data.iov, 0,
2690                                 nvme_verify_mdata_in_cb, ctx);
2691     return NVME_NO_COMPLETE;
2692 }
2693 
2694 typedef struct NvmeCopyAIOCB {
2695     BlockAIOCB common;
2696     BlockAIOCB *aiocb;
2697     NvmeRequest *req;
2698     int ret;
2699 
2700     void *ranges;
2701     unsigned int format;
2702     int nr;
2703     int idx;
2704 
2705     uint8_t *bounce;
2706     QEMUIOVector iov;
2707     struct {
2708         BlockAcctCookie read;
2709         BlockAcctCookie write;
2710     } acct;
2711 
2712     uint64_t reftag;
2713     uint64_t slba;
2714 
2715     NvmeZone *zone;
2716 } NvmeCopyAIOCB;
2717 
2718 static void nvme_copy_cancel(BlockAIOCB *aiocb)
2719 {
2720     NvmeCopyAIOCB *iocb = container_of(aiocb, NvmeCopyAIOCB, common);
2721 
2722     iocb->ret = -ECANCELED;
2723 
2724     if (iocb->aiocb) {
2725         blk_aio_cancel_async(iocb->aiocb);
2726         iocb->aiocb = NULL;
2727     }
2728 }
2729 
2730 static const AIOCBInfo nvme_copy_aiocb_info = {
2731     .aiocb_size   = sizeof(NvmeCopyAIOCB),
2732     .cancel_async = nvme_copy_cancel,
2733 };
2734 
2735 static void nvme_copy_done(NvmeCopyAIOCB *iocb)
2736 {
2737     NvmeRequest *req = iocb->req;
2738     NvmeNamespace *ns = req->ns;
2739     BlockAcctStats *stats = blk_get_stats(ns->blkconf.blk);
2740 
2741     if (iocb->idx != iocb->nr) {
2742         req->cqe.result = cpu_to_le32(iocb->idx);
2743     }
2744 
2745     qemu_iovec_destroy(&iocb->iov);
2746     g_free(iocb->bounce);
2747 
2748     if (iocb->ret < 0) {
2749         block_acct_failed(stats, &iocb->acct.read);
2750         block_acct_failed(stats, &iocb->acct.write);
2751     } else {
2752         block_acct_done(stats, &iocb->acct.read);
2753         block_acct_done(stats, &iocb->acct.write);
2754     }
2755 
2756     iocb->common.cb(iocb->common.opaque, iocb->ret);
2757     qemu_aio_unref(iocb);
2758 }
2759 
2760 static void nvme_do_copy(NvmeCopyAIOCB *iocb);
2761 
2762 static void nvme_copy_source_range_parse_format0(void *ranges, int idx,
2763                                                  uint64_t *slba, uint32_t *nlb,
2764                                                  uint16_t *apptag,
2765                                                  uint16_t *appmask,
2766                                                  uint64_t *reftag)
2767 {
2768     NvmeCopySourceRangeFormat0 *_ranges = ranges;
2769 
2770     if (slba) {
2771         *slba = le64_to_cpu(_ranges[idx].slba);
2772     }
2773 
2774     if (nlb) {
2775         *nlb = le16_to_cpu(_ranges[idx].nlb) + 1;
2776     }
2777 
2778     if (apptag) {
2779         *apptag = le16_to_cpu(_ranges[idx].apptag);
2780     }
2781 
2782     if (appmask) {
2783         *appmask = le16_to_cpu(_ranges[idx].appmask);
2784     }
2785 
2786     if (reftag) {
2787         *reftag = le32_to_cpu(_ranges[idx].reftag);
2788     }
2789 }
2790 
2791 static void nvme_copy_source_range_parse_format1(void *ranges, int idx,
2792                                                  uint64_t *slba, uint32_t *nlb,
2793                                                  uint16_t *apptag,
2794                                                  uint16_t *appmask,
2795                                                  uint64_t *reftag)
2796 {
2797     NvmeCopySourceRangeFormat1 *_ranges = ranges;
2798 
2799     if (slba) {
2800         *slba = le64_to_cpu(_ranges[idx].slba);
2801     }
2802 
2803     if (nlb) {
2804         *nlb = le16_to_cpu(_ranges[idx].nlb) + 1;
2805     }
2806 
2807     if (apptag) {
2808         *apptag = le16_to_cpu(_ranges[idx].apptag);
2809     }
2810 
2811     if (appmask) {
2812         *appmask = le16_to_cpu(_ranges[idx].appmask);
2813     }
2814 
2815     if (reftag) {
2816         *reftag = 0;
2817 
2818         *reftag |= (uint64_t)_ranges[idx].sr[4] << 40;
2819         *reftag |= (uint64_t)_ranges[idx].sr[5] << 32;
2820         *reftag |= (uint64_t)_ranges[idx].sr[6] << 24;
2821         *reftag |= (uint64_t)_ranges[idx].sr[7] << 16;
2822         *reftag |= (uint64_t)_ranges[idx].sr[8] << 8;
2823         *reftag |= (uint64_t)_ranges[idx].sr[9];
2824     }
2825 }
2826 
2827 static void nvme_copy_source_range_parse(void *ranges, int idx, uint8_t format,
2828                                          uint64_t *slba, uint32_t *nlb,
2829                                          uint16_t *apptag, uint16_t *appmask,
2830                                          uint64_t *reftag)
2831 {
2832     switch (format) {
2833     case NVME_COPY_FORMAT_0:
2834         nvme_copy_source_range_parse_format0(ranges, idx, slba, nlb, apptag,
2835                                              appmask, reftag);
2836         break;
2837 
2838     case NVME_COPY_FORMAT_1:
2839         nvme_copy_source_range_parse_format1(ranges, idx, slba, nlb, apptag,
2840                                              appmask, reftag);
2841         break;
2842 
2843     default:
2844         abort();
2845     }
2846 }
2847 
2848 static inline uint16_t nvme_check_copy_mcl(NvmeNamespace *ns,
2849                                            NvmeCopyAIOCB *iocb, uint16_t nr)
2850 {
2851     uint32_t copy_len = 0;
2852 
2853     for (int idx = 0; idx < nr; idx++) {
2854         uint32_t nlb;
2855         nvme_copy_source_range_parse(iocb->ranges, idx, iocb->format, NULL,
2856                                      &nlb, NULL, NULL, NULL);
2857         copy_len += nlb;
2858     }
2859 
2860     if (copy_len > ns->id_ns.mcl) {
2861         return NVME_CMD_SIZE_LIMIT | NVME_DNR;
2862     }
2863 
2864     return NVME_SUCCESS;
2865 }
2866 
2867 static void nvme_copy_out_completed_cb(void *opaque, int ret)
2868 {
2869     NvmeCopyAIOCB *iocb = opaque;
2870     NvmeRequest *req = iocb->req;
2871     NvmeNamespace *ns = req->ns;
2872     uint32_t nlb;
2873 
2874     nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, NULL,
2875                                  &nlb, NULL, NULL, NULL);
2876 
2877     if (ret < 0) {
2878         iocb->ret = ret;
2879         goto out;
2880     } else if (iocb->ret < 0) {
2881         goto out;
2882     }
2883 
2884     if (ns->params.zoned) {
2885         nvme_advance_zone_wp(ns, iocb->zone, nlb);
2886     }
2887 
2888     iocb->idx++;
2889     iocb->slba += nlb;
2890 out:
2891     nvme_do_copy(iocb);
2892 }
2893 
2894 static void nvme_copy_out_cb(void *opaque, int ret)
2895 {
2896     NvmeCopyAIOCB *iocb = opaque;
2897     NvmeRequest *req = iocb->req;
2898     NvmeNamespace *ns = req->ns;
2899     uint32_t nlb;
2900     size_t mlen;
2901     uint8_t *mbounce;
2902 
2903     if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
2904         goto out;
2905     }
2906 
2907     nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, NULL,
2908                                  &nlb, NULL, NULL, NULL);
2909 
2910     mlen = nvme_m2b(ns, nlb);
2911     mbounce = iocb->bounce + nvme_l2b(ns, nlb);
2912 
2913     qemu_iovec_reset(&iocb->iov);
2914     qemu_iovec_add(&iocb->iov, mbounce, mlen);
2915 
2916     iocb->aiocb = blk_aio_pwritev(ns->blkconf.blk, nvme_moff(ns, iocb->slba),
2917                                   &iocb->iov, 0, nvme_copy_out_completed_cb,
2918                                   iocb);
2919 
2920     return;
2921 
2922 out:
2923     nvme_copy_out_completed_cb(iocb, ret);
2924 }
2925 
2926 static void nvme_copy_in_completed_cb(void *opaque, int ret)
2927 {
2928     NvmeCopyAIOCB *iocb = opaque;
2929     NvmeRequest *req = iocb->req;
2930     NvmeNamespace *ns = req->ns;
2931     uint32_t nlb;
2932     uint64_t slba;
2933     uint16_t apptag, appmask;
2934     uint64_t reftag;
2935     size_t len;
2936     uint16_t status;
2937 
2938     if (ret < 0) {
2939         iocb->ret = ret;
2940         goto out;
2941     } else if (iocb->ret < 0) {
2942         goto out;
2943     }
2944 
2945     nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, &slba,
2946                                  &nlb, &apptag, &appmask, &reftag);
2947     len = nvme_l2b(ns, nlb);
2948 
2949     trace_pci_nvme_copy_out(iocb->slba, nlb);
2950 
2951     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
2952         NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
2953 
2954         uint16_t prinfor = ((copy->control[0] >> 4) & 0xf);
2955         uint16_t prinfow = ((copy->control[2] >> 2) & 0xf);
2956 
2957         size_t mlen = nvme_m2b(ns, nlb);
2958         uint8_t *mbounce = iocb->bounce + nvme_l2b(ns, nlb);
2959 
2960         status = nvme_dif_mangle_mdata(ns, mbounce, mlen, slba);
2961         if (status) {
2962             goto invalid;
2963         }
2964         status = nvme_dif_check(ns, iocb->bounce, len, mbounce, mlen, prinfor,
2965                                 slba, apptag, appmask, &reftag);
2966         if (status) {
2967             goto invalid;
2968         }
2969 
2970         apptag = le16_to_cpu(copy->apptag);
2971         appmask = le16_to_cpu(copy->appmask);
2972 
2973         if (prinfow & NVME_PRINFO_PRACT) {
2974             status = nvme_check_prinfo(ns, prinfow, iocb->slba, iocb->reftag);
2975             if (status) {
2976                 goto invalid;
2977             }
2978 
2979             nvme_dif_pract_generate_dif(ns, iocb->bounce, len, mbounce, mlen,
2980                                         apptag, &iocb->reftag);
2981         } else {
2982             status = nvme_dif_check(ns, iocb->bounce, len, mbounce, mlen,
2983                                     prinfow, iocb->slba, apptag, appmask,
2984                                     &iocb->reftag);
2985             if (status) {
2986                 goto invalid;
2987             }
2988         }
2989     }
2990 
2991     status = nvme_check_bounds(ns, iocb->slba, nlb);
2992     if (status) {
2993         goto invalid;
2994     }
2995 
2996     if (ns->params.zoned) {
2997         status = nvme_check_zone_write(ns, iocb->zone, iocb->slba, nlb);
2998         if (status) {
2999             goto invalid;
3000         }
3001 
3002         if (!(iocb->zone->d.za & NVME_ZA_ZRWA_VALID)) {
3003             iocb->zone->w_ptr += nlb;
3004         }
3005     }
3006 
3007     qemu_iovec_reset(&iocb->iov);
3008     qemu_iovec_add(&iocb->iov, iocb->bounce, len);
3009 
3010     iocb->aiocb = blk_aio_pwritev(ns->blkconf.blk, nvme_l2b(ns, iocb->slba),
3011                                   &iocb->iov, 0, nvme_copy_out_cb, iocb);
3012 
3013     return;
3014 
3015 invalid:
3016     req->status = status;
3017     iocb->ret = -1;
3018 out:
3019     nvme_do_copy(iocb);
3020 }
3021 
3022 static void nvme_copy_in_cb(void *opaque, int ret)
3023 {
3024     NvmeCopyAIOCB *iocb = opaque;
3025     NvmeRequest *req = iocb->req;
3026     NvmeNamespace *ns = req->ns;
3027     uint64_t slba;
3028     uint32_t nlb;
3029 
3030     if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
3031         goto out;
3032     }
3033 
3034     nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, &slba,
3035                                  &nlb, NULL, NULL, NULL);
3036 
3037     qemu_iovec_reset(&iocb->iov);
3038     qemu_iovec_add(&iocb->iov, iocb->bounce + nvme_l2b(ns, nlb),
3039                    nvme_m2b(ns, nlb));
3040 
3041     iocb->aiocb = blk_aio_preadv(ns->blkconf.blk, nvme_moff(ns, slba),
3042                                  &iocb->iov, 0, nvme_copy_in_completed_cb,
3043                                  iocb);
3044     return;
3045 
3046 out:
3047     nvme_copy_in_completed_cb(iocb, ret);
3048 }
3049 
3050 static void nvme_do_copy(NvmeCopyAIOCB *iocb)
3051 {
3052     NvmeRequest *req = iocb->req;
3053     NvmeNamespace *ns = req->ns;
3054     uint64_t slba;
3055     uint32_t nlb;
3056     size_t len;
3057     uint16_t status;
3058 
3059     if (iocb->ret < 0) {
3060         goto done;
3061     }
3062 
3063     if (iocb->idx == iocb->nr) {
3064         goto done;
3065     }
3066 
3067     nvme_copy_source_range_parse(iocb->ranges, iocb->idx, iocb->format, &slba,
3068                                  &nlb, NULL, NULL, NULL);
3069     len = nvme_l2b(ns, nlb);
3070 
3071     trace_pci_nvme_copy_source_range(slba, nlb);
3072 
3073     if (nlb > le16_to_cpu(ns->id_ns.mssrl)) {
3074         status = NVME_CMD_SIZE_LIMIT | NVME_DNR;
3075         goto invalid;
3076     }
3077 
3078     status = nvme_check_bounds(ns, slba, nlb);
3079     if (status) {
3080         goto invalid;
3081     }
3082 
3083     if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
3084         status = nvme_check_dulbe(ns, slba, nlb);
3085         if (status) {
3086             goto invalid;
3087         }
3088     }
3089 
3090     if (ns->params.zoned) {
3091         status = nvme_check_zone_read(ns, slba, nlb);
3092         if (status) {
3093             goto invalid;
3094         }
3095     }
3096 
3097     qemu_iovec_reset(&iocb->iov);
3098     qemu_iovec_add(&iocb->iov, iocb->bounce, len);
3099 
3100     iocb->aiocb = blk_aio_preadv(ns->blkconf.blk, nvme_l2b(ns, slba),
3101                                  &iocb->iov, 0, nvme_copy_in_cb, iocb);
3102     return;
3103 
3104 invalid:
3105     req->status = status;
3106     iocb->ret = -1;
3107 done:
3108     nvme_copy_done(iocb);
3109 }
3110 
3111 static uint16_t nvme_copy(NvmeCtrl *n, NvmeRequest *req)
3112 {
3113     NvmeNamespace *ns = req->ns;
3114     NvmeCopyCmd *copy = (NvmeCopyCmd *)&req->cmd;
3115     NvmeCopyAIOCB *iocb = blk_aio_get(&nvme_copy_aiocb_info, ns->blkconf.blk,
3116                                       nvme_misc_cb, req);
3117     uint16_t nr = copy->nr + 1;
3118     uint8_t format = copy->control[0] & 0xf;
3119     uint16_t prinfor = ((copy->control[0] >> 4) & 0xf);
3120     uint16_t prinfow = ((copy->control[2] >> 2) & 0xf);
3121     size_t len = sizeof(NvmeCopySourceRangeFormat0);
3122 
3123     uint16_t status;
3124 
3125     trace_pci_nvme_copy(nvme_cid(req), nvme_nsid(ns), nr, format);
3126 
3127     iocb->ranges = NULL;
3128     iocb->zone = NULL;
3129 
3130     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps) &&
3131         ((prinfor & NVME_PRINFO_PRACT) != (prinfow & NVME_PRINFO_PRACT))) {
3132         status = NVME_INVALID_FIELD | NVME_DNR;
3133         goto invalid;
3134     }
3135 
3136     if (!(n->id_ctrl.ocfs & (1 << format))) {
3137         trace_pci_nvme_err_copy_invalid_format(format);
3138         status = NVME_INVALID_FIELD | NVME_DNR;
3139         goto invalid;
3140     }
3141 
3142     if (nr > ns->id_ns.msrc + 1) {
3143         status = NVME_CMD_SIZE_LIMIT | NVME_DNR;
3144         goto invalid;
3145     }
3146 
3147     if ((ns->pif == 0x0 && format != 0x0) ||
3148         (ns->pif != 0x0 && format != 0x1)) {
3149         status = NVME_INVALID_FORMAT | NVME_DNR;
3150         goto invalid;
3151     }
3152 
3153     if (ns->pif) {
3154         len = sizeof(NvmeCopySourceRangeFormat1);
3155     }
3156 
3157     iocb->format = format;
3158     iocb->ranges = g_malloc_n(nr, len);
3159     status = nvme_h2c(n, (uint8_t *)iocb->ranges, len * nr, req);
3160     if (status) {
3161         goto invalid;
3162     }
3163 
3164     iocb->slba = le64_to_cpu(copy->sdlba);
3165 
3166     if (ns->params.zoned) {
3167         iocb->zone = nvme_get_zone_by_slba(ns, iocb->slba);
3168         if (!iocb->zone) {
3169             status = NVME_LBA_RANGE | NVME_DNR;
3170             goto invalid;
3171         }
3172 
3173         status = nvme_zrm_auto(n, ns, iocb->zone);
3174         if (status) {
3175             goto invalid;
3176         }
3177     }
3178 
3179     status = nvme_check_copy_mcl(ns, iocb, nr);
3180     if (status) {
3181         goto invalid;
3182     }
3183 
3184     iocb->req = req;
3185     iocb->ret = 0;
3186     iocb->nr = nr;
3187     iocb->idx = 0;
3188     iocb->reftag = le32_to_cpu(copy->reftag);
3189     iocb->reftag |= (uint64_t)le32_to_cpu(copy->cdw3) << 32;
3190     iocb->bounce = g_malloc_n(le16_to_cpu(ns->id_ns.mssrl),
3191                               ns->lbasz + ns->lbaf.ms);
3192 
3193     qemu_iovec_init(&iocb->iov, 1);
3194 
3195     block_acct_start(blk_get_stats(ns->blkconf.blk), &iocb->acct.read, 0,
3196                      BLOCK_ACCT_READ);
3197     block_acct_start(blk_get_stats(ns->blkconf.blk), &iocb->acct.write, 0,
3198                      BLOCK_ACCT_WRITE);
3199 
3200     req->aiocb = &iocb->common;
3201     nvme_do_copy(iocb);
3202 
3203     return NVME_NO_COMPLETE;
3204 
3205 invalid:
3206     g_free(iocb->ranges);
3207     qemu_aio_unref(iocb);
3208     return status;
3209 }
3210 
3211 static uint16_t nvme_compare(NvmeCtrl *n, NvmeRequest *req)
3212 {
3213     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3214     NvmeNamespace *ns = req->ns;
3215     BlockBackend *blk = ns->blkconf.blk;
3216     uint64_t slba = le64_to_cpu(rw->slba);
3217     uint32_t nlb = le16_to_cpu(rw->nlb) + 1;
3218     uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
3219     size_t data_len = nvme_l2b(ns, nlb);
3220     size_t len = data_len;
3221     int64_t offset = nvme_l2b(ns, slba);
3222     struct nvme_compare_ctx *ctx = NULL;
3223     uint16_t status;
3224 
3225     trace_pci_nvme_compare(nvme_cid(req), nvme_nsid(ns), slba, nlb);
3226 
3227     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps) && (prinfo & NVME_PRINFO_PRACT)) {
3228         return NVME_INVALID_PROT_INFO | NVME_DNR;
3229     }
3230 
3231     if (nvme_ns_ext(ns)) {
3232         len += nvme_m2b(ns, nlb);
3233     }
3234 
3235     status = nvme_check_mdts(n, len);
3236     if (status) {
3237         return status;
3238     }
3239 
3240     status = nvme_check_bounds(ns, slba, nlb);
3241     if (status) {
3242         return status;
3243     }
3244 
3245     if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
3246         status = nvme_check_dulbe(ns, slba, nlb);
3247         if (status) {
3248             return status;
3249         }
3250     }
3251 
3252     status = nvme_map_dptr(n, &req->sg, len, &req->cmd);
3253     if (status) {
3254         return status;
3255     }
3256 
3257     ctx = g_new(struct nvme_compare_ctx, 1);
3258     ctx->data.bounce = g_malloc(data_len);
3259 
3260     req->opaque = ctx;
3261 
3262     qemu_iovec_init(&ctx->data.iov, 1);
3263     qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, data_len);
3264 
3265     block_acct_start(blk_get_stats(blk), &req->acct, data_len,
3266                      BLOCK_ACCT_READ);
3267     req->aiocb = blk_aio_preadv(blk, offset, &ctx->data.iov, 0,
3268                                 nvme_compare_data_cb, req);
3269 
3270     return NVME_NO_COMPLETE;
3271 }
3272 
3273 typedef struct NvmeFlushAIOCB {
3274     BlockAIOCB common;
3275     BlockAIOCB *aiocb;
3276     NvmeRequest *req;
3277     int ret;
3278 
3279     NvmeNamespace *ns;
3280     uint32_t nsid;
3281     bool broadcast;
3282 } NvmeFlushAIOCB;
3283 
3284 static void nvme_flush_cancel(BlockAIOCB *acb)
3285 {
3286     NvmeFlushAIOCB *iocb = container_of(acb, NvmeFlushAIOCB, common);
3287 
3288     iocb->ret = -ECANCELED;
3289 
3290     if (iocb->aiocb) {
3291         blk_aio_cancel_async(iocb->aiocb);
3292         iocb->aiocb = NULL;
3293     }
3294 }
3295 
3296 static const AIOCBInfo nvme_flush_aiocb_info = {
3297     .aiocb_size = sizeof(NvmeFlushAIOCB),
3298     .cancel_async = nvme_flush_cancel,
3299 };
3300 
3301 static void nvme_do_flush(NvmeFlushAIOCB *iocb);
3302 
3303 static void nvme_flush_ns_cb(void *opaque, int ret)
3304 {
3305     NvmeFlushAIOCB *iocb = opaque;
3306     NvmeNamespace *ns = iocb->ns;
3307 
3308     if (ret < 0) {
3309         iocb->ret = ret;
3310         goto out;
3311     } else if (iocb->ret < 0) {
3312         goto out;
3313     }
3314 
3315     if (ns) {
3316         trace_pci_nvme_flush_ns(iocb->nsid);
3317 
3318         iocb->ns = NULL;
3319         iocb->aiocb = blk_aio_flush(ns->blkconf.blk, nvme_flush_ns_cb, iocb);
3320         return;
3321     }
3322 
3323 out:
3324     nvme_do_flush(iocb);
3325 }
3326 
3327 static void nvme_do_flush(NvmeFlushAIOCB *iocb)
3328 {
3329     NvmeRequest *req = iocb->req;
3330     NvmeCtrl *n = nvme_ctrl(req);
3331     int i;
3332 
3333     if (iocb->ret < 0) {
3334         goto done;
3335     }
3336 
3337     if (iocb->broadcast) {
3338         for (i = iocb->nsid + 1; i <= NVME_MAX_NAMESPACES; i++) {
3339             iocb->ns = nvme_ns(n, i);
3340             if (iocb->ns) {
3341                 iocb->nsid = i;
3342                 break;
3343             }
3344         }
3345     }
3346 
3347     if (!iocb->ns) {
3348         goto done;
3349     }
3350 
3351     nvme_flush_ns_cb(iocb, 0);
3352     return;
3353 
3354 done:
3355     iocb->common.cb(iocb->common.opaque, iocb->ret);
3356     qemu_aio_unref(iocb);
3357 }
3358 
3359 static uint16_t nvme_flush(NvmeCtrl *n, NvmeRequest *req)
3360 {
3361     NvmeFlushAIOCB *iocb;
3362     uint32_t nsid = le32_to_cpu(req->cmd.nsid);
3363     uint16_t status;
3364 
3365     iocb = qemu_aio_get(&nvme_flush_aiocb_info, NULL, nvme_misc_cb, req);
3366 
3367     iocb->req = req;
3368     iocb->ret = 0;
3369     iocb->ns = NULL;
3370     iocb->nsid = 0;
3371     iocb->broadcast = (nsid == NVME_NSID_BROADCAST);
3372 
3373     if (!iocb->broadcast) {
3374         if (!nvme_nsid_valid(n, nsid)) {
3375             status = NVME_INVALID_NSID | NVME_DNR;
3376             goto out;
3377         }
3378 
3379         iocb->ns = nvme_ns(n, nsid);
3380         if (!iocb->ns) {
3381             status = NVME_INVALID_FIELD | NVME_DNR;
3382             goto out;
3383         }
3384 
3385         iocb->nsid = nsid;
3386     }
3387 
3388     req->aiocb = &iocb->common;
3389     nvme_do_flush(iocb);
3390 
3391     return NVME_NO_COMPLETE;
3392 
3393 out:
3394     qemu_aio_unref(iocb);
3395 
3396     return status;
3397 }
3398 
3399 static uint16_t nvme_read(NvmeCtrl *n, NvmeRequest *req)
3400 {
3401     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3402     NvmeNamespace *ns = req->ns;
3403     uint64_t slba = le64_to_cpu(rw->slba);
3404     uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
3405     uint8_t prinfo = NVME_RW_PRINFO(le16_to_cpu(rw->control));
3406     uint64_t data_size = nvme_l2b(ns, nlb);
3407     uint64_t mapped_size = data_size;
3408     uint64_t data_offset;
3409     BlockBackend *blk = ns->blkconf.blk;
3410     uint16_t status;
3411 
3412     if (nvme_ns_ext(ns)) {
3413         mapped_size += nvme_m2b(ns, nlb);
3414 
3415         if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3416             bool pract = prinfo & NVME_PRINFO_PRACT;
3417 
3418             if (pract && ns->lbaf.ms == nvme_pi_tuple_size(ns)) {
3419                 mapped_size = data_size;
3420             }
3421         }
3422     }
3423 
3424     trace_pci_nvme_read(nvme_cid(req), nvme_nsid(ns), nlb, mapped_size, slba);
3425 
3426     status = nvme_check_mdts(n, mapped_size);
3427     if (status) {
3428         goto invalid;
3429     }
3430 
3431     status = nvme_check_bounds(ns, slba, nlb);
3432     if (status) {
3433         goto invalid;
3434     }
3435 
3436     if (ns->params.zoned) {
3437         status = nvme_check_zone_read(ns, slba, nlb);
3438         if (status) {
3439             trace_pci_nvme_err_zone_read_not_ok(slba, nlb, status);
3440             goto invalid;
3441         }
3442     }
3443 
3444     if (NVME_ERR_REC_DULBE(ns->features.err_rec)) {
3445         status = nvme_check_dulbe(ns, slba, nlb);
3446         if (status) {
3447             goto invalid;
3448         }
3449     }
3450 
3451     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3452         return nvme_dif_rw(n, req);
3453     }
3454 
3455     status = nvme_map_data(n, nlb, req);
3456     if (status) {
3457         goto invalid;
3458     }
3459 
3460     data_offset = nvme_l2b(ns, slba);
3461 
3462     block_acct_start(blk_get_stats(blk), &req->acct, data_size,
3463                      BLOCK_ACCT_READ);
3464     nvme_blk_read(blk, data_offset, BDRV_SECTOR_SIZE, nvme_rw_cb, req);
3465     return NVME_NO_COMPLETE;
3466 
3467 invalid:
3468     block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_READ);
3469     return status | NVME_DNR;
3470 }
3471 
3472 static void nvme_do_write_fdp(NvmeCtrl *n, NvmeRequest *req, uint64_t slba,
3473                               uint32_t nlb)
3474 {
3475     NvmeNamespace *ns = req->ns;
3476     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3477     uint64_t data_size = nvme_l2b(ns, nlb);
3478     uint32_t dw12 = le32_to_cpu(req->cmd.cdw12);
3479     uint8_t dtype = (dw12 >> 20) & 0xf;
3480     uint16_t pid = le16_to_cpu(rw->dspec);
3481     uint16_t ph, rg, ruhid;
3482     NvmeReclaimUnit *ru;
3483 
3484     if (dtype != NVME_DIRECTIVE_DATA_PLACEMENT ||
3485         !nvme_parse_pid(ns, pid, &ph, &rg)) {
3486         ph = 0;
3487         rg = 0;
3488     }
3489 
3490     ruhid = ns->fdp.phs[ph];
3491     ru = &ns->endgrp->fdp.ruhs[ruhid].rus[rg];
3492 
3493     nvme_fdp_stat_inc(&ns->endgrp->fdp.hbmw, data_size);
3494     nvme_fdp_stat_inc(&ns->endgrp->fdp.mbmw, data_size);
3495 
3496     while (nlb) {
3497         if (nlb < ru->ruamw) {
3498             ru->ruamw -= nlb;
3499             break;
3500         }
3501 
3502         nlb -= ru->ruamw;
3503         nvme_update_ruh(n, ns, pid);
3504     }
3505 }
3506 
3507 static uint16_t nvme_do_write(NvmeCtrl *n, NvmeRequest *req, bool append,
3508                               bool wrz)
3509 {
3510     NvmeRwCmd *rw = (NvmeRwCmd *)&req->cmd;
3511     NvmeNamespace *ns = req->ns;
3512     uint64_t slba = le64_to_cpu(rw->slba);
3513     uint32_t nlb = (uint32_t)le16_to_cpu(rw->nlb) + 1;
3514     uint16_t ctrl = le16_to_cpu(rw->control);
3515     uint8_t prinfo = NVME_RW_PRINFO(ctrl);
3516     uint64_t data_size = nvme_l2b(ns, nlb);
3517     uint64_t mapped_size = data_size;
3518     uint64_t data_offset;
3519     NvmeZone *zone;
3520     NvmeZonedResult *res = (NvmeZonedResult *)&req->cqe;
3521     BlockBackend *blk = ns->blkconf.blk;
3522     uint16_t status;
3523 
3524     if (nvme_ns_ext(ns)) {
3525         mapped_size += nvme_m2b(ns, nlb);
3526 
3527         if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3528             bool pract = prinfo & NVME_PRINFO_PRACT;
3529 
3530             if (pract && ns->lbaf.ms == nvme_pi_tuple_size(ns)) {
3531                 mapped_size -= nvme_m2b(ns, nlb);
3532             }
3533         }
3534     }
3535 
3536     trace_pci_nvme_write(nvme_cid(req), nvme_io_opc_str(rw->opcode),
3537                          nvme_nsid(ns), nlb, mapped_size, slba);
3538 
3539     if (!wrz) {
3540         status = nvme_check_mdts(n, mapped_size);
3541         if (status) {
3542             goto invalid;
3543         }
3544     }
3545 
3546     status = nvme_check_bounds(ns, slba, nlb);
3547     if (status) {
3548         goto invalid;
3549     }
3550 
3551     if (ns->params.zoned) {
3552         zone = nvme_get_zone_by_slba(ns, slba);
3553         assert(zone);
3554 
3555         if (append) {
3556             bool piremap = !!(ctrl & NVME_RW_PIREMAP);
3557 
3558             if (unlikely(zone->d.za & NVME_ZA_ZRWA_VALID)) {
3559                 return NVME_INVALID_ZONE_OP | NVME_DNR;
3560             }
3561 
3562             if (unlikely(slba != zone->d.zslba)) {
3563                 trace_pci_nvme_err_append_not_at_start(slba, zone->d.zslba);
3564                 status = NVME_INVALID_FIELD;
3565                 goto invalid;
3566             }
3567 
3568             if (n->params.zasl &&
3569                 data_size > (uint64_t)n->page_size << n->params.zasl) {
3570                 trace_pci_nvme_err_zasl(data_size);
3571                 return NVME_INVALID_FIELD | NVME_DNR;
3572             }
3573 
3574             slba = zone->w_ptr;
3575             rw->slba = cpu_to_le64(slba);
3576             res->slba = cpu_to_le64(slba);
3577 
3578             switch (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3579             case NVME_ID_NS_DPS_TYPE_1:
3580                 if (!piremap) {
3581                     return NVME_INVALID_PROT_INFO | NVME_DNR;
3582                 }
3583 
3584                 /* fallthrough */
3585 
3586             case NVME_ID_NS_DPS_TYPE_2:
3587                 if (piremap) {
3588                     uint32_t reftag = le32_to_cpu(rw->reftag);
3589                     rw->reftag = cpu_to_le32(reftag + (slba - zone->d.zslba));
3590                 }
3591 
3592                 break;
3593 
3594             case NVME_ID_NS_DPS_TYPE_3:
3595                 if (piremap) {
3596                     return NVME_INVALID_PROT_INFO | NVME_DNR;
3597                 }
3598 
3599                 break;
3600             }
3601         }
3602 
3603         status = nvme_check_zone_write(ns, zone, slba, nlb);
3604         if (status) {
3605             goto invalid;
3606         }
3607 
3608         status = nvme_zrm_auto(n, ns, zone);
3609         if (status) {
3610             goto invalid;
3611         }
3612 
3613         if (!(zone->d.za & NVME_ZA_ZRWA_VALID)) {
3614             zone->w_ptr += nlb;
3615         }
3616     } else if (ns->endgrp && ns->endgrp->fdp.enabled) {
3617         nvme_do_write_fdp(n, req, slba, nlb);
3618     }
3619 
3620     data_offset = nvme_l2b(ns, slba);
3621 
3622     if (NVME_ID_NS_DPS_TYPE(ns->id_ns.dps)) {
3623         return nvme_dif_rw(n, req);
3624     }
3625 
3626     if (!wrz) {
3627         status = nvme_map_data(n, nlb, req);
3628         if (status) {
3629             goto invalid;
3630         }
3631 
3632         block_acct_start(blk_get_stats(blk), &req->acct, data_size,
3633                          BLOCK_ACCT_WRITE);
3634         nvme_blk_write(blk, data_offset, BDRV_SECTOR_SIZE, nvme_rw_cb, req);
3635     } else {
3636         req->aiocb = blk_aio_pwrite_zeroes(blk, data_offset, data_size,
3637                                            BDRV_REQ_MAY_UNMAP, nvme_rw_cb,
3638                                            req);
3639     }
3640 
3641     return NVME_NO_COMPLETE;
3642 
3643 invalid:
3644     block_acct_invalid(blk_get_stats(blk), BLOCK_ACCT_WRITE);
3645     return status | NVME_DNR;
3646 }
3647 
3648 static inline uint16_t nvme_write(NvmeCtrl *n, NvmeRequest *req)
3649 {
3650     return nvme_do_write(n, req, false, false);
3651 }
3652 
3653 static inline uint16_t nvme_write_zeroes(NvmeCtrl *n, NvmeRequest *req)
3654 {
3655     return nvme_do_write(n, req, false, true);
3656 }
3657 
3658 static inline uint16_t nvme_zone_append(NvmeCtrl *n, NvmeRequest *req)
3659 {
3660     return nvme_do_write(n, req, true, false);
3661 }
3662 
3663 static uint16_t nvme_get_mgmt_zone_slba_idx(NvmeNamespace *ns, NvmeCmd *c,
3664                                             uint64_t *slba, uint32_t *zone_idx)
3665 {
3666     uint32_t dw10 = le32_to_cpu(c->cdw10);
3667     uint32_t dw11 = le32_to_cpu(c->cdw11);
3668 
3669     if (!ns->params.zoned) {
3670         trace_pci_nvme_err_invalid_opc(c->opcode);
3671         return NVME_INVALID_OPCODE | NVME_DNR;
3672     }
3673 
3674     *slba = ((uint64_t)dw11) << 32 | dw10;
3675     if (unlikely(*slba >= ns->id_ns.nsze)) {
3676         trace_pci_nvme_err_invalid_lba_range(*slba, 0, ns->id_ns.nsze);
3677         *slba = 0;
3678         return NVME_LBA_RANGE | NVME_DNR;
3679     }
3680 
3681     *zone_idx = nvme_zone_idx(ns, *slba);
3682     assert(*zone_idx < ns->num_zones);
3683 
3684     return NVME_SUCCESS;
3685 }
3686 
3687 typedef uint16_t (*op_handler_t)(NvmeNamespace *, NvmeZone *, NvmeZoneState,
3688                                  NvmeRequest *);
3689 
3690 enum NvmeZoneProcessingMask {
3691     NVME_PROC_CURRENT_ZONE    = 0,
3692     NVME_PROC_OPENED_ZONES    = 1 << 0,
3693     NVME_PROC_CLOSED_ZONES    = 1 << 1,
3694     NVME_PROC_READ_ONLY_ZONES = 1 << 2,
3695     NVME_PROC_FULL_ZONES      = 1 << 3,
3696 };
3697 
3698 static uint16_t nvme_open_zone(NvmeNamespace *ns, NvmeZone *zone,
3699                                NvmeZoneState state, NvmeRequest *req)
3700 {
3701     NvmeZoneSendCmd *cmd = (NvmeZoneSendCmd *)&req->cmd;
3702     int flags = 0;
3703 
3704     if (cmd->zsflags & NVME_ZSFLAG_ZRWA_ALLOC) {
3705         uint16_t ozcs = le16_to_cpu(ns->id_ns_zoned->ozcs);
3706 
3707         if (!(ozcs & NVME_ID_NS_ZONED_OZCS_ZRWASUP)) {
3708             return NVME_INVALID_ZONE_OP | NVME_DNR;
3709         }
3710 
3711         if (zone->w_ptr % ns->zns.zrwafg) {
3712             return NVME_NOZRWA | NVME_DNR;
3713         }
3714 
3715         flags = NVME_ZRM_ZRWA;
3716     }
3717 
3718     return nvme_zrm_open_flags(nvme_ctrl(req), ns, zone, flags);
3719 }
3720 
3721 static uint16_t nvme_close_zone(NvmeNamespace *ns, NvmeZone *zone,
3722                                 NvmeZoneState state, NvmeRequest *req)
3723 {
3724     return nvme_zrm_close(ns, zone);
3725 }
3726 
3727 static uint16_t nvme_finish_zone(NvmeNamespace *ns, NvmeZone *zone,
3728                                  NvmeZoneState state, NvmeRequest *req)
3729 {
3730     return nvme_zrm_finish(ns, zone);
3731 }
3732 
3733 static uint16_t nvme_offline_zone(NvmeNamespace *ns, NvmeZone *zone,
3734                                   NvmeZoneState state, NvmeRequest *req)
3735 {
3736     switch (state) {
3737     case NVME_ZONE_STATE_READ_ONLY:
3738         nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_OFFLINE);
3739         /* fall through */
3740     case NVME_ZONE_STATE_OFFLINE:
3741         return NVME_SUCCESS;
3742     default:
3743         return NVME_ZONE_INVAL_TRANSITION;
3744     }
3745 }
3746 
3747 static uint16_t nvme_set_zd_ext(NvmeNamespace *ns, NvmeZone *zone)
3748 {
3749     uint16_t status;
3750     uint8_t state = nvme_get_zone_state(zone);
3751 
3752     if (state == NVME_ZONE_STATE_EMPTY) {
3753         status = nvme_aor_check(ns, 1, 0);
3754         if (status) {
3755             return status;
3756         }
3757         nvme_aor_inc_active(ns);
3758         zone->d.za |= NVME_ZA_ZD_EXT_VALID;
3759         nvme_assign_zone_state(ns, zone, NVME_ZONE_STATE_CLOSED);
3760         return NVME_SUCCESS;
3761     }
3762 
3763     return NVME_ZONE_INVAL_TRANSITION;
3764 }
3765 
3766 static uint16_t nvme_bulk_proc_zone(NvmeNamespace *ns, NvmeZone *zone,
3767                                     enum NvmeZoneProcessingMask proc_mask,
3768                                     op_handler_t op_hndlr, NvmeRequest *req)
3769 {
3770     uint16_t status = NVME_SUCCESS;
3771     NvmeZoneState zs = nvme_get_zone_state(zone);
3772     bool proc_zone;
3773 
3774     switch (zs) {
3775     case NVME_ZONE_STATE_IMPLICITLY_OPEN:
3776     case NVME_ZONE_STATE_EXPLICITLY_OPEN:
3777         proc_zone = proc_mask & NVME_PROC_OPENED_ZONES;
3778         break;
3779     case NVME_ZONE_STATE_CLOSED:
3780         proc_zone = proc_mask & NVME_PROC_CLOSED_ZONES;
3781         break;
3782     case NVME_ZONE_STATE_READ_ONLY:
3783         proc_zone = proc_mask & NVME_PROC_READ_ONLY_ZONES;
3784         break;
3785     case NVME_ZONE_STATE_FULL:
3786         proc_zone = proc_mask & NVME_PROC_FULL_ZONES;
3787         break;
3788     default:
3789         proc_zone = false;
3790     }
3791 
3792     if (proc_zone) {
3793         status = op_hndlr(ns, zone, zs, req);
3794     }
3795 
3796     return status;
3797 }
3798 
3799 static uint16_t nvme_do_zone_op(NvmeNamespace *ns, NvmeZone *zone,
3800                                 enum NvmeZoneProcessingMask proc_mask,
3801                                 op_handler_t op_hndlr, NvmeRequest *req)
3802 {
3803     NvmeZone *next;
3804     uint16_t status = NVME_SUCCESS;
3805     int i;
3806 
3807     if (!proc_mask) {
3808         status = op_hndlr(ns, zone, nvme_get_zone_state(zone), req);
3809     } else {
3810         if (proc_mask & NVME_PROC_CLOSED_ZONES) {
3811             QTAILQ_FOREACH_SAFE(zone, &ns->closed_zones, entry, next) {
3812                 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3813                                              req);
3814                 if (status && status != NVME_NO_COMPLETE) {
3815                     goto out;
3816                 }
3817             }
3818         }
3819         if (proc_mask & NVME_PROC_OPENED_ZONES) {
3820             QTAILQ_FOREACH_SAFE(zone, &ns->imp_open_zones, entry, next) {
3821                 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3822                                              req);
3823                 if (status && status != NVME_NO_COMPLETE) {
3824                     goto out;
3825                 }
3826             }
3827 
3828             QTAILQ_FOREACH_SAFE(zone, &ns->exp_open_zones, entry, next) {
3829                 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3830                                              req);
3831                 if (status && status != NVME_NO_COMPLETE) {
3832                     goto out;
3833                 }
3834             }
3835         }
3836         if (proc_mask & NVME_PROC_FULL_ZONES) {
3837             QTAILQ_FOREACH_SAFE(zone, &ns->full_zones, entry, next) {
3838                 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3839                                              req);
3840                 if (status && status != NVME_NO_COMPLETE) {
3841                     goto out;
3842                 }
3843             }
3844         }
3845 
3846         if (proc_mask & NVME_PROC_READ_ONLY_ZONES) {
3847             for (i = 0; i < ns->num_zones; i++, zone++) {
3848                 status = nvme_bulk_proc_zone(ns, zone, proc_mask, op_hndlr,
3849                                              req);
3850                 if (status && status != NVME_NO_COMPLETE) {
3851                     goto out;
3852                 }
3853             }
3854         }
3855     }
3856 
3857 out:
3858     return status;
3859 }
3860 
3861 typedef struct NvmeZoneResetAIOCB {
3862     BlockAIOCB common;
3863     BlockAIOCB *aiocb;
3864     NvmeRequest *req;
3865     int ret;
3866 
3867     bool all;
3868     int idx;
3869     NvmeZone *zone;
3870 } NvmeZoneResetAIOCB;
3871 
3872 static void nvme_zone_reset_cancel(BlockAIOCB *aiocb)
3873 {
3874     NvmeZoneResetAIOCB *iocb = container_of(aiocb, NvmeZoneResetAIOCB, common);
3875     NvmeRequest *req = iocb->req;
3876     NvmeNamespace *ns = req->ns;
3877 
3878     iocb->idx = ns->num_zones;
3879 
3880     iocb->ret = -ECANCELED;
3881 
3882     if (iocb->aiocb) {
3883         blk_aio_cancel_async(iocb->aiocb);
3884         iocb->aiocb = NULL;
3885     }
3886 }
3887 
3888 static const AIOCBInfo nvme_zone_reset_aiocb_info = {
3889     .aiocb_size = sizeof(NvmeZoneResetAIOCB),
3890     .cancel_async = nvme_zone_reset_cancel,
3891 };
3892 
3893 static void nvme_zone_reset_cb(void *opaque, int ret);
3894 
3895 static void nvme_zone_reset_epilogue_cb(void *opaque, int ret)
3896 {
3897     NvmeZoneResetAIOCB *iocb = opaque;
3898     NvmeRequest *req = iocb->req;
3899     NvmeNamespace *ns = req->ns;
3900     int64_t moff;
3901     int count;
3902 
3903     if (ret < 0 || iocb->ret < 0 || !ns->lbaf.ms) {
3904         goto out;
3905     }
3906 
3907     moff = nvme_moff(ns, iocb->zone->d.zslba);
3908     count = nvme_m2b(ns, ns->zone_size);
3909 
3910     iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, moff, count,
3911                                         BDRV_REQ_MAY_UNMAP,
3912                                         nvme_zone_reset_cb, iocb);
3913     return;
3914 
3915 out:
3916     nvme_zone_reset_cb(iocb, ret);
3917 }
3918 
3919 static void nvme_zone_reset_cb(void *opaque, int ret)
3920 {
3921     NvmeZoneResetAIOCB *iocb = opaque;
3922     NvmeRequest *req = iocb->req;
3923     NvmeNamespace *ns = req->ns;
3924 
3925     if (iocb->ret < 0) {
3926         goto done;
3927     } else if (ret < 0) {
3928         iocb->ret = ret;
3929         goto done;
3930     }
3931 
3932     if (iocb->zone) {
3933         nvme_zrm_reset(ns, iocb->zone);
3934 
3935         if (!iocb->all) {
3936             goto done;
3937         }
3938     }
3939 
3940     while (iocb->idx < ns->num_zones) {
3941         NvmeZone *zone = &ns->zone_array[iocb->idx++];
3942 
3943         switch (nvme_get_zone_state(zone)) {
3944         case NVME_ZONE_STATE_EMPTY:
3945             if (!iocb->all) {
3946                 goto done;
3947             }
3948 
3949             continue;
3950 
3951         case NVME_ZONE_STATE_EXPLICITLY_OPEN:
3952         case NVME_ZONE_STATE_IMPLICITLY_OPEN:
3953         case NVME_ZONE_STATE_CLOSED:
3954         case NVME_ZONE_STATE_FULL:
3955             iocb->zone = zone;
3956             break;
3957 
3958         default:
3959             continue;
3960         }
3961 
3962         trace_pci_nvme_zns_zone_reset(zone->d.zslba);
3963 
3964         iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk,
3965                                             nvme_l2b(ns, zone->d.zslba),
3966                                             nvme_l2b(ns, ns->zone_size),
3967                                             BDRV_REQ_MAY_UNMAP,
3968                                             nvme_zone_reset_epilogue_cb,
3969                                             iocb);
3970         return;
3971     }
3972 
3973 done:
3974     iocb->aiocb = NULL;
3975 
3976     iocb->common.cb(iocb->common.opaque, iocb->ret);
3977     qemu_aio_unref(iocb);
3978 }
3979 
3980 static uint16_t nvme_zone_mgmt_send_zrwa_flush(NvmeCtrl *n, NvmeZone *zone,
3981                                                uint64_t elba, NvmeRequest *req)
3982 {
3983     NvmeNamespace *ns = req->ns;
3984     uint16_t ozcs = le16_to_cpu(ns->id_ns_zoned->ozcs);
3985     uint64_t wp = zone->d.wp;
3986     uint32_t nlb = elba - wp + 1;
3987     uint16_t status;
3988 
3989 
3990     if (!(ozcs & NVME_ID_NS_ZONED_OZCS_ZRWASUP)) {
3991         return NVME_INVALID_ZONE_OP | NVME_DNR;
3992     }
3993 
3994     if (!(zone->d.za & NVME_ZA_ZRWA_VALID)) {
3995         return NVME_INVALID_FIELD | NVME_DNR;
3996     }
3997 
3998     if (elba < wp || elba > wp + ns->zns.zrwas) {
3999         return NVME_ZONE_BOUNDARY_ERROR | NVME_DNR;
4000     }
4001 
4002     if (nlb % ns->zns.zrwafg) {
4003         return NVME_INVALID_FIELD | NVME_DNR;
4004     }
4005 
4006     status = nvme_zrm_auto(n, ns, zone);
4007     if (status) {
4008         return status;
4009     }
4010 
4011     zone->w_ptr += nlb;
4012 
4013     nvme_advance_zone_wp(ns, zone, nlb);
4014 
4015     return NVME_SUCCESS;
4016 }
4017 
4018 static uint16_t nvme_zone_mgmt_send(NvmeCtrl *n, NvmeRequest *req)
4019 {
4020     NvmeZoneSendCmd *cmd = (NvmeZoneSendCmd *)&req->cmd;
4021     NvmeNamespace *ns = req->ns;
4022     NvmeZone *zone;
4023     NvmeZoneResetAIOCB *iocb;
4024     uint8_t *zd_ext;
4025     uint64_t slba = 0;
4026     uint32_t zone_idx = 0;
4027     uint16_t status;
4028     uint8_t action = cmd->zsa;
4029     bool all;
4030     enum NvmeZoneProcessingMask proc_mask = NVME_PROC_CURRENT_ZONE;
4031 
4032     all = cmd->zsflags & NVME_ZSFLAG_SELECT_ALL;
4033 
4034     req->status = NVME_SUCCESS;
4035 
4036     if (!all) {
4037         status = nvme_get_mgmt_zone_slba_idx(ns, &req->cmd, &slba, &zone_idx);
4038         if (status) {
4039             return status;
4040         }
4041     }
4042 
4043     zone = &ns->zone_array[zone_idx];
4044     if (slba != zone->d.zslba && action != NVME_ZONE_ACTION_ZRWA_FLUSH) {
4045         trace_pci_nvme_err_unaligned_zone_cmd(action, slba, zone->d.zslba);
4046         return NVME_INVALID_FIELD | NVME_DNR;
4047     }
4048 
4049     switch (action) {
4050 
4051     case NVME_ZONE_ACTION_OPEN:
4052         if (all) {
4053             proc_mask = NVME_PROC_CLOSED_ZONES;
4054         }
4055         trace_pci_nvme_open_zone(slba, zone_idx, all);
4056         status = nvme_do_zone_op(ns, zone, proc_mask, nvme_open_zone, req);
4057         break;
4058 
4059     case NVME_ZONE_ACTION_CLOSE:
4060         if (all) {
4061             proc_mask = NVME_PROC_OPENED_ZONES;
4062         }
4063         trace_pci_nvme_close_zone(slba, zone_idx, all);
4064         status = nvme_do_zone_op(ns, zone, proc_mask, nvme_close_zone, req);
4065         break;
4066 
4067     case NVME_ZONE_ACTION_FINISH:
4068         if (all) {
4069             proc_mask = NVME_PROC_OPENED_ZONES | NVME_PROC_CLOSED_ZONES;
4070         }
4071         trace_pci_nvme_finish_zone(slba, zone_idx, all);
4072         status = nvme_do_zone_op(ns, zone, proc_mask, nvme_finish_zone, req);
4073         break;
4074 
4075     case NVME_ZONE_ACTION_RESET:
4076         trace_pci_nvme_reset_zone(slba, zone_idx, all);
4077 
4078         iocb = blk_aio_get(&nvme_zone_reset_aiocb_info, ns->blkconf.blk,
4079                            nvme_misc_cb, req);
4080 
4081         iocb->req = req;
4082         iocb->ret = 0;
4083         iocb->all = all;
4084         iocb->idx = zone_idx;
4085         iocb->zone = NULL;
4086 
4087         req->aiocb = &iocb->common;
4088         nvme_zone_reset_cb(iocb, 0);
4089 
4090         return NVME_NO_COMPLETE;
4091 
4092     case NVME_ZONE_ACTION_OFFLINE:
4093         if (all) {
4094             proc_mask = NVME_PROC_READ_ONLY_ZONES;
4095         }
4096         trace_pci_nvme_offline_zone(slba, zone_idx, all);
4097         status = nvme_do_zone_op(ns, zone, proc_mask, nvme_offline_zone, req);
4098         break;
4099 
4100     case NVME_ZONE_ACTION_SET_ZD_EXT:
4101         trace_pci_nvme_set_descriptor_extension(slba, zone_idx);
4102         if (all || !ns->params.zd_extension_size) {
4103             return NVME_INVALID_FIELD | NVME_DNR;
4104         }
4105         zd_ext = nvme_get_zd_extension(ns, zone_idx);
4106         status = nvme_h2c(n, zd_ext, ns->params.zd_extension_size, req);
4107         if (status) {
4108             trace_pci_nvme_err_zd_extension_map_error(zone_idx);
4109             return status;
4110         }
4111 
4112         status = nvme_set_zd_ext(ns, zone);
4113         if (status == NVME_SUCCESS) {
4114             trace_pci_nvme_zd_extension_set(zone_idx);
4115             return status;
4116         }
4117         break;
4118 
4119     case NVME_ZONE_ACTION_ZRWA_FLUSH:
4120         if (all) {
4121             return NVME_INVALID_FIELD | NVME_DNR;
4122         }
4123 
4124         return nvme_zone_mgmt_send_zrwa_flush(n, zone, slba, req);
4125 
4126     default:
4127         trace_pci_nvme_err_invalid_mgmt_action(action);
4128         status = NVME_INVALID_FIELD;
4129     }
4130 
4131     if (status == NVME_ZONE_INVAL_TRANSITION) {
4132         trace_pci_nvme_err_invalid_zone_state_transition(action, slba,
4133                                                          zone->d.za);
4134     }
4135     if (status) {
4136         status |= NVME_DNR;
4137     }
4138 
4139     return status;
4140 }
4141 
4142 static bool nvme_zone_matches_filter(uint32_t zafs, NvmeZone *zl)
4143 {
4144     NvmeZoneState zs = nvme_get_zone_state(zl);
4145 
4146     switch (zafs) {
4147     case NVME_ZONE_REPORT_ALL:
4148         return true;
4149     case NVME_ZONE_REPORT_EMPTY:
4150         return zs == NVME_ZONE_STATE_EMPTY;
4151     case NVME_ZONE_REPORT_IMPLICITLY_OPEN:
4152         return zs == NVME_ZONE_STATE_IMPLICITLY_OPEN;
4153     case NVME_ZONE_REPORT_EXPLICITLY_OPEN:
4154         return zs == NVME_ZONE_STATE_EXPLICITLY_OPEN;
4155     case NVME_ZONE_REPORT_CLOSED:
4156         return zs == NVME_ZONE_STATE_CLOSED;
4157     case NVME_ZONE_REPORT_FULL:
4158         return zs == NVME_ZONE_STATE_FULL;
4159     case NVME_ZONE_REPORT_READ_ONLY:
4160         return zs == NVME_ZONE_STATE_READ_ONLY;
4161     case NVME_ZONE_REPORT_OFFLINE:
4162         return zs == NVME_ZONE_STATE_OFFLINE;
4163     default:
4164         return false;
4165     }
4166 }
4167 
4168 static uint16_t nvme_zone_mgmt_recv(NvmeCtrl *n, NvmeRequest *req)
4169 {
4170     NvmeCmd *cmd = (NvmeCmd *)&req->cmd;
4171     NvmeNamespace *ns = req->ns;
4172     /* cdw12 is zero-based number of dwords to return. Convert to bytes */
4173     uint32_t data_size = (le32_to_cpu(cmd->cdw12) + 1) << 2;
4174     uint32_t dw13 = le32_to_cpu(cmd->cdw13);
4175     uint32_t zone_idx, zra, zrasf, partial;
4176     uint64_t max_zones, nr_zones = 0;
4177     uint16_t status;
4178     uint64_t slba;
4179     NvmeZoneDescr *z;
4180     NvmeZone *zone;
4181     NvmeZoneReportHeader *header;
4182     void *buf, *buf_p;
4183     size_t zone_entry_sz;
4184     int i;
4185 
4186     req->status = NVME_SUCCESS;
4187 
4188     status = nvme_get_mgmt_zone_slba_idx(ns, cmd, &slba, &zone_idx);
4189     if (status) {
4190         return status;
4191     }
4192 
4193     zra = dw13 & 0xff;
4194     if (zra != NVME_ZONE_REPORT && zra != NVME_ZONE_REPORT_EXTENDED) {
4195         return NVME_INVALID_FIELD | NVME_DNR;
4196     }
4197     if (zra == NVME_ZONE_REPORT_EXTENDED && !ns->params.zd_extension_size) {
4198         return NVME_INVALID_FIELD | NVME_DNR;
4199     }
4200 
4201     zrasf = (dw13 >> 8) & 0xff;
4202     if (zrasf > NVME_ZONE_REPORT_OFFLINE) {
4203         return NVME_INVALID_FIELD | NVME_DNR;
4204     }
4205 
4206     if (data_size < sizeof(NvmeZoneReportHeader)) {
4207         return NVME_INVALID_FIELD | NVME_DNR;
4208     }
4209 
4210     status = nvme_check_mdts(n, data_size);
4211     if (status) {
4212         return status;
4213     }
4214 
4215     partial = (dw13 >> 16) & 0x01;
4216 
4217     zone_entry_sz = sizeof(NvmeZoneDescr);
4218     if (zra == NVME_ZONE_REPORT_EXTENDED) {
4219         zone_entry_sz += ns->params.zd_extension_size;
4220     }
4221 
4222     max_zones = (data_size - sizeof(NvmeZoneReportHeader)) / zone_entry_sz;
4223     buf = g_malloc0(data_size);
4224 
4225     zone = &ns->zone_array[zone_idx];
4226     for (i = zone_idx; i < ns->num_zones; i++) {
4227         if (partial && nr_zones >= max_zones) {
4228             break;
4229         }
4230         if (nvme_zone_matches_filter(zrasf, zone++)) {
4231             nr_zones++;
4232         }
4233     }
4234     header = buf;
4235     header->nr_zones = cpu_to_le64(nr_zones);
4236 
4237     buf_p = buf + sizeof(NvmeZoneReportHeader);
4238     for (; zone_idx < ns->num_zones && max_zones > 0; zone_idx++) {
4239         zone = &ns->zone_array[zone_idx];
4240         if (nvme_zone_matches_filter(zrasf, zone)) {
4241             z = buf_p;
4242             buf_p += sizeof(NvmeZoneDescr);
4243 
4244             z->zt = zone->d.zt;
4245             z->zs = zone->d.zs;
4246             z->zcap = cpu_to_le64(zone->d.zcap);
4247             z->zslba = cpu_to_le64(zone->d.zslba);
4248             z->za = zone->d.za;
4249 
4250             if (nvme_wp_is_valid(zone)) {
4251                 z->wp = cpu_to_le64(zone->d.wp);
4252             } else {
4253                 z->wp = cpu_to_le64(~0ULL);
4254             }
4255 
4256             if (zra == NVME_ZONE_REPORT_EXTENDED) {
4257                 if (zone->d.za & NVME_ZA_ZD_EXT_VALID) {
4258                     memcpy(buf_p, nvme_get_zd_extension(ns, zone_idx),
4259                            ns->params.zd_extension_size);
4260                 }
4261                 buf_p += ns->params.zd_extension_size;
4262             }
4263 
4264             max_zones--;
4265         }
4266     }
4267 
4268     status = nvme_c2h(n, (uint8_t *)buf, data_size, req);
4269 
4270     g_free(buf);
4271 
4272     return status;
4273 }
4274 
4275 static uint16_t nvme_io_mgmt_recv_ruhs(NvmeCtrl *n, NvmeRequest *req,
4276                                        size_t len)
4277 {
4278     NvmeNamespace *ns = req->ns;
4279     NvmeEnduranceGroup *endgrp;
4280     NvmeRuhStatus *hdr;
4281     NvmeRuhStatusDescr *ruhsd;
4282     unsigned int nruhsd;
4283     uint16_t rg, ph, *ruhid;
4284     size_t trans_len;
4285     g_autofree uint8_t *buf = NULL;
4286 
4287     if (!n->subsys) {
4288         return NVME_INVALID_FIELD | NVME_DNR;
4289     }
4290 
4291     if (ns->params.nsid == 0 || ns->params.nsid == 0xffffffff) {
4292         return NVME_INVALID_NSID | NVME_DNR;
4293     }
4294 
4295     if (!n->subsys->endgrp.fdp.enabled) {
4296         return NVME_FDP_DISABLED | NVME_DNR;
4297     }
4298 
4299     endgrp = ns->endgrp;
4300 
4301     nruhsd = ns->fdp.nphs * endgrp->fdp.nrg;
4302     trans_len = sizeof(NvmeRuhStatus) + nruhsd * sizeof(NvmeRuhStatusDescr);
4303     buf = g_malloc(trans_len);
4304 
4305     trans_len = MIN(trans_len, len);
4306 
4307     hdr = (NvmeRuhStatus *)buf;
4308     ruhsd = (NvmeRuhStatusDescr *)(buf + sizeof(NvmeRuhStatus));
4309 
4310     hdr->nruhsd = cpu_to_le16(nruhsd);
4311 
4312     ruhid = ns->fdp.phs;
4313 
4314     for (ph = 0; ph < ns->fdp.nphs; ph++, ruhid++) {
4315         NvmeRuHandle *ruh = &endgrp->fdp.ruhs[*ruhid];
4316 
4317         for (rg = 0; rg < endgrp->fdp.nrg; rg++, ruhsd++) {
4318             uint16_t pid = nvme_make_pid(ns, rg, ph);
4319 
4320             ruhsd->pid = cpu_to_le16(pid);
4321             ruhsd->ruhid = *ruhid;
4322             ruhsd->earutr = 0;
4323             ruhsd->ruamw = cpu_to_le64(ruh->rus[rg].ruamw);
4324         }
4325     }
4326 
4327     return nvme_c2h(n, buf, trans_len, req);
4328 }
4329 
4330 static uint16_t nvme_io_mgmt_recv(NvmeCtrl *n, NvmeRequest *req)
4331 {
4332     NvmeCmd *cmd = &req->cmd;
4333     uint32_t cdw10 = le32_to_cpu(cmd->cdw10);
4334     uint32_t numd = le32_to_cpu(cmd->cdw11);
4335     uint8_t mo = (cdw10 & 0xff);
4336     size_t len = (numd + 1) << 2;
4337 
4338     switch (mo) {
4339     case NVME_IOMR_MO_NOP:
4340         return 0;
4341     case NVME_IOMR_MO_RUH_STATUS:
4342         return nvme_io_mgmt_recv_ruhs(n, req, len);
4343     default:
4344         return NVME_INVALID_FIELD | NVME_DNR;
4345     };
4346 }
4347 
4348 static uint16_t nvme_io_mgmt_send_ruh_update(NvmeCtrl *n, NvmeRequest *req)
4349 {
4350     NvmeCmd *cmd = &req->cmd;
4351     NvmeNamespace *ns = req->ns;
4352     uint32_t cdw10 = le32_to_cpu(cmd->cdw10);
4353     uint16_t ret = NVME_SUCCESS;
4354     uint32_t npid = (cdw10 >> 16) + 1;
4355     unsigned int i = 0;
4356     g_autofree uint16_t *pids = NULL;
4357     uint32_t maxnpid;
4358 
4359     if (!ns->endgrp || !ns->endgrp->fdp.enabled) {
4360         return NVME_FDP_DISABLED | NVME_DNR;
4361     }
4362 
4363     maxnpid = n->subsys->endgrp.fdp.nrg * n->subsys->endgrp.fdp.nruh;
4364 
4365     if (unlikely(npid >= MIN(NVME_FDP_MAXPIDS, maxnpid))) {
4366         return NVME_INVALID_FIELD | NVME_DNR;
4367     }
4368 
4369     pids = g_new(uint16_t, npid);
4370 
4371     ret = nvme_h2c(n, pids, npid * sizeof(uint16_t), req);
4372     if (ret) {
4373         return ret;
4374     }
4375 
4376     for (; i < npid; i++) {
4377         if (!nvme_update_ruh(n, ns, pids[i])) {
4378             return NVME_INVALID_FIELD | NVME_DNR;
4379         }
4380     }
4381 
4382     return ret;
4383 }
4384 
4385 static uint16_t nvme_io_mgmt_send(NvmeCtrl *n, NvmeRequest *req)
4386 {
4387     NvmeCmd *cmd = &req->cmd;
4388     uint32_t cdw10 = le32_to_cpu(cmd->cdw10);
4389     uint8_t mo = (cdw10 & 0xff);
4390 
4391     switch (mo) {
4392     case NVME_IOMS_MO_NOP:
4393         return 0;
4394     case NVME_IOMS_MO_RUH_UPDATE:
4395         return nvme_io_mgmt_send_ruh_update(n, req);
4396     default:
4397         return NVME_INVALID_FIELD | NVME_DNR;
4398     };
4399 }
4400 
4401 static uint16_t nvme_io_cmd(NvmeCtrl *n, NvmeRequest *req)
4402 {
4403     NvmeNamespace *ns;
4404     uint32_t nsid = le32_to_cpu(req->cmd.nsid);
4405 
4406     trace_pci_nvme_io_cmd(nvme_cid(req), nsid, nvme_sqid(req),
4407                           req->cmd.opcode, nvme_io_opc_str(req->cmd.opcode));
4408 
4409     if (!nvme_nsid_valid(n, nsid)) {
4410         return NVME_INVALID_NSID | NVME_DNR;
4411     }
4412 
4413     /*
4414      * In the base NVM command set, Flush may apply to all namespaces
4415      * (indicated by NSID being set to FFFFFFFFh). But if that feature is used
4416      * along with TP 4056 (Namespace Types), it may be pretty screwed up.
4417      *
4418      * If NSID is indeed set to FFFFFFFFh, we simply cannot associate the
4419      * opcode with a specific command since we cannot determine a unique I/O
4420      * command set. Opcode 0h could have any other meaning than something
4421      * equivalent to flushing and say it DOES have completely different
4422      * semantics in some other command set - does an NSID of FFFFFFFFh then
4423      * mean "for all namespaces, apply whatever command set specific command
4424      * that uses the 0h opcode?" Or does it mean "for all namespaces, apply
4425      * whatever command that uses the 0h opcode if, and only if, it allows NSID
4426      * to be FFFFFFFFh"?
4427      *
4428      * Anyway (and luckily), for now, we do not care about this since the
4429      * device only supports namespace types that includes the NVM Flush command
4430      * (NVM and Zoned), so always do an NVM Flush.
4431      */
4432     if (req->cmd.opcode == NVME_CMD_FLUSH) {
4433         return nvme_flush(n, req);
4434     }
4435 
4436     ns = nvme_ns(n, nsid);
4437     if (unlikely(!ns)) {
4438         return NVME_INVALID_FIELD | NVME_DNR;
4439     }
4440 
4441     if (!(ns->iocs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
4442         trace_pci_nvme_err_invalid_opc(req->cmd.opcode);
4443         return NVME_INVALID_OPCODE | NVME_DNR;
4444     }
4445 
4446     if (ns->status) {
4447         return ns->status;
4448     }
4449 
4450     if (NVME_CMD_FLAGS_FUSE(req->cmd.flags)) {
4451         return NVME_INVALID_FIELD;
4452     }
4453 
4454     req->ns = ns;
4455 
4456     switch (req->cmd.opcode) {
4457     case NVME_CMD_WRITE_ZEROES:
4458         return nvme_write_zeroes(n, req);
4459     case NVME_CMD_ZONE_APPEND:
4460         return nvme_zone_append(n, req);
4461     case NVME_CMD_WRITE:
4462         return nvme_write(n, req);
4463     case NVME_CMD_READ:
4464         return nvme_read(n, req);
4465     case NVME_CMD_COMPARE:
4466         return nvme_compare(n, req);
4467     case NVME_CMD_DSM:
4468         return nvme_dsm(n, req);
4469     case NVME_CMD_VERIFY:
4470         return nvme_verify(n, req);
4471     case NVME_CMD_COPY:
4472         return nvme_copy(n, req);
4473     case NVME_CMD_ZONE_MGMT_SEND:
4474         return nvme_zone_mgmt_send(n, req);
4475     case NVME_CMD_ZONE_MGMT_RECV:
4476         return nvme_zone_mgmt_recv(n, req);
4477     case NVME_CMD_IO_MGMT_RECV:
4478         return nvme_io_mgmt_recv(n, req);
4479     case NVME_CMD_IO_MGMT_SEND:
4480         return nvme_io_mgmt_send(n, req);
4481     default:
4482         assert(false);
4483     }
4484 
4485     return NVME_INVALID_OPCODE | NVME_DNR;
4486 }
4487 
4488 static void nvme_cq_notifier(EventNotifier *e)
4489 {
4490     NvmeCQueue *cq = container_of(e, NvmeCQueue, notifier);
4491     NvmeCtrl *n = cq->ctrl;
4492 
4493     if (!event_notifier_test_and_clear(e)) {
4494         return;
4495     }
4496 
4497     nvme_update_cq_head(cq);
4498 
4499     if (cq->tail == cq->head) {
4500         if (cq->irq_enabled) {
4501             n->cq_pending--;
4502         }
4503 
4504         nvme_irq_deassert(n, cq);
4505     }
4506 
4507     qemu_bh_schedule(cq->bh);
4508 }
4509 
4510 static int nvme_init_cq_ioeventfd(NvmeCQueue *cq)
4511 {
4512     NvmeCtrl *n = cq->ctrl;
4513     uint16_t offset = (cq->cqid << 3) + (1 << 2);
4514     int ret;
4515 
4516     ret = event_notifier_init(&cq->notifier, 0);
4517     if (ret < 0) {
4518         return ret;
4519     }
4520 
4521     event_notifier_set_handler(&cq->notifier, nvme_cq_notifier);
4522     memory_region_add_eventfd(&n->iomem,
4523                               0x1000 + offset, 4, false, 0, &cq->notifier);
4524 
4525     return 0;
4526 }
4527 
4528 static void nvme_sq_notifier(EventNotifier *e)
4529 {
4530     NvmeSQueue *sq = container_of(e, NvmeSQueue, notifier);
4531 
4532     if (!event_notifier_test_and_clear(e)) {
4533         return;
4534     }
4535 
4536     nvme_process_sq(sq);
4537 }
4538 
4539 static int nvme_init_sq_ioeventfd(NvmeSQueue *sq)
4540 {
4541     NvmeCtrl *n = sq->ctrl;
4542     uint16_t offset = sq->sqid << 3;
4543     int ret;
4544 
4545     ret = event_notifier_init(&sq->notifier, 0);
4546     if (ret < 0) {
4547         return ret;
4548     }
4549 
4550     event_notifier_set_handler(&sq->notifier, nvme_sq_notifier);
4551     memory_region_add_eventfd(&n->iomem,
4552                               0x1000 + offset, 4, false, 0, &sq->notifier);
4553 
4554     return 0;
4555 }
4556 
4557 static void nvme_free_sq(NvmeSQueue *sq, NvmeCtrl *n)
4558 {
4559     uint16_t offset = sq->sqid << 3;
4560 
4561     n->sq[sq->sqid] = NULL;
4562     qemu_bh_delete(sq->bh);
4563     if (sq->ioeventfd_enabled) {
4564         memory_region_del_eventfd(&n->iomem,
4565                                   0x1000 + offset, 4, false, 0, &sq->notifier);
4566         event_notifier_set_handler(&sq->notifier, NULL);
4567         event_notifier_cleanup(&sq->notifier);
4568     }
4569     g_free(sq->io_req);
4570     if (sq->sqid) {
4571         g_free(sq);
4572     }
4573 }
4574 
4575 static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeRequest *req)
4576 {
4577     NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
4578     NvmeRequest *r, *next;
4579     NvmeSQueue *sq;
4580     NvmeCQueue *cq;
4581     uint16_t qid = le16_to_cpu(c->qid);
4582 
4583     if (unlikely(!qid || nvme_check_sqid(n, qid))) {
4584         trace_pci_nvme_err_invalid_del_sq(qid);
4585         return NVME_INVALID_QID | NVME_DNR;
4586     }
4587 
4588     trace_pci_nvme_del_sq(qid);
4589 
4590     sq = n->sq[qid];
4591     while (!QTAILQ_EMPTY(&sq->out_req_list)) {
4592         r = QTAILQ_FIRST(&sq->out_req_list);
4593         assert(r->aiocb);
4594         blk_aio_cancel(r->aiocb);
4595     }
4596 
4597     assert(QTAILQ_EMPTY(&sq->out_req_list));
4598 
4599     if (!nvme_check_cqid(n, sq->cqid)) {
4600         cq = n->cq[sq->cqid];
4601         QTAILQ_REMOVE(&cq->sq_list, sq, entry);
4602 
4603         nvme_post_cqes(cq);
4604         QTAILQ_FOREACH_SAFE(r, &cq->req_list, entry, next) {
4605             if (r->sq == sq) {
4606                 QTAILQ_REMOVE(&cq->req_list, r, entry);
4607                 QTAILQ_INSERT_TAIL(&sq->req_list, r, entry);
4608             }
4609         }
4610     }
4611 
4612     nvme_free_sq(sq, n);
4613     return NVME_SUCCESS;
4614 }
4615 
4616 static void nvme_init_sq(NvmeSQueue *sq, NvmeCtrl *n, uint64_t dma_addr,
4617                          uint16_t sqid, uint16_t cqid, uint16_t size)
4618 {
4619     int i;
4620     NvmeCQueue *cq;
4621 
4622     sq->ctrl = n;
4623     sq->dma_addr = dma_addr;
4624     sq->sqid = sqid;
4625     sq->size = size;
4626     sq->cqid = cqid;
4627     sq->head = sq->tail = 0;
4628     sq->io_req = g_new0(NvmeRequest, sq->size);
4629 
4630     QTAILQ_INIT(&sq->req_list);
4631     QTAILQ_INIT(&sq->out_req_list);
4632     for (i = 0; i < sq->size; i++) {
4633         sq->io_req[i].sq = sq;
4634         QTAILQ_INSERT_TAIL(&(sq->req_list), &sq->io_req[i], entry);
4635     }
4636 
4637     sq->bh = qemu_bh_new_guarded(nvme_process_sq, sq,
4638                                  &DEVICE(sq->ctrl)->mem_reentrancy_guard);
4639 
4640     if (n->dbbuf_enabled) {
4641         sq->db_addr = n->dbbuf_dbs + (sqid << 3);
4642         sq->ei_addr = n->dbbuf_eis + (sqid << 3);
4643 
4644         if (n->params.ioeventfd && sq->sqid != 0) {
4645             if (!nvme_init_sq_ioeventfd(sq)) {
4646                 sq->ioeventfd_enabled = true;
4647             }
4648         }
4649     }
4650 
4651     assert(n->cq[cqid]);
4652     cq = n->cq[cqid];
4653     QTAILQ_INSERT_TAIL(&(cq->sq_list), sq, entry);
4654     n->sq[sqid] = sq;
4655 }
4656 
4657 static uint16_t nvme_create_sq(NvmeCtrl *n, NvmeRequest *req)
4658 {
4659     NvmeSQueue *sq;
4660     NvmeCreateSq *c = (NvmeCreateSq *)&req->cmd;
4661 
4662     uint16_t cqid = le16_to_cpu(c->cqid);
4663     uint16_t sqid = le16_to_cpu(c->sqid);
4664     uint16_t qsize = le16_to_cpu(c->qsize);
4665     uint16_t qflags = le16_to_cpu(c->sq_flags);
4666     uint64_t prp1 = le64_to_cpu(c->prp1);
4667 
4668     trace_pci_nvme_create_sq(prp1, sqid, cqid, qsize, qflags);
4669 
4670     if (unlikely(!cqid || nvme_check_cqid(n, cqid))) {
4671         trace_pci_nvme_err_invalid_create_sq_cqid(cqid);
4672         return NVME_INVALID_CQID | NVME_DNR;
4673     }
4674     if (unlikely(!sqid || sqid > n->conf_ioqpairs || n->sq[sqid] != NULL)) {
4675         trace_pci_nvme_err_invalid_create_sq_sqid(sqid);
4676         return NVME_INVALID_QID | NVME_DNR;
4677     }
4678     if (unlikely(!qsize || qsize > NVME_CAP_MQES(ldq_le_p(&n->bar.cap)))) {
4679         trace_pci_nvme_err_invalid_create_sq_size(qsize);
4680         return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
4681     }
4682     if (unlikely(prp1 & (n->page_size - 1))) {
4683         trace_pci_nvme_err_invalid_create_sq_addr(prp1);
4684         return NVME_INVALID_PRP_OFFSET | NVME_DNR;
4685     }
4686     if (unlikely(!(NVME_SQ_FLAGS_PC(qflags)))) {
4687         trace_pci_nvme_err_invalid_create_sq_qflags(NVME_SQ_FLAGS_PC(qflags));
4688         return NVME_INVALID_FIELD | NVME_DNR;
4689     }
4690     sq = g_malloc0(sizeof(*sq));
4691     nvme_init_sq(sq, n, prp1, sqid, cqid, qsize + 1);
4692     return NVME_SUCCESS;
4693 }
4694 
4695 struct nvme_stats {
4696     uint64_t units_read;
4697     uint64_t units_written;
4698     uint64_t read_commands;
4699     uint64_t write_commands;
4700 };
4701 
4702 static void nvme_set_blk_stats(NvmeNamespace *ns, struct nvme_stats *stats)
4703 {
4704     BlockAcctStats *s = blk_get_stats(ns->blkconf.blk);
4705 
4706     stats->units_read += s->nr_bytes[BLOCK_ACCT_READ];
4707     stats->units_written += s->nr_bytes[BLOCK_ACCT_WRITE];
4708     stats->read_commands += s->nr_ops[BLOCK_ACCT_READ];
4709     stats->write_commands += s->nr_ops[BLOCK_ACCT_WRITE];
4710 }
4711 
4712 static uint16_t nvme_smart_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4713                                 uint64_t off, NvmeRequest *req)
4714 {
4715     uint32_t nsid = le32_to_cpu(req->cmd.nsid);
4716     struct nvme_stats stats = { 0 };
4717     NvmeSmartLog smart = { 0 };
4718     uint32_t trans_len;
4719     NvmeNamespace *ns;
4720     time_t current_ms;
4721     uint64_t u_read, u_written;
4722 
4723     if (off >= sizeof(smart)) {
4724         return NVME_INVALID_FIELD | NVME_DNR;
4725     }
4726 
4727     if (nsid != 0xffffffff) {
4728         ns = nvme_ns(n, nsid);
4729         if (!ns) {
4730             return NVME_INVALID_NSID | NVME_DNR;
4731         }
4732         nvme_set_blk_stats(ns, &stats);
4733     } else {
4734         int i;
4735 
4736         for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4737             ns = nvme_ns(n, i);
4738             if (!ns) {
4739                 continue;
4740             }
4741             nvme_set_blk_stats(ns, &stats);
4742         }
4743     }
4744 
4745     trans_len = MIN(sizeof(smart) - off, buf_len);
4746     smart.critical_warning = n->smart_critical_warning;
4747 
4748     u_read = DIV_ROUND_UP(stats.units_read >> BDRV_SECTOR_BITS, 1000);
4749     u_written = DIV_ROUND_UP(stats.units_written >> BDRV_SECTOR_BITS, 1000);
4750 
4751     smart.data_units_read[0] = cpu_to_le64(u_read);
4752     smart.data_units_written[0] = cpu_to_le64(u_written);
4753     smart.host_read_commands[0] = cpu_to_le64(stats.read_commands);
4754     smart.host_write_commands[0] = cpu_to_le64(stats.write_commands);
4755 
4756     smart.temperature = cpu_to_le16(n->temperature);
4757 
4758     if ((n->temperature >= n->features.temp_thresh_hi) ||
4759         (n->temperature <= n->features.temp_thresh_low)) {
4760         smart.critical_warning |= NVME_SMART_TEMPERATURE;
4761     }
4762 
4763     current_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
4764     smart.power_on_hours[0] =
4765         cpu_to_le64((((current_ms - n->starttime_ms) / 1000) / 60) / 60);
4766 
4767     if (!rae) {
4768         nvme_clear_events(n, NVME_AER_TYPE_SMART);
4769     }
4770 
4771     return nvme_c2h(n, (uint8_t *) &smart + off, trans_len, req);
4772 }
4773 
4774 static uint16_t nvme_endgrp_info(NvmeCtrl *n,  uint8_t rae, uint32_t buf_len,
4775                                  uint64_t off, NvmeRequest *req)
4776 {
4777     uint32_t dw11 = le32_to_cpu(req->cmd.cdw11);
4778     uint16_t endgrpid = (dw11 >> 16) & 0xffff;
4779     struct nvme_stats stats = {};
4780     NvmeEndGrpLog info = {};
4781     int i;
4782 
4783     if (!n->subsys || endgrpid != 0x1) {
4784         return NVME_INVALID_FIELD | NVME_DNR;
4785     }
4786 
4787     if (off >= sizeof(info)) {
4788         return NVME_INVALID_FIELD | NVME_DNR;
4789     }
4790 
4791     for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
4792         NvmeNamespace *ns = nvme_subsys_ns(n->subsys, i);
4793         if (!ns) {
4794             continue;
4795         }
4796 
4797         nvme_set_blk_stats(ns, &stats);
4798     }
4799 
4800     info.data_units_read[0] =
4801         cpu_to_le64(DIV_ROUND_UP(stats.units_read / 1000000000, 1000000000));
4802     info.data_units_written[0] =
4803         cpu_to_le64(DIV_ROUND_UP(stats.units_written / 1000000000, 1000000000));
4804     info.media_units_written[0] =
4805         cpu_to_le64(DIV_ROUND_UP(stats.units_written / 1000000000, 1000000000));
4806 
4807     info.host_read_commands[0] = cpu_to_le64(stats.read_commands);
4808     info.host_write_commands[0] = cpu_to_le64(stats.write_commands);
4809 
4810     buf_len = MIN(sizeof(info) - off, buf_len);
4811 
4812     return nvme_c2h(n, (uint8_t *)&info + off, buf_len, req);
4813 }
4814 
4815 
4816 static uint16_t nvme_fw_log_info(NvmeCtrl *n, uint32_t buf_len, uint64_t off,
4817                                  NvmeRequest *req)
4818 {
4819     uint32_t trans_len;
4820     NvmeFwSlotInfoLog fw_log = {
4821         .afi = 0x1,
4822     };
4823 
4824     if (off >= sizeof(fw_log)) {
4825         return NVME_INVALID_FIELD | NVME_DNR;
4826     }
4827 
4828     strpadcpy((char *)&fw_log.frs1, sizeof(fw_log.frs1), "1.0", ' ');
4829     trans_len = MIN(sizeof(fw_log) - off, buf_len);
4830 
4831     return nvme_c2h(n, (uint8_t *) &fw_log + off, trans_len, req);
4832 }
4833 
4834 static uint16_t nvme_error_info(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4835                                 uint64_t off, NvmeRequest *req)
4836 {
4837     uint32_t trans_len;
4838     NvmeErrorLog errlog;
4839 
4840     if (off >= sizeof(errlog)) {
4841         return NVME_INVALID_FIELD | NVME_DNR;
4842     }
4843 
4844     if (!rae) {
4845         nvme_clear_events(n, NVME_AER_TYPE_ERROR);
4846     }
4847 
4848     memset(&errlog, 0x0, sizeof(errlog));
4849     trans_len = MIN(sizeof(errlog) - off, buf_len);
4850 
4851     return nvme_c2h(n, (uint8_t *)&errlog, trans_len, req);
4852 }
4853 
4854 static uint16_t nvme_changed_nslist(NvmeCtrl *n, uint8_t rae, uint32_t buf_len,
4855                                     uint64_t off, NvmeRequest *req)
4856 {
4857     uint32_t nslist[1024];
4858     uint32_t trans_len;
4859     int i = 0;
4860     uint32_t nsid;
4861 
4862     if (off >= sizeof(nslist)) {
4863         trace_pci_nvme_err_invalid_log_page_offset(off, sizeof(nslist));
4864         return NVME_INVALID_FIELD | NVME_DNR;
4865     }
4866 
4867     memset(nslist, 0x0, sizeof(nslist));
4868     trans_len = MIN(sizeof(nslist) - off, buf_len);
4869 
4870     while ((nsid = find_first_bit(n->changed_nsids, NVME_CHANGED_NSID_SIZE)) !=
4871             NVME_CHANGED_NSID_SIZE) {
4872         /*
4873          * If more than 1024 namespaces, the first entry in the log page should
4874          * be set to FFFFFFFFh and the others to 0 as spec.
4875          */
4876         if (i == ARRAY_SIZE(nslist)) {
4877             memset(nslist, 0x0, sizeof(nslist));
4878             nslist[0] = 0xffffffff;
4879             break;
4880         }
4881 
4882         nslist[i++] = nsid;
4883         clear_bit(nsid, n->changed_nsids);
4884     }
4885 
4886     /*
4887      * Remove all the remaining list entries in case returns directly due to
4888      * more than 1024 namespaces.
4889      */
4890     if (nslist[0] == 0xffffffff) {
4891         bitmap_zero(n->changed_nsids, NVME_CHANGED_NSID_SIZE);
4892     }
4893 
4894     if (!rae) {
4895         nvme_clear_events(n, NVME_AER_TYPE_NOTICE);
4896     }
4897 
4898     return nvme_c2h(n, ((uint8_t *)nslist) + off, trans_len, req);
4899 }
4900 
4901 static uint16_t nvme_cmd_effects(NvmeCtrl *n, uint8_t csi, uint32_t buf_len,
4902                                  uint64_t off, NvmeRequest *req)
4903 {
4904     NvmeEffectsLog log = {};
4905     const uint32_t *src_iocs = NULL;
4906     uint32_t trans_len;
4907 
4908     if (off >= sizeof(log)) {
4909         trace_pci_nvme_err_invalid_log_page_offset(off, sizeof(log));
4910         return NVME_INVALID_FIELD | NVME_DNR;
4911     }
4912 
4913     switch (NVME_CC_CSS(ldl_le_p(&n->bar.cc))) {
4914     case NVME_CC_CSS_NVM:
4915         src_iocs = nvme_cse_iocs_nvm;
4916         /* fall through */
4917     case NVME_CC_CSS_ADMIN_ONLY:
4918         break;
4919     case NVME_CC_CSS_CSI:
4920         switch (csi) {
4921         case NVME_CSI_NVM:
4922             src_iocs = nvme_cse_iocs_nvm;
4923             break;
4924         case NVME_CSI_ZONED:
4925             src_iocs = nvme_cse_iocs_zoned;
4926             break;
4927         }
4928     }
4929 
4930     memcpy(log.acs, nvme_cse_acs, sizeof(nvme_cse_acs));
4931 
4932     if (src_iocs) {
4933         memcpy(log.iocs, src_iocs, sizeof(log.iocs));
4934     }
4935 
4936     trans_len = MIN(sizeof(log) - off, buf_len);
4937 
4938     return nvme_c2h(n, ((uint8_t *)&log) + off, trans_len, req);
4939 }
4940 
4941 static size_t sizeof_fdp_conf_descr(size_t nruh, size_t vss)
4942 {
4943     size_t entry_siz = sizeof(NvmeFdpDescrHdr) + nruh * sizeof(NvmeRuhDescr)
4944                        + vss;
4945     return ROUND_UP(entry_siz, 8);
4946 }
4947 
4948 static uint16_t nvme_fdp_confs(NvmeCtrl *n, uint32_t endgrpid, uint32_t buf_len,
4949                                uint64_t off, NvmeRequest *req)
4950 {
4951     uint32_t log_size, trans_len;
4952     g_autofree uint8_t *buf = NULL;
4953     NvmeFdpDescrHdr *hdr;
4954     NvmeRuhDescr *ruhd;
4955     NvmeEnduranceGroup *endgrp;
4956     NvmeFdpConfsHdr *log;
4957     size_t nruh, fdp_descr_size;
4958     int i;
4959 
4960     if (endgrpid != 1 || !n->subsys) {
4961         return NVME_INVALID_FIELD | NVME_DNR;
4962     }
4963 
4964     endgrp = &n->subsys->endgrp;
4965 
4966     if (endgrp->fdp.enabled) {
4967         nruh = endgrp->fdp.nruh;
4968     } else {
4969         nruh = 1;
4970     }
4971 
4972     fdp_descr_size = sizeof_fdp_conf_descr(nruh, FDPVSS);
4973     log_size = sizeof(NvmeFdpConfsHdr) + fdp_descr_size;
4974 
4975     if (off >= log_size) {
4976         return NVME_INVALID_FIELD | NVME_DNR;
4977     }
4978 
4979     trans_len = MIN(log_size - off, buf_len);
4980 
4981     buf = g_malloc0(log_size);
4982     log = (NvmeFdpConfsHdr *)buf;
4983     hdr = (NvmeFdpDescrHdr *)(log + 1);
4984     ruhd = (NvmeRuhDescr *)(buf + sizeof(*log) + sizeof(*hdr));
4985 
4986     log->num_confs = cpu_to_le16(0);
4987     log->size = cpu_to_le32(log_size);
4988 
4989     hdr->descr_size = cpu_to_le16(fdp_descr_size);
4990     if (endgrp->fdp.enabled) {
4991         hdr->fdpa = FIELD_DP8(hdr->fdpa, FDPA, VALID, 1);
4992         hdr->fdpa = FIELD_DP8(hdr->fdpa, FDPA, RGIF, endgrp->fdp.rgif);
4993         hdr->nrg = cpu_to_le16(endgrp->fdp.nrg);
4994         hdr->nruh = cpu_to_le16(endgrp->fdp.nruh);
4995         hdr->maxpids = cpu_to_le16(NVME_FDP_MAXPIDS - 1);
4996         hdr->nnss = cpu_to_le32(NVME_MAX_NAMESPACES);
4997         hdr->runs = cpu_to_le64(endgrp->fdp.runs);
4998 
4999         for (i = 0; i < nruh; i++) {
5000             ruhd->ruht = NVME_RUHT_INITIALLY_ISOLATED;
5001             ruhd++;
5002         }
5003     } else {
5004         /* 1 bit for RUH in PIF -> 2 RUHs max. */
5005         hdr->nrg = cpu_to_le16(1);
5006         hdr->nruh = cpu_to_le16(1);
5007         hdr->maxpids = cpu_to_le16(NVME_FDP_MAXPIDS - 1);
5008         hdr->nnss = cpu_to_le32(1);
5009         hdr->runs = cpu_to_le64(96 * MiB);
5010 
5011         ruhd->ruht = NVME_RUHT_INITIALLY_ISOLATED;
5012     }
5013 
5014     return nvme_c2h(n, (uint8_t *)buf + off, trans_len, req);
5015 }
5016 
5017 static uint16_t nvme_fdp_ruh_usage(NvmeCtrl *n, uint32_t endgrpid,
5018                                    uint32_t dw10, uint32_t dw12,
5019                                    uint32_t buf_len, uint64_t off,
5020                                    NvmeRequest *req)
5021 {
5022     NvmeRuHandle *ruh;
5023     NvmeRuhuLog *hdr;
5024     NvmeRuhuDescr *ruhud;
5025     NvmeEnduranceGroup *endgrp;
5026     g_autofree uint8_t *buf = NULL;
5027     uint32_t log_size, trans_len;
5028     uint16_t i;
5029 
5030     if (endgrpid != 1 || !n->subsys) {
5031         return NVME_INVALID_FIELD | NVME_DNR;
5032     }
5033 
5034     endgrp = &n->subsys->endgrp;
5035 
5036     if (!endgrp->fdp.enabled) {
5037         return NVME_FDP_DISABLED | NVME_DNR;
5038     }
5039 
5040     log_size = sizeof(NvmeRuhuLog) + endgrp->fdp.nruh * sizeof(NvmeRuhuDescr);
5041 
5042     if (off >= log_size) {
5043         return NVME_INVALID_FIELD | NVME_DNR;
5044     }
5045 
5046     trans_len = MIN(log_size - off, buf_len);
5047 
5048     buf = g_malloc0(log_size);
5049     hdr = (NvmeRuhuLog *)buf;
5050     ruhud = (NvmeRuhuDescr *)(hdr + 1);
5051 
5052     ruh = endgrp->fdp.ruhs;
5053     hdr->nruh = cpu_to_le16(endgrp->fdp.nruh);
5054 
5055     for (i = 0; i < endgrp->fdp.nruh; i++, ruhud++, ruh++) {
5056         ruhud->ruha = ruh->ruha;
5057     }
5058 
5059     return nvme_c2h(n, (uint8_t *)buf + off, trans_len, req);
5060 }
5061 
5062 static uint16_t nvme_fdp_stats(NvmeCtrl *n, uint32_t endgrpid, uint32_t buf_len,
5063                                uint64_t off, NvmeRequest *req)
5064 {
5065     NvmeEnduranceGroup *endgrp;
5066     NvmeFdpStatsLog log = {};
5067     uint32_t trans_len;
5068 
5069     if (off >= sizeof(NvmeFdpStatsLog)) {
5070         return NVME_INVALID_FIELD | NVME_DNR;
5071     }
5072 
5073     if (endgrpid != 1 || !n->subsys) {
5074         return NVME_INVALID_FIELD | NVME_DNR;
5075     }
5076 
5077     if (!n->subsys->endgrp.fdp.enabled) {
5078         return NVME_FDP_DISABLED | NVME_DNR;
5079     }
5080 
5081     endgrp = &n->subsys->endgrp;
5082 
5083     trans_len = MIN(sizeof(log) - off, buf_len);
5084 
5085     /* spec value is 128 bit, we only use 64 bit */
5086     log.hbmw[0] = cpu_to_le64(endgrp->fdp.hbmw);
5087     log.mbmw[0] = cpu_to_le64(endgrp->fdp.mbmw);
5088     log.mbe[0] = cpu_to_le64(endgrp->fdp.mbe);
5089 
5090     return nvme_c2h(n, (uint8_t *)&log + off, trans_len, req);
5091 }
5092 
5093 static uint16_t nvme_fdp_events(NvmeCtrl *n, uint32_t endgrpid,
5094                                 uint32_t buf_len, uint64_t off,
5095                                 NvmeRequest *req)
5096 {
5097     NvmeEnduranceGroup *endgrp;
5098     NvmeCmd *cmd = &req->cmd;
5099     bool host_events = (cmd->cdw10 >> 8) & 0x1;
5100     uint32_t log_size, trans_len;
5101     NvmeFdpEventBuffer *ebuf;
5102     g_autofree NvmeFdpEventsLog *elog = NULL;
5103     NvmeFdpEvent *event;
5104 
5105     if (endgrpid != 1 || !n->subsys) {
5106         return NVME_INVALID_FIELD | NVME_DNR;
5107     }
5108 
5109     endgrp = &n->subsys->endgrp;
5110 
5111     if (!endgrp->fdp.enabled) {
5112         return NVME_FDP_DISABLED | NVME_DNR;
5113     }
5114 
5115     if (host_events) {
5116         ebuf = &endgrp->fdp.host_events;
5117     } else {
5118         ebuf = &endgrp->fdp.ctrl_events;
5119     }
5120 
5121     log_size = sizeof(NvmeFdpEventsLog) + ebuf->nelems * sizeof(NvmeFdpEvent);
5122 
5123     if (off >= log_size) {
5124         return NVME_INVALID_FIELD | NVME_DNR;
5125     }
5126 
5127     trans_len = MIN(log_size - off, buf_len);
5128     elog = g_malloc0(log_size);
5129     elog->num_events = cpu_to_le32(ebuf->nelems);
5130     event = (NvmeFdpEvent *)(elog + 1);
5131 
5132     if (ebuf->nelems && ebuf->start == ebuf->next) {
5133         unsigned int nelems = (NVME_FDP_MAX_EVENTS - ebuf->start);
5134         /* wrap over, copy [start;NVME_FDP_MAX_EVENTS[ and [0; next[ */
5135         memcpy(event, &ebuf->events[ebuf->start],
5136                sizeof(NvmeFdpEvent) * nelems);
5137         memcpy(event + nelems, ebuf->events,
5138                sizeof(NvmeFdpEvent) * ebuf->next);
5139     } else if (ebuf->start < ebuf->next) {
5140         memcpy(event, &ebuf->events[ebuf->start],
5141                sizeof(NvmeFdpEvent) * (ebuf->next - ebuf->start));
5142     }
5143 
5144     return nvme_c2h(n, (uint8_t *)elog + off, trans_len, req);
5145 }
5146 
5147 static uint16_t nvme_get_log(NvmeCtrl *n, NvmeRequest *req)
5148 {
5149     NvmeCmd *cmd = &req->cmd;
5150 
5151     uint32_t dw10 = le32_to_cpu(cmd->cdw10);
5152     uint32_t dw11 = le32_to_cpu(cmd->cdw11);
5153     uint32_t dw12 = le32_to_cpu(cmd->cdw12);
5154     uint32_t dw13 = le32_to_cpu(cmd->cdw13);
5155     uint8_t  lid = dw10 & 0xff;
5156     uint8_t  lsp = (dw10 >> 8) & 0xf;
5157     uint8_t  rae = (dw10 >> 15) & 0x1;
5158     uint8_t  csi = le32_to_cpu(cmd->cdw14) >> 24;
5159     uint32_t numdl, numdu, lspi;
5160     uint64_t off, lpol, lpou;
5161     size_t   len;
5162     uint16_t status;
5163 
5164     numdl = (dw10 >> 16);
5165     numdu = (dw11 & 0xffff);
5166     lspi = (dw11 >> 16);
5167     lpol = dw12;
5168     lpou = dw13;
5169 
5170     len = (((numdu << 16) | numdl) + 1) << 2;
5171     off = (lpou << 32ULL) | lpol;
5172 
5173     if (off & 0x3) {
5174         return NVME_INVALID_FIELD | NVME_DNR;
5175     }
5176 
5177     trace_pci_nvme_get_log(nvme_cid(req), lid, lsp, rae, len, off);
5178 
5179     status = nvme_check_mdts(n, len);
5180     if (status) {
5181         return status;
5182     }
5183 
5184     switch (lid) {
5185     case NVME_LOG_ERROR_INFO:
5186         return nvme_error_info(n, rae, len, off, req);
5187     case NVME_LOG_SMART_INFO:
5188         return nvme_smart_info(n, rae, len, off, req);
5189     case NVME_LOG_FW_SLOT_INFO:
5190         return nvme_fw_log_info(n, len, off, req);
5191     case NVME_LOG_CHANGED_NSLIST:
5192         return nvme_changed_nslist(n, rae, len, off, req);
5193     case NVME_LOG_CMD_EFFECTS:
5194         return nvme_cmd_effects(n, csi, len, off, req);
5195     case NVME_LOG_ENDGRP:
5196         return nvme_endgrp_info(n, rae, len, off, req);
5197     case NVME_LOG_FDP_CONFS:
5198         return nvme_fdp_confs(n, lspi, len, off, req);
5199     case NVME_LOG_FDP_RUH_USAGE:
5200         return nvme_fdp_ruh_usage(n, lspi, dw10, dw12, len, off, req);
5201     case NVME_LOG_FDP_STATS:
5202         return nvme_fdp_stats(n, lspi, len, off, req);
5203     case NVME_LOG_FDP_EVENTS:
5204         return nvme_fdp_events(n, lspi, len, off, req);
5205     default:
5206         trace_pci_nvme_err_invalid_log_page(nvme_cid(req), lid);
5207         return NVME_INVALID_FIELD | NVME_DNR;
5208     }
5209 }
5210 
5211 static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
5212 {
5213     PCIDevice *pci = PCI_DEVICE(n);
5214     uint16_t offset = (cq->cqid << 3) + (1 << 2);
5215 
5216     n->cq[cq->cqid] = NULL;
5217     qemu_bh_delete(cq->bh);
5218     if (cq->ioeventfd_enabled) {
5219         memory_region_del_eventfd(&n->iomem,
5220                                   0x1000 + offset, 4, false, 0, &cq->notifier);
5221         event_notifier_set_handler(&cq->notifier, NULL);
5222         event_notifier_cleanup(&cq->notifier);
5223     }
5224     if (msix_enabled(pci)) {
5225         msix_vector_unuse(pci, cq->vector);
5226     }
5227     if (cq->cqid) {
5228         g_free(cq);
5229     }
5230 }
5231 
5232 static uint16_t nvme_del_cq(NvmeCtrl *n, NvmeRequest *req)
5233 {
5234     NvmeDeleteQ *c = (NvmeDeleteQ *)&req->cmd;
5235     NvmeCQueue *cq;
5236     uint16_t qid = le16_to_cpu(c->qid);
5237 
5238     if (unlikely(!qid || nvme_check_cqid(n, qid))) {
5239         trace_pci_nvme_err_invalid_del_cq_cqid(qid);
5240         return NVME_INVALID_CQID | NVME_DNR;
5241     }
5242 
5243     cq = n->cq[qid];
5244     if (unlikely(!QTAILQ_EMPTY(&cq->sq_list))) {
5245         trace_pci_nvme_err_invalid_del_cq_notempty(qid);
5246         return NVME_INVALID_QUEUE_DEL;
5247     }
5248 
5249     if (cq->irq_enabled && cq->tail != cq->head) {
5250         n->cq_pending--;
5251     }
5252 
5253     nvme_irq_deassert(n, cq);
5254     trace_pci_nvme_del_cq(qid);
5255     nvme_free_cq(cq, n);
5256     return NVME_SUCCESS;
5257 }
5258 
5259 static void nvme_init_cq(NvmeCQueue *cq, NvmeCtrl *n, uint64_t dma_addr,
5260                          uint16_t cqid, uint16_t vector, uint16_t size,
5261                          uint16_t irq_enabled)
5262 {
5263     PCIDevice *pci = PCI_DEVICE(n);
5264 
5265     if (msix_enabled(pci)) {
5266         msix_vector_use(pci, vector);
5267     }
5268     cq->ctrl = n;
5269     cq->cqid = cqid;
5270     cq->size = size;
5271     cq->dma_addr = dma_addr;
5272     cq->phase = 1;
5273     cq->irq_enabled = irq_enabled;
5274     cq->vector = vector;
5275     cq->head = cq->tail = 0;
5276     QTAILQ_INIT(&cq->req_list);
5277     QTAILQ_INIT(&cq->sq_list);
5278     if (n->dbbuf_enabled) {
5279         cq->db_addr = n->dbbuf_dbs + (cqid << 3) + (1 << 2);
5280         cq->ei_addr = n->dbbuf_eis + (cqid << 3) + (1 << 2);
5281 
5282         if (n->params.ioeventfd && cqid != 0) {
5283             if (!nvme_init_cq_ioeventfd(cq)) {
5284                 cq->ioeventfd_enabled = true;
5285             }
5286         }
5287     }
5288     n->cq[cqid] = cq;
5289     cq->bh = qemu_bh_new_guarded(nvme_post_cqes, cq,
5290                                  &DEVICE(cq->ctrl)->mem_reentrancy_guard);
5291 }
5292 
5293 static uint16_t nvme_create_cq(NvmeCtrl *n, NvmeRequest *req)
5294 {
5295     NvmeCQueue *cq;
5296     NvmeCreateCq *c = (NvmeCreateCq *)&req->cmd;
5297     uint16_t cqid = le16_to_cpu(c->cqid);
5298     uint16_t vector = le16_to_cpu(c->irq_vector);
5299     uint16_t qsize = le16_to_cpu(c->qsize);
5300     uint16_t qflags = le16_to_cpu(c->cq_flags);
5301     uint64_t prp1 = le64_to_cpu(c->prp1);
5302     uint32_t cc = ldq_le_p(&n->bar.cc);
5303     uint8_t iocqes = NVME_CC_IOCQES(cc);
5304     uint8_t iosqes = NVME_CC_IOSQES(cc);
5305 
5306     trace_pci_nvme_create_cq(prp1, cqid, vector, qsize, qflags,
5307                              NVME_CQ_FLAGS_IEN(qflags) != 0);
5308 
5309     if (iosqes != NVME_SQES || iocqes != NVME_CQES) {
5310         trace_pci_nvme_err_invalid_create_cq_entry_size(iosqes, iocqes);
5311         return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
5312     }
5313 
5314     if (unlikely(!cqid || cqid > n->conf_ioqpairs || n->cq[cqid] != NULL)) {
5315         trace_pci_nvme_err_invalid_create_cq_cqid(cqid);
5316         return NVME_INVALID_QID | NVME_DNR;
5317     }
5318     if (unlikely(!qsize || qsize > NVME_CAP_MQES(ldq_le_p(&n->bar.cap)))) {
5319         trace_pci_nvme_err_invalid_create_cq_size(qsize);
5320         return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
5321     }
5322     if (unlikely(prp1 & (n->page_size - 1))) {
5323         trace_pci_nvme_err_invalid_create_cq_addr(prp1);
5324         return NVME_INVALID_PRP_OFFSET | NVME_DNR;
5325     }
5326     if (unlikely(!msix_enabled(PCI_DEVICE(n)) && vector)) {
5327         trace_pci_nvme_err_invalid_create_cq_vector(vector);
5328         return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
5329     }
5330     if (unlikely(vector >= n->conf_msix_qsize)) {
5331         trace_pci_nvme_err_invalid_create_cq_vector(vector);
5332         return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
5333     }
5334     if (unlikely(!(NVME_CQ_FLAGS_PC(qflags)))) {
5335         trace_pci_nvme_err_invalid_create_cq_qflags(NVME_CQ_FLAGS_PC(qflags));
5336         return NVME_INVALID_FIELD | NVME_DNR;
5337     }
5338 
5339     cq = g_malloc0(sizeof(*cq));
5340     nvme_init_cq(cq, n, prp1, cqid, vector, qsize + 1,
5341                  NVME_CQ_FLAGS_IEN(qflags));
5342 
5343     /*
5344      * It is only required to set qs_created when creating a completion queue;
5345      * creating a submission queue without a matching completion queue will
5346      * fail.
5347      */
5348     n->qs_created = true;
5349     return NVME_SUCCESS;
5350 }
5351 
5352 static uint16_t nvme_rpt_empty_id_struct(NvmeCtrl *n, NvmeRequest *req)
5353 {
5354     uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
5355 
5356     return nvme_c2h(n, id, sizeof(id), req);
5357 }
5358 
5359 static uint16_t nvme_identify_ctrl(NvmeCtrl *n, NvmeRequest *req)
5360 {
5361     trace_pci_nvme_identify_ctrl();
5362 
5363     return nvme_c2h(n, (uint8_t *)&n->id_ctrl, sizeof(n->id_ctrl), req);
5364 }
5365 
5366 static uint16_t nvme_identify_ctrl_csi(NvmeCtrl *n, NvmeRequest *req)
5367 {
5368     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5369     uint8_t id[NVME_IDENTIFY_DATA_SIZE] = {};
5370     NvmeIdCtrlNvm *id_nvm = (NvmeIdCtrlNvm *)&id;
5371 
5372     trace_pci_nvme_identify_ctrl_csi(c->csi);
5373 
5374     switch (c->csi) {
5375     case NVME_CSI_NVM:
5376         id_nvm->vsl = n->params.vsl;
5377         id_nvm->dmrsl = cpu_to_le32(n->dmrsl);
5378         break;
5379 
5380     case NVME_CSI_ZONED:
5381         ((NvmeIdCtrlZoned *)&id)->zasl = n->params.zasl;
5382         break;
5383 
5384     default:
5385         return NVME_INVALID_FIELD | NVME_DNR;
5386     }
5387 
5388     return nvme_c2h(n, id, sizeof(id), req);
5389 }
5390 
5391 static uint16_t nvme_identify_ns(NvmeCtrl *n, NvmeRequest *req, bool active)
5392 {
5393     NvmeNamespace *ns;
5394     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5395     uint32_t nsid = le32_to_cpu(c->nsid);
5396 
5397     trace_pci_nvme_identify_ns(nsid);
5398 
5399     if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5400         return NVME_INVALID_NSID | NVME_DNR;
5401     }
5402 
5403     ns = nvme_ns(n, nsid);
5404     if (unlikely(!ns)) {
5405         if (!active) {
5406             ns = nvme_subsys_ns(n->subsys, nsid);
5407             if (!ns) {
5408                 return nvme_rpt_empty_id_struct(n, req);
5409             }
5410         } else {
5411             return nvme_rpt_empty_id_struct(n, req);
5412         }
5413     }
5414 
5415     if (active || ns->csi == NVME_CSI_NVM) {
5416         return nvme_c2h(n, (uint8_t *)&ns->id_ns, sizeof(NvmeIdNs), req);
5417     }
5418 
5419     return NVME_INVALID_CMD_SET | NVME_DNR;
5420 }
5421 
5422 static uint16_t nvme_identify_ctrl_list(NvmeCtrl *n, NvmeRequest *req,
5423                                         bool attached)
5424 {
5425     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5426     uint32_t nsid = le32_to_cpu(c->nsid);
5427     uint16_t min_id = le16_to_cpu(c->ctrlid);
5428     uint16_t list[NVME_CONTROLLER_LIST_SIZE] = {};
5429     uint16_t *ids = &list[1];
5430     NvmeNamespace *ns;
5431     NvmeCtrl *ctrl;
5432     int cntlid, nr_ids = 0;
5433 
5434     trace_pci_nvme_identify_ctrl_list(c->cns, min_id);
5435 
5436     if (!n->subsys) {
5437         return NVME_INVALID_FIELD | NVME_DNR;
5438     }
5439 
5440     if (attached) {
5441         if (nsid == NVME_NSID_BROADCAST) {
5442             return NVME_INVALID_FIELD | NVME_DNR;
5443         }
5444 
5445         ns = nvme_subsys_ns(n->subsys, nsid);
5446         if (!ns) {
5447             return NVME_INVALID_FIELD | NVME_DNR;
5448         }
5449     }
5450 
5451     for (cntlid = min_id; cntlid < ARRAY_SIZE(n->subsys->ctrls); cntlid++) {
5452         ctrl = nvme_subsys_ctrl(n->subsys, cntlid);
5453         if (!ctrl) {
5454             continue;
5455         }
5456 
5457         if (attached && !nvme_ns(ctrl, nsid)) {
5458             continue;
5459         }
5460 
5461         ids[nr_ids++] = cntlid;
5462     }
5463 
5464     list[0] = nr_ids;
5465 
5466     return nvme_c2h(n, (uint8_t *)list, sizeof(list), req);
5467 }
5468 
5469 static uint16_t nvme_identify_pri_ctrl_cap(NvmeCtrl *n, NvmeRequest *req)
5470 {
5471     trace_pci_nvme_identify_pri_ctrl_cap(le16_to_cpu(n->pri_ctrl_cap.cntlid));
5472 
5473     return nvme_c2h(n, (uint8_t *)&n->pri_ctrl_cap,
5474                     sizeof(NvmePriCtrlCap), req);
5475 }
5476 
5477 static uint16_t nvme_identify_sec_ctrl_list(NvmeCtrl *n, NvmeRequest *req)
5478 {
5479     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5480     uint16_t pri_ctrl_id = le16_to_cpu(n->pri_ctrl_cap.cntlid);
5481     uint16_t min_id = le16_to_cpu(c->ctrlid);
5482     uint8_t num_sec_ctrl = n->nr_sec_ctrls;
5483     NvmeSecCtrlList list = {0};
5484     uint8_t i;
5485 
5486     for (i = 0; i < num_sec_ctrl; i++) {
5487         if (n->sec_ctrl_list[i].scid >= min_id) {
5488             list.numcntl = MIN(num_sec_ctrl - i, 127);
5489             memcpy(&list.sec, n->sec_ctrl_list + i,
5490                    list.numcntl * sizeof(NvmeSecCtrlEntry));
5491             break;
5492         }
5493     }
5494 
5495     trace_pci_nvme_identify_sec_ctrl_list(pri_ctrl_id, list.numcntl);
5496 
5497     return nvme_c2h(n, (uint8_t *)&list, sizeof(list), req);
5498 }
5499 
5500 static uint16_t nvme_identify_ns_csi(NvmeCtrl *n, NvmeRequest *req,
5501                                      bool active)
5502 {
5503     NvmeNamespace *ns;
5504     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5505     uint32_t nsid = le32_to_cpu(c->nsid);
5506 
5507     trace_pci_nvme_identify_ns_csi(nsid, c->csi);
5508 
5509     if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5510         return NVME_INVALID_NSID | NVME_DNR;
5511     }
5512 
5513     ns = nvme_ns(n, nsid);
5514     if (unlikely(!ns)) {
5515         if (!active) {
5516             ns = nvme_subsys_ns(n->subsys, nsid);
5517             if (!ns) {
5518                 return nvme_rpt_empty_id_struct(n, req);
5519             }
5520         } else {
5521             return nvme_rpt_empty_id_struct(n, req);
5522         }
5523     }
5524 
5525     if (c->csi == NVME_CSI_NVM) {
5526         return nvme_c2h(n, (uint8_t *)&ns->id_ns_nvm, sizeof(NvmeIdNsNvm),
5527                         req);
5528     } else if (c->csi == NVME_CSI_ZONED && ns->csi == NVME_CSI_ZONED) {
5529         return nvme_c2h(n, (uint8_t *)ns->id_ns_zoned, sizeof(NvmeIdNsZoned),
5530                         req);
5531     }
5532 
5533     return NVME_INVALID_FIELD | NVME_DNR;
5534 }
5535 
5536 static uint16_t nvme_identify_nslist(NvmeCtrl *n, NvmeRequest *req,
5537                                      bool active)
5538 {
5539     NvmeNamespace *ns;
5540     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5541     uint32_t min_nsid = le32_to_cpu(c->nsid);
5542     uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5543     static const int data_len = sizeof(list);
5544     uint32_t *list_ptr = (uint32_t *)list;
5545     int i, j = 0;
5546 
5547     trace_pci_nvme_identify_nslist(min_nsid);
5548 
5549     /*
5550      * Both FFFFFFFFh (NVME_NSID_BROADCAST) and FFFFFFFFEh are invalid values
5551      * since the Active Namespace ID List should return namespaces with ids
5552      * *higher* than the NSID specified in the command. This is also specified
5553      * in the spec (NVM Express v1.3d, Section 5.15.4).
5554      */
5555     if (min_nsid >= NVME_NSID_BROADCAST - 1) {
5556         return NVME_INVALID_NSID | NVME_DNR;
5557     }
5558 
5559     for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5560         ns = nvme_ns(n, i);
5561         if (!ns) {
5562             if (!active) {
5563                 ns = nvme_subsys_ns(n->subsys, i);
5564                 if (!ns) {
5565                     continue;
5566                 }
5567             } else {
5568                 continue;
5569             }
5570         }
5571         if (ns->params.nsid <= min_nsid) {
5572             continue;
5573         }
5574         list_ptr[j++] = cpu_to_le32(ns->params.nsid);
5575         if (j == data_len / sizeof(uint32_t)) {
5576             break;
5577         }
5578     }
5579 
5580     return nvme_c2h(n, list, data_len, req);
5581 }
5582 
5583 static uint16_t nvme_identify_nslist_csi(NvmeCtrl *n, NvmeRequest *req,
5584                                          bool active)
5585 {
5586     NvmeNamespace *ns;
5587     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5588     uint32_t min_nsid = le32_to_cpu(c->nsid);
5589     uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5590     static const int data_len = sizeof(list);
5591     uint32_t *list_ptr = (uint32_t *)list;
5592     int i, j = 0;
5593 
5594     trace_pci_nvme_identify_nslist_csi(min_nsid, c->csi);
5595 
5596     /*
5597      * Same as in nvme_identify_nslist(), FFFFFFFFh/FFFFFFFFEh are invalid.
5598      */
5599     if (min_nsid >= NVME_NSID_BROADCAST - 1) {
5600         return NVME_INVALID_NSID | NVME_DNR;
5601     }
5602 
5603     if (c->csi != NVME_CSI_NVM && c->csi != NVME_CSI_ZONED) {
5604         return NVME_INVALID_FIELD | NVME_DNR;
5605     }
5606 
5607     for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
5608         ns = nvme_ns(n, i);
5609         if (!ns) {
5610             if (!active) {
5611                 ns = nvme_subsys_ns(n->subsys, i);
5612                 if (!ns) {
5613                     continue;
5614                 }
5615             } else {
5616                 continue;
5617             }
5618         }
5619         if (ns->params.nsid <= min_nsid || c->csi != ns->csi) {
5620             continue;
5621         }
5622         list_ptr[j++] = cpu_to_le32(ns->params.nsid);
5623         if (j == data_len / sizeof(uint32_t)) {
5624             break;
5625         }
5626     }
5627 
5628     return nvme_c2h(n, list, data_len, req);
5629 }
5630 
5631 static uint16_t nvme_endurance_group_list(NvmeCtrl *n, NvmeRequest *req)
5632 {
5633     uint16_t list[NVME_CONTROLLER_LIST_SIZE] = {};
5634     uint16_t *nr_ids = &list[0];
5635     uint16_t *ids = &list[1];
5636     uint16_t endgid = le32_to_cpu(req->cmd.cdw11) & 0xffff;
5637 
5638     /*
5639      * The current nvme-subsys only supports Endurance Group #1.
5640      */
5641     if (!endgid) {
5642         *nr_ids = 1;
5643         ids[0] = 1;
5644     } else {
5645         *nr_ids = 0;
5646     }
5647 
5648     return nvme_c2h(n, list, sizeof(list), req);
5649 }
5650 
5651 static uint16_t nvme_identify_ns_descr_list(NvmeCtrl *n, NvmeRequest *req)
5652 {
5653     NvmeNamespace *ns;
5654     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5655     uint32_t nsid = le32_to_cpu(c->nsid);
5656     uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5657     uint8_t *pos = list;
5658     struct {
5659         NvmeIdNsDescr hdr;
5660         uint8_t v[NVME_NIDL_UUID];
5661     } QEMU_PACKED uuid = {};
5662     struct {
5663         NvmeIdNsDescr hdr;
5664         uint8_t v[NVME_NIDL_NGUID];
5665     } QEMU_PACKED nguid = {};
5666     struct {
5667         NvmeIdNsDescr hdr;
5668         uint64_t v;
5669     } QEMU_PACKED eui64 = {};
5670     struct {
5671         NvmeIdNsDescr hdr;
5672         uint8_t v;
5673     } QEMU_PACKED csi = {};
5674 
5675     trace_pci_nvme_identify_ns_descr_list(nsid);
5676 
5677     if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5678         return NVME_INVALID_NSID | NVME_DNR;
5679     }
5680 
5681     ns = nvme_ns(n, nsid);
5682     if (unlikely(!ns)) {
5683         return NVME_INVALID_FIELD | NVME_DNR;
5684     }
5685 
5686     if (!qemu_uuid_is_null(&ns->params.uuid)) {
5687         uuid.hdr.nidt = NVME_NIDT_UUID;
5688         uuid.hdr.nidl = NVME_NIDL_UUID;
5689         memcpy(uuid.v, ns->params.uuid.data, NVME_NIDL_UUID);
5690         memcpy(pos, &uuid, sizeof(uuid));
5691         pos += sizeof(uuid);
5692     }
5693 
5694     if (!nvme_nguid_is_null(&ns->params.nguid)) {
5695         nguid.hdr.nidt = NVME_NIDT_NGUID;
5696         nguid.hdr.nidl = NVME_NIDL_NGUID;
5697         memcpy(nguid.v, ns->params.nguid.data, NVME_NIDL_NGUID);
5698         memcpy(pos, &nguid, sizeof(nguid));
5699         pos += sizeof(nguid);
5700     }
5701 
5702     if (ns->params.eui64) {
5703         eui64.hdr.nidt = NVME_NIDT_EUI64;
5704         eui64.hdr.nidl = NVME_NIDL_EUI64;
5705         eui64.v = cpu_to_be64(ns->params.eui64);
5706         memcpy(pos, &eui64, sizeof(eui64));
5707         pos += sizeof(eui64);
5708     }
5709 
5710     csi.hdr.nidt = NVME_NIDT_CSI;
5711     csi.hdr.nidl = NVME_NIDL_CSI;
5712     csi.v = ns->csi;
5713     memcpy(pos, &csi, sizeof(csi));
5714     pos += sizeof(csi);
5715 
5716     return nvme_c2h(n, list, sizeof(list), req);
5717 }
5718 
5719 static uint16_t nvme_identify_cmd_set(NvmeCtrl *n, NvmeRequest *req)
5720 {
5721     uint8_t list[NVME_IDENTIFY_DATA_SIZE] = {};
5722     static const int data_len = sizeof(list);
5723 
5724     trace_pci_nvme_identify_cmd_set();
5725 
5726     NVME_SET_CSI(*list, NVME_CSI_NVM);
5727     NVME_SET_CSI(*list, NVME_CSI_ZONED);
5728 
5729     return nvme_c2h(n, list, data_len, req);
5730 }
5731 
5732 static uint16_t nvme_identify(NvmeCtrl *n, NvmeRequest *req)
5733 {
5734     NvmeIdentify *c = (NvmeIdentify *)&req->cmd;
5735 
5736     trace_pci_nvme_identify(nvme_cid(req), c->cns, le16_to_cpu(c->ctrlid),
5737                             c->csi);
5738 
5739     switch (c->cns) {
5740     case NVME_ID_CNS_NS:
5741         return nvme_identify_ns(n, req, true);
5742     case NVME_ID_CNS_NS_PRESENT:
5743         return nvme_identify_ns(n, req, false);
5744     case NVME_ID_CNS_NS_ATTACHED_CTRL_LIST:
5745         return nvme_identify_ctrl_list(n, req, true);
5746     case NVME_ID_CNS_CTRL_LIST:
5747         return nvme_identify_ctrl_list(n, req, false);
5748     case NVME_ID_CNS_PRIMARY_CTRL_CAP:
5749         return nvme_identify_pri_ctrl_cap(n, req);
5750     case NVME_ID_CNS_SECONDARY_CTRL_LIST:
5751         return nvme_identify_sec_ctrl_list(n, req);
5752     case NVME_ID_CNS_CS_NS:
5753         return nvme_identify_ns_csi(n, req, true);
5754     case NVME_ID_CNS_CS_NS_PRESENT:
5755         return nvme_identify_ns_csi(n, req, false);
5756     case NVME_ID_CNS_CTRL:
5757         return nvme_identify_ctrl(n, req);
5758     case NVME_ID_CNS_CS_CTRL:
5759         return nvme_identify_ctrl_csi(n, req);
5760     case NVME_ID_CNS_NS_ACTIVE_LIST:
5761         return nvme_identify_nslist(n, req, true);
5762     case NVME_ID_CNS_NS_PRESENT_LIST:
5763         return nvme_identify_nslist(n, req, false);
5764     case NVME_ID_CNS_CS_NS_ACTIVE_LIST:
5765         return nvme_identify_nslist_csi(n, req, true);
5766     case NVME_ID_CNS_ENDURANCE_GROUP_LIST:
5767         return nvme_endurance_group_list(n, req);
5768     case NVME_ID_CNS_CS_NS_PRESENT_LIST:
5769         return nvme_identify_nslist_csi(n, req, false);
5770     case NVME_ID_CNS_NS_DESCR_LIST:
5771         return nvme_identify_ns_descr_list(n, req);
5772     case NVME_ID_CNS_IO_COMMAND_SET:
5773         return nvme_identify_cmd_set(n, req);
5774     default:
5775         trace_pci_nvme_err_invalid_identify_cns(le32_to_cpu(c->cns));
5776         return NVME_INVALID_FIELD | NVME_DNR;
5777     }
5778 }
5779 
5780 static uint16_t nvme_abort(NvmeCtrl *n, NvmeRequest *req)
5781 {
5782     uint16_t sqid = le32_to_cpu(req->cmd.cdw10) & 0xffff;
5783 
5784     req->cqe.result = 1;
5785     if (nvme_check_sqid(n, sqid)) {
5786         return NVME_INVALID_FIELD | NVME_DNR;
5787     }
5788 
5789     return NVME_SUCCESS;
5790 }
5791 
5792 static inline void nvme_set_timestamp(NvmeCtrl *n, uint64_t ts)
5793 {
5794     trace_pci_nvme_setfeat_timestamp(ts);
5795 
5796     n->host_timestamp = le64_to_cpu(ts);
5797     n->timestamp_set_qemu_clock_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
5798 }
5799 
5800 static inline uint64_t nvme_get_timestamp(const NvmeCtrl *n)
5801 {
5802     uint64_t current_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
5803     uint64_t elapsed_time = current_time - n->timestamp_set_qemu_clock_ms;
5804 
5805     union nvme_timestamp {
5806         struct {
5807             uint64_t timestamp:48;
5808             uint64_t sync:1;
5809             uint64_t origin:3;
5810             uint64_t rsvd1:12;
5811         };
5812         uint64_t all;
5813     };
5814 
5815     union nvme_timestamp ts;
5816     ts.all = 0;
5817     ts.timestamp = n->host_timestamp + elapsed_time;
5818 
5819     /* If the host timestamp is non-zero, set the timestamp origin */
5820     ts.origin = n->host_timestamp ? 0x01 : 0x00;
5821 
5822     trace_pci_nvme_getfeat_timestamp(ts.all);
5823 
5824     return cpu_to_le64(ts.all);
5825 }
5826 
5827 static uint16_t nvme_get_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
5828 {
5829     uint64_t timestamp = nvme_get_timestamp(n);
5830 
5831     return nvme_c2h(n, (uint8_t *)&timestamp, sizeof(timestamp), req);
5832 }
5833 
5834 static int nvme_get_feature_fdp(NvmeCtrl *n, uint32_t endgrpid,
5835                                 uint32_t *result)
5836 {
5837     *result = 0;
5838 
5839     if (!n->subsys || !n->subsys->endgrp.fdp.enabled) {
5840         return NVME_INVALID_FIELD | NVME_DNR;
5841     }
5842 
5843     *result = FIELD_DP16(0, FEAT_FDP, FDPE, 1);
5844     *result = FIELD_DP16(*result, FEAT_FDP, CONF_NDX, 0);
5845 
5846     return NVME_SUCCESS;
5847 }
5848 
5849 static uint16_t nvme_get_feature_fdp_events(NvmeCtrl *n, NvmeNamespace *ns,
5850                                             NvmeRequest *req, uint32_t *result)
5851 {
5852     NvmeCmd *cmd = &req->cmd;
5853     uint32_t cdw11 = le32_to_cpu(cmd->cdw11);
5854     uint16_t ph = cdw11 & 0xffff;
5855     uint8_t noet = (cdw11 >> 16) & 0xff;
5856     uint16_t ruhid, ret;
5857     uint32_t nentries = 0;
5858     uint8_t s_events_ndx = 0;
5859     size_t s_events_siz = sizeof(NvmeFdpEventDescr) * noet;
5860     g_autofree NvmeFdpEventDescr *s_events = g_malloc0(s_events_siz);
5861     NvmeRuHandle *ruh;
5862     NvmeFdpEventDescr *s_event;
5863 
5864     if (!n->subsys || !n->subsys->endgrp.fdp.enabled) {
5865         return NVME_FDP_DISABLED | NVME_DNR;
5866     }
5867 
5868     if (!nvme_ph_valid(ns, ph)) {
5869         return NVME_INVALID_FIELD | NVME_DNR;
5870     }
5871 
5872     ruhid = ns->fdp.phs[ph];
5873     ruh = &n->subsys->endgrp.fdp.ruhs[ruhid];
5874 
5875     assert(ruh);
5876 
5877     if (unlikely(noet == 0)) {
5878         return NVME_INVALID_FIELD | NVME_DNR;
5879     }
5880 
5881     for (uint8_t event_type = 0; event_type < FDP_EVT_MAX; event_type++) {
5882         uint8_t shift = nvme_fdp_evf_shifts[event_type];
5883         if (!shift && event_type) {
5884             /*
5885              * only first entry (event_type == 0) has a shift value of 0
5886              * other entries are simply unpopulated.
5887              */
5888             continue;
5889         }
5890 
5891         nentries++;
5892 
5893         s_event = &s_events[s_events_ndx];
5894         s_event->evt = event_type;
5895         s_event->evta = (ruh->event_filter >> shift) & 0x1;
5896 
5897         /* break if all `noet` entries are filled */
5898         if ((++s_events_ndx) == noet) {
5899             break;
5900         }
5901     }
5902 
5903     ret = nvme_c2h(n, s_events, s_events_siz, req);
5904     if (ret) {
5905         return ret;
5906     }
5907 
5908     *result = nentries;
5909     return NVME_SUCCESS;
5910 }
5911 
5912 static uint16_t nvme_get_feature(NvmeCtrl *n, NvmeRequest *req)
5913 {
5914     NvmeCmd *cmd = &req->cmd;
5915     uint32_t dw10 = le32_to_cpu(cmd->cdw10);
5916     uint32_t dw11 = le32_to_cpu(cmd->cdw11);
5917     uint32_t nsid = le32_to_cpu(cmd->nsid);
5918     uint32_t result = 0;
5919     uint8_t fid = NVME_GETSETFEAT_FID(dw10);
5920     NvmeGetFeatureSelect sel = NVME_GETFEAT_SELECT(dw10);
5921     uint16_t iv;
5922     NvmeNamespace *ns;
5923     int i;
5924     uint16_t endgrpid = 0, ret = NVME_SUCCESS;
5925 
5926     static const uint32_t nvme_feature_default[NVME_FID_MAX] = {
5927         [NVME_ARBITRATION] = NVME_ARB_AB_NOLIMIT,
5928     };
5929 
5930     trace_pci_nvme_getfeat(nvme_cid(req), nsid, fid, sel, dw11);
5931 
5932     if (!nvme_feature_support[fid]) {
5933         return NVME_INVALID_FIELD | NVME_DNR;
5934     }
5935 
5936     if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
5937         if (!nvme_nsid_valid(n, nsid) || nsid == NVME_NSID_BROADCAST) {
5938             /*
5939              * The Reservation Notification Mask and Reservation Persistence
5940              * features require a status code of Invalid Field in Command when
5941              * NSID is FFFFFFFFh. Since the device does not support those
5942              * features we can always return Invalid Namespace or Format as we
5943              * should do for all other features.
5944              */
5945             return NVME_INVALID_NSID | NVME_DNR;
5946         }
5947 
5948         if (!nvme_ns(n, nsid)) {
5949             return NVME_INVALID_FIELD | NVME_DNR;
5950         }
5951     }
5952 
5953     switch (sel) {
5954     case NVME_GETFEAT_SELECT_CURRENT:
5955         break;
5956     case NVME_GETFEAT_SELECT_SAVED:
5957         /* no features are saveable by the controller; fallthrough */
5958     case NVME_GETFEAT_SELECT_DEFAULT:
5959         goto defaults;
5960     case NVME_GETFEAT_SELECT_CAP:
5961         result = nvme_feature_cap[fid];
5962         goto out;
5963     }
5964 
5965     switch (fid) {
5966     case NVME_TEMPERATURE_THRESHOLD:
5967         result = 0;
5968 
5969         /*
5970          * The controller only implements the Composite Temperature sensor, so
5971          * return 0 for all other sensors.
5972          */
5973         if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
5974             goto out;
5975         }
5976 
5977         switch (NVME_TEMP_THSEL(dw11)) {
5978         case NVME_TEMP_THSEL_OVER:
5979             result = n->features.temp_thresh_hi;
5980             goto out;
5981         case NVME_TEMP_THSEL_UNDER:
5982             result = n->features.temp_thresh_low;
5983             goto out;
5984         }
5985 
5986         return NVME_INVALID_FIELD | NVME_DNR;
5987     case NVME_ERROR_RECOVERY:
5988         if (!nvme_nsid_valid(n, nsid)) {
5989             return NVME_INVALID_NSID | NVME_DNR;
5990         }
5991 
5992         ns = nvme_ns(n, nsid);
5993         if (unlikely(!ns)) {
5994             return NVME_INVALID_FIELD | NVME_DNR;
5995         }
5996 
5997         result = ns->features.err_rec;
5998         goto out;
5999     case NVME_VOLATILE_WRITE_CACHE:
6000         result = 0;
6001         for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6002             ns = nvme_ns(n, i);
6003             if (!ns) {
6004                 continue;
6005             }
6006 
6007             result = blk_enable_write_cache(ns->blkconf.blk);
6008             if (result) {
6009                 break;
6010             }
6011         }
6012         trace_pci_nvme_getfeat_vwcache(result ? "enabled" : "disabled");
6013         goto out;
6014     case NVME_ASYNCHRONOUS_EVENT_CONF:
6015         result = n->features.async_config;
6016         goto out;
6017     case NVME_TIMESTAMP:
6018         return nvme_get_feature_timestamp(n, req);
6019     case NVME_HOST_BEHAVIOR_SUPPORT:
6020         return nvme_c2h(n, (uint8_t *)&n->features.hbs,
6021                         sizeof(n->features.hbs), req);
6022     case NVME_FDP_MODE:
6023         endgrpid = dw11 & 0xff;
6024 
6025         if (endgrpid != 0x1) {
6026             return NVME_INVALID_FIELD | NVME_DNR;
6027         }
6028 
6029         ret = nvme_get_feature_fdp(n, endgrpid, &result);
6030         if (ret) {
6031             return ret;
6032         }
6033         goto out;
6034     case NVME_FDP_EVENTS:
6035         if (!nvme_nsid_valid(n, nsid)) {
6036             return NVME_INVALID_NSID | NVME_DNR;
6037         }
6038 
6039         ns = nvme_ns(n, nsid);
6040         if (unlikely(!ns)) {
6041             return NVME_INVALID_FIELD | NVME_DNR;
6042         }
6043 
6044         ret = nvme_get_feature_fdp_events(n, ns, req, &result);
6045         if (ret) {
6046             return ret;
6047         }
6048         goto out;
6049     default:
6050         break;
6051     }
6052 
6053 defaults:
6054     switch (fid) {
6055     case NVME_TEMPERATURE_THRESHOLD:
6056         result = 0;
6057 
6058         if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
6059             break;
6060         }
6061 
6062         if (NVME_TEMP_THSEL(dw11) == NVME_TEMP_THSEL_OVER) {
6063             result = NVME_TEMPERATURE_WARNING;
6064         }
6065 
6066         break;
6067     case NVME_NUMBER_OF_QUEUES:
6068         result = (n->conf_ioqpairs - 1) | ((n->conf_ioqpairs - 1) << 16);
6069         trace_pci_nvme_getfeat_numq(result);
6070         break;
6071     case NVME_INTERRUPT_VECTOR_CONF:
6072         iv = dw11 & 0xffff;
6073         if (iv >= n->conf_ioqpairs + 1) {
6074             return NVME_INVALID_FIELD | NVME_DNR;
6075         }
6076 
6077         result = iv;
6078         if (iv == n->admin_cq.vector) {
6079             result |= NVME_INTVC_NOCOALESCING;
6080         }
6081         break;
6082     case NVME_FDP_MODE:
6083         endgrpid = dw11 & 0xff;
6084 
6085         if (endgrpid != 0x1) {
6086             return NVME_INVALID_FIELD | NVME_DNR;
6087         }
6088 
6089         ret = nvme_get_feature_fdp(n, endgrpid, &result);
6090         if (ret) {
6091             return ret;
6092         }
6093         goto out;
6094 
6095         break;
6096     default:
6097         result = nvme_feature_default[fid];
6098         break;
6099     }
6100 
6101 out:
6102     req->cqe.result = cpu_to_le32(result);
6103     return ret;
6104 }
6105 
6106 static uint16_t nvme_set_feature_timestamp(NvmeCtrl *n, NvmeRequest *req)
6107 {
6108     uint16_t ret;
6109     uint64_t timestamp;
6110 
6111     ret = nvme_h2c(n, (uint8_t *)&timestamp, sizeof(timestamp), req);
6112     if (ret) {
6113         return ret;
6114     }
6115 
6116     nvme_set_timestamp(n, timestamp);
6117 
6118     return NVME_SUCCESS;
6119 }
6120 
6121 static uint16_t nvme_set_feature_fdp_events(NvmeCtrl *n, NvmeNamespace *ns,
6122                                             NvmeRequest *req)
6123 {
6124     NvmeCmd *cmd = &req->cmd;
6125     uint32_t cdw11 = le32_to_cpu(cmd->cdw11);
6126     uint16_t ph = cdw11 & 0xffff;
6127     uint8_t noet = (cdw11 >> 16) & 0xff;
6128     uint16_t ret, ruhid;
6129     uint8_t enable = le32_to_cpu(cmd->cdw12) & 0x1;
6130     uint8_t event_mask = 0;
6131     unsigned int i;
6132     g_autofree uint8_t *events = g_malloc0(noet);
6133     NvmeRuHandle *ruh = NULL;
6134 
6135     assert(ns);
6136 
6137     if (!n->subsys || !n->subsys->endgrp.fdp.enabled) {
6138         return NVME_FDP_DISABLED | NVME_DNR;
6139     }
6140 
6141     if (!nvme_ph_valid(ns, ph)) {
6142         return NVME_INVALID_FIELD | NVME_DNR;
6143     }
6144 
6145     ruhid = ns->fdp.phs[ph];
6146     ruh = &n->subsys->endgrp.fdp.ruhs[ruhid];
6147 
6148     ret = nvme_h2c(n, events, noet, req);
6149     if (ret) {
6150         return ret;
6151     }
6152 
6153     for (i = 0; i < noet; i++) {
6154         event_mask |= (1 << nvme_fdp_evf_shifts[events[i]]);
6155     }
6156 
6157     if (enable) {
6158         ruh->event_filter |= event_mask;
6159     } else {
6160         ruh->event_filter = ruh->event_filter & ~event_mask;
6161     }
6162 
6163     return NVME_SUCCESS;
6164 }
6165 
6166 static uint16_t nvme_set_feature(NvmeCtrl *n, NvmeRequest *req)
6167 {
6168     NvmeNamespace *ns = NULL;
6169 
6170     NvmeCmd *cmd = &req->cmd;
6171     uint32_t dw10 = le32_to_cpu(cmd->cdw10);
6172     uint32_t dw11 = le32_to_cpu(cmd->cdw11);
6173     uint32_t nsid = le32_to_cpu(cmd->nsid);
6174     uint8_t fid = NVME_GETSETFEAT_FID(dw10);
6175     uint8_t save = NVME_SETFEAT_SAVE(dw10);
6176     uint16_t status;
6177     int i;
6178 
6179     trace_pci_nvme_setfeat(nvme_cid(req), nsid, fid, save, dw11);
6180 
6181     if (save && !(nvme_feature_cap[fid] & NVME_FEAT_CAP_SAVE)) {
6182         return NVME_FID_NOT_SAVEABLE | NVME_DNR;
6183     }
6184 
6185     if (!nvme_feature_support[fid]) {
6186         return NVME_INVALID_FIELD | NVME_DNR;
6187     }
6188 
6189     if (nvme_feature_cap[fid] & NVME_FEAT_CAP_NS) {
6190         if (nsid != NVME_NSID_BROADCAST) {
6191             if (!nvme_nsid_valid(n, nsid)) {
6192                 return NVME_INVALID_NSID | NVME_DNR;
6193             }
6194 
6195             ns = nvme_ns(n, nsid);
6196             if (unlikely(!ns)) {
6197                 return NVME_INVALID_FIELD | NVME_DNR;
6198             }
6199         }
6200     } else if (nsid && nsid != NVME_NSID_BROADCAST) {
6201         if (!nvme_nsid_valid(n, nsid)) {
6202             return NVME_INVALID_NSID | NVME_DNR;
6203         }
6204 
6205         return NVME_FEAT_NOT_NS_SPEC | NVME_DNR;
6206     }
6207 
6208     if (!(nvme_feature_cap[fid] & NVME_FEAT_CAP_CHANGE)) {
6209         return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
6210     }
6211 
6212     switch (fid) {
6213     case NVME_TEMPERATURE_THRESHOLD:
6214         if (NVME_TEMP_TMPSEL(dw11) != NVME_TEMP_TMPSEL_COMPOSITE) {
6215             break;
6216         }
6217 
6218         switch (NVME_TEMP_THSEL(dw11)) {
6219         case NVME_TEMP_THSEL_OVER:
6220             n->features.temp_thresh_hi = NVME_TEMP_TMPTH(dw11);
6221             break;
6222         case NVME_TEMP_THSEL_UNDER:
6223             n->features.temp_thresh_low = NVME_TEMP_TMPTH(dw11);
6224             break;
6225         default:
6226             return NVME_INVALID_FIELD | NVME_DNR;
6227         }
6228 
6229         if ((n->temperature >= n->features.temp_thresh_hi) ||
6230             (n->temperature <= n->features.temp_thresh_low)) {
6231             nvme_smart_event(n, NVME_SMART_TEMPERATURE);
6232         }
6233 
6234         break;
6235     case NVME_ERROR_RECOVERY:
6236         if (nsid == NVME_NSID_BROADCAST) {
6237             for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6238                 ns = nvme_ns(n, i);
6239 
6240                 if (!ns) {
6241                     continue;
6242                 }
6243 
6244                 if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat)) {
6245                     ns->features.err_rec = dw11;
6246                 }
6247             }
6248 
6249             break;
6250         }
6251 
6252         assert(ns);
6253         if (NVME_ID_NS_NSFEAT_DULBE(ns->id_ns.nsfeat))  {
6254             ns->features.err_rec = dw11;
6255         }
6256         break;
6257     case NVME_VOLATILE_WRITE_CACHE:
6258         for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6259             ns = nvme_ns(n, i);
6260             if (!ns) {
6261                 continue;
6262             }
6263 
6264             if (!(dw11 & 0x1) && blk_enable_write_cache(ns->blkconf.blk)) {
6265                 blk_flush(ns->blkconf.blk);
6266             }
6267 
6268             blk_set_enable_write_cache(ns->blkconf.blk, dw11 & 1);
6269         }
6270 
6271         break;
6272 
6273     case NVME_NUMBER_OF_QUEUES:
6274         if (n->qs_created) {
6275             return NVME_CMD_SEQ_ERROR | NVME_DNR;
6276         }
6277 
6278         /*
6279          * NVMe v1.3, Section 5.21.1.7: FFFFh is not an allowed value for NCQR
6280          * and NSQR.
6281          */
6282         if ((dw11 & 0xffff) == 0xffff || ((dw11 >> 16) & 0xffff) == 0xffff) {
6283             return NVME_INVALID_FIELD | NVME_DNR;
6284         }
6285 
6286         trace_pci_nvme_setfeat_numq((dw11 & 0xffff) + 1,
6287                                     ((dw11 >> 16) & 0xffff) + 1,
6288                                     n->conf_ioqpairs,
6289                                     n->conf_ioqpairs);
6290         req->cqe.result = cpu_to_le32((n->conf_ioqpairs - 1) |
6291                                       ((n->conf_ioqpairs - 1) << 16));
6292         break;
6293     case NVME_ASYNCHRONOUS_EVENT_CONF:
6294         n->features.async_config = dw11;
6295         break;
6296     case NVME_TIMESTAMP:
6297         return nvme_set_feature_timestamp(n, req);
6298     case NVME_HOST_BEHAVIOR_SUPPORT:
6299         status = nvme_h2c(n, (uint8_t *)&n->features.hbs,
6300                           sizeof(n->features.hbs), req);
6301         if (status) {
6302             return status;
6303         }
6304 
6305         for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
6306             ns = nvme_ns(n, i);
6307 
6308             if (!ns) {
6309                 continue;
6310             }
6311 
6312             ns->id_ns.nlbaf = ns->nlbaf - 1;
6313             if (!n->features.hbs.lbafee) {
6314                 ns->id_ns.nlbaf = MIN(ns->id_ns.nlbaf, 15);
6315             }
6316         }
6317 
6318         return status;
6319     case NVME_COMMAND_SET_PROFILE:
6320         if (dw11 & 0x1ff) {
6321             trace_pci_nvme_err_invalid_iocsci(dw11 & 0x1ff);
6322             return NVME_CMD_SET_CMB_REJECTED | NVME_DNR;
6323         }
6324         break;
6325     case NVME_FDP_MODE:
6326         /* spec: abort with cmd seq err if there's one or more NS' in endgrp */
6327         return NVME_CMD_SEQ_ERROR | NVME_DNR;
6328     case NVME_FDP_EVENTS:
6329         return nvme_set_feature_fdp_events(n, ns, req);
6330     default:
6331         return NVME_FEAT_NOT_CHANGEABLE | NVME_DNR;
6332     }
6333     return NVME_SUCCESS;
6334 }
6335 
6336 static uint16_t nvme_aer(NvmeCtrl *n, NvmeRequest *req)
6337 {
6338     trace_pci_nvme_aer(nvme_cid(req));
6339 
6340     if (n->outstanding_aers > n->params.aerl) {
6341         trace_pci_nvme_aer_aerl_exceeded();
6342         return NVME_AER_LIMIT_EXCEEDED;
6343     }
6344 
6345     n->aer_reqs[n->outstanding_aers] = req;
6346     n->outstanding_aers++;
6347 
6348     if (!QTAILQ_EMPTY(&n->aer_queue)) {
6349         nvme_process_aers(n);
6350     }
6351 
6352     return NVME_NO_COMPLETE;
6353 }
6354 
6355 static void nvme_update_dmrsl(NvmeCtrl *n)
6356 {
6357     int nsid;
6358 
6359     for (nsid = 1; nsid <= NVME_MAX_NAMESPACES; nsid++) {
6360         NvmeNamespace *ns = nvme_ns(n, nsid);
6361         if (!ns) {
6362             continue;
6363         }
6364 
6365         n->dmrsl = MIN_NON_ZERO(n->dmrsl,
6366                                 BDRV_REQUEST_MAX_BYTES / nvme_l2b(ns, 1));
6367     }
6368 }
6369 
6370 static void nvme_select_iocs_ns(NvmeCtrl *n, NvmeNamespace *ns)
6371 {
6372     uint32_t cc = ldl_le_p(&n->bar.cc);
6373 
6374     ns->iocs = nvme_cse_iocs_none;
6375     switch (ns->csi) {
6376     case NVME_CSI_NVM:
6377         if (NVME_CC_CSS(cc) != NVME_CC_CSS_ADMIN_ONLY) {
6378             ns->iocs = nvme_cse_iocs_nvm;
6379         }
6380         break;
6381     case NVME_CSI_ZONED:
6382         if (NVME_CC_CSS(cc) == NVME_CC_CSS_CSI) {
6383             ns->iocs = nvme_cse_iocs_zoned;
6384         } else if (NVME_CC_CSS(cc) == NVME_CC_CSS_NVM) {
6385             ns->iocs = nvme_cse_iocs_nvm;
6386         }
6387         break;
6388     }
6389 }
6390 
6391 static uint16_t nvme_ns_attachment(NvmeCtrl *n, NvmeRequest *req)
6392 {
6393     NvmeNamespace *ns;
6394     NvmeCtrl *ctrl;
6395     uint16_t list[NVME_CONTROLLER_LIST_SIZE] = {};
6396     uint32_t nsid = le32_to_cpu(req->cmd.nsid);
6397     uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6398     uint8_t sel = dw10 & 0xf;
6399     uint16_t *nr_ids = &list[0];
6400     uint16_t *ids = &list[1];
6401     uint16_t ret;
6402     int i;
6403 
6404     trace_pci_nvme_ns_attachment(nvme_cid(req), dw10 & 0xf);
6405 
6406     if (!nvme_nsid_valid(n, nsid)) {
6407         return NVME_INVALID_NSID | NVME_DNR;
6408     }
6409 
6410     ns = nvme_subsys_ns(n->subsys, nsid);
6411     if (!ns) {
6412         return NVME_INVALID_FIELD | NVME_DNR;
6413     }
6414 
6415     ret = nvme_h2c(n, (uint8_t *)list, 4096, req);
6416     if (ret) {
6417         return ret;
6418     }
6419 
6420     if (!*nr_ids) {
6421         return NVME_NS_CTRL_LIST_INVALID | NVME_DNR;
6422     }
6423 
6424     *nr_ids = MIN(*nr_ids, NVME_CONTROLLER_LIST_SIZE - 1);
6425     for (i = 0; i < *nr_ids; i++) {
6426         ctrl = nvme_subsys_ctrl(n->subsys, ids[i]);
6427         if (!ctrl) {
6428             return NVME_NS_CTRL_LIST_INVALID | NVME_DNR;
6429         }
6430 
6431         switch (sel) {
6432         case NVME_NS_ATTACHMENT_ATTACH:
6433             if (nvme_ns(ctrl, nsid)) {
6434                 return NVME_NS_ALREADY_ATTACHED | NVME_DNR;
6435             }
6436 
6437             if (ns->attached && !ns->params.shared) {
6438                 return NVME_NS_PRIVATE | NVME_DNR;
6439             }
6440 
6441             nvme_attach_ns(ctrl, ns);
6442             nvme_select_iocs_ns(ctrl, ns);
6443 
6444             break;
6445 
6446         case NVME_NS_ATTACHMENT_DETACH:
6447             if (!nvme_ns(ctrl, nsid)) {
6448                 return NVME_NS_NOT_ATTACHED | NVME_DNR;
6449             }
6450 
6451             ctrl->namespaces[nsid] = NULL;
6452             ns->attached--;
6453 
6454             nvme_update_dmrsl(ctrl);
6455 
6456             break;
6457 
6458         default:
6459             return NVME_INVALID_FIELD | NVME_DNR;
6460         }
6461 
6462         /*
6463          * Add namespace id to the changed namespace id list for event clearing
6464          * via Get Log Page command.
6465          */
6466         if (!test_and_set_bit(nsid, ctrl->changed_nsids)) {
6467             nvme_enqueue_event(ctrl, NVME_AER_TYPE_NOTICE,
6468                                NVME_AER_INFO_NOTICE_NS_ATTR_CHANGED,
6469                                NVME_LOG_CHANGED_NSLIST);
6470         }
6471     }
6472 
6473     return NVME_SUCCESS;
6474 }
6475 
6476 typedef struct NvmeFormatAIOCB {
6477     BlockAIOCB common;
6478     BlockAIOCB *aiocb;
6479     NvmeRequest *req;
6480     int ret;
6481 
6482     NvmeNamespace *ns;
6483     uint32_t nsid;
6484     bool broadcast;
6485     int64_t offset;
6486 
6487     uint8_t lbaf;
6488     uint8_t mset;
6489     uint8_t pi;
6490     uint8_t pil;
6491 } NvmeFormatAIOCB;
6492 
6493 static void nvme_format_cancel(BlockAIOCB *aiocb)
6494 {
6495     NvmeFormatAIOCB *iocb = container_of(aiocb, NvmeFormatAIOCB, common);
6496 
6497     iocb->ret = -ECANCELED;
6498 
6499     if (iocb->aiocb) {
6500         blk_aio_cancel_async(iocb->aiocb);
6501         iocb->aiocb = NULL;
6502     }
6503 }
6504 
6505 static const AIOCBInfo nvme_format_aiocb_info = {
6506     .aiocb_size = sizeof(NvmeFormatAIOCB),
6507     .cancel_async = nvme_format_cancel,
6508 };
6509 
6510 static void nvme_format_set(NvmeNamespace *ns, uint8_t lbaf, uint8_t mset,
6511                             uint8_t pi, uint8_t pil)
6512 {
6513     uint8_t lbafl = lbaf & 0xf;
6514     uint8_t lbafu = lbaf >> 4;
6515 
6516     trace_pci_nvme_format_set(ns->params.nsid, lbaf, mset, pi, pil);
6517 
6518     ns->id_ns.dps = (pil << 3) | pi;
6519     ns->id_ns.flbas = (lbafu << 5) | (mset << 4) | lbafl;
6520 
6521     nvme_ns_init_format(ns);
6522 }
6523 
6524 static void nvme_do_format(NvmeFormatAIOCB *iocb);
6525 
6526 static void nvme_format_ns_cb(void *opaque, int ret)
6527 {
6528     NvmeFormatAIOCB *iocb = opaque;
6529     NvmeNamespace *ns = iocb->ns;
6530     int bytes;
6531 
6532     if (iocb->ret < 0) {
6533         goto done;
6534     } else if (ret < 0) {
6535         iocb->ret = ret;
6536         goto done;
6537     }
6538 
6539     assert(ns);
6540 
6541     if (iocb->offset < ns->size) {
6542         bytes = MIN(BDRV_REQUEST_MAX_BYTES, ns->size - iocb->offset);
6543 
6544         iocb->aiocb = blk_aio_pwrite_zeroes(ns->blkconf.blk, iocb->offset,
6545                                             bytes, BDRV_REQ_MAY_UNMAP,
6546                                             nvme_format_ns_cb, iocb);
6547 
6548         iocb->offset += bytes;
6549         return;
6550     }
6551 
6552     nvme_format_set(ns, iocb->lbaf, iocb->mset, iocb->pi, iocb->pil);
6553     ns->status = 0x0;
6554     iocb->ns = NULL;
6555     iocb->offset = 0;
6556 
6557 done:
6558     nvme_do_format(iocb);
6559 }
6560 
6561 static uint16_t nvme_format_check(NvmeNamespace *ns, uint8_t lbaf, uint8_t pi)
6562 {
6563     if (ns->params.zoned) {
6564         return NVME_INVALID_FORMAT | NVME_DNR;
6565     }
6566 
6567     if (lbaf > ns->id_ns.nlbaf) {
6568         return NVME_INVALID_FORMAT | NVME_DNR;
6569     }
6570 
6571     if (pi && (ns->id_ns.lbaf[lbaf].ms < nvme_pi_tuple_size(ns))) {
6572         return NVME_INVALID_FORMAT | NVME_DNR;
6573     }
6574 
6575     if (pi && pi > NVME_ID_NS_DPS_TYPE_3) {
6576         return NVME_INVALID_FIELD | NVME_DNR;
6577     }
6578 
6579     return NVME_SUCCESS;
6580 }
6581 
6582 static void nvme_do_format(NvmeFormatAIOCB *iocb)
6583 {
6584     NvmeRequest *req = iocb->req;
6585     NvmeCtrl *n = nvme_ctrl(req);
6586     uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6587     uint8_t lbaf = dw10 & 0xf;
6588     uint8_t pi = (dw10 >> 5) & 0x7;
6589     uint16_t status;
6590     int i;
6591 
6592     if (iocb->ret < 0) {
6593         goto done;
6594     }
6595 
6596     if (iocb->broadcast) {
6597         for (i = iocb->nsid + 1; i <= NVME_MAX_NAMESPACES; i++) {
6598             iocb->ns = nvme_ns(n, i);
6599             if (iocb->ns) {
6600                 iocb->nsid = i;
6601                 break;
6602             }
6603         }
6604     }
6605 
6606     if (!iocb->ns) {
6607         goto done;
6608     }
6609 
6610     status = nvme_format_check(iocb->ns, lbaf, pi);
6611     if (status) {
6612         req->status = status;
6613         goto done;
6614     }
6615 
6616     iocb->ns->status = NVME_FORMAT_IN_PROGRESS;
6617     nvme_format_ns_cb(iocb, 0);
6618     return;
6619 
6620 done:
6621     iocb->common.cb(iocb->common.opaque, iocb->ret);
6622     qemu_aio_unref(iocb);
6623 }
6624 
6625 static uint16_t nvme_format(NvmeCtrl *n, NvmeRequest *req)
6626 {
6627     NvmeFormatAIOCB *iocb;
6628     uint32_t nsid = le32_to_cpu(req->cmd.nsid);
6629     uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6630     uint8_t lbaf = dw10 & 0xf;
6631     uint8_t mset = (dw10 >> 4) & 0x1;
6632     uint8_t pi = (dw10 >> 5) & 0x7;
6633     uint8_t pil = (dw10 >> 8) & 0x1;
6634     uint8_t lbafu = (dw10 >> 12) & 0x3;
6635     uint16_t status;
6636 
6637     iocb = qemu_aio_get(&nvme_format_aiocb_info, NULL, nvme_misc_cb, req);
6638 
6639     iocb->req = req;
6640     iocb->ret = 0;
6641     iocb->ns = NULL;
6642     iocb->nsid = 0;
6643     iocb->lbaf = lbaf;
6644     iocb->mset = mset;
6645     iocb->pi = pi;
6646     iocb->pil = pil;
6647     iocb->broadcast = (nsid == NVME_NSID_BROADCAST);
6648     iocb->offset = 0;
6649 
6650     if (n->features.hbs.lbafee) {
6651         iocb->lbaf |= lbafu << 4;
6652     }
6653 
6654     if (!iocb->broadcast) {
6655         if (!nvme_nsid_valid(n, nsid)) {
6656             status = NVME_INVALID_NSID | NVME_DNR;
6657             goto out;
6658         }
6659 
6660         iocb->ns = nvme_ns(n, nsid);
6661         if (!iocb->ns) {
6662             status = NVME_INVALID_FIELD | NVME_DNR;
6663             goto out;
6664         }
6665     }
6666 
6667     req->aiocb = &iocb->common;
6668     nvme_do_format(iocb);
6669 
6670     return NVME_NO_COMPLETE;
6671 
6672 out:
6673     qemu_aio_unref(iocb);
6674 
6675     return status;
6676 }
6677 
6678 static void nvme_get_virt_res_num(NvmeCtrl *n, uint8_t rt, int *num_total,
6679                                   int *num_prim, int *num_sec)
6680 {
6681     *num_total = le32_to_cpu(rt ?
6682                              n->pri_ctrl_cap.vifrt : n->pri_ctrl_cap.vqfrt);
6683     *num_prim = le16_to_cpu(rt ?
6684                             n->pri_ctrl_cap.virfap : n->pri_ctrl_cap.vqrfap);
6685     *num_sec = le16_to_cpu(rt ? n->pri_ctrl_cap.virfa : n->pri_ctrl_cap.vqrfa);
6686 }
6687 
6688 static uint16_t nvme_assign_virt_res_to_prim(NvmeCtrl *n, NvmeRequest *req,
6689                                              uint16_t cntlid, uint8_t rt,
6690                                              int nr)
6691 {
6692     int num_total, num_prim, num_sec;
6693 
6694     if (cntlid != n->cntlid) {
6695         return NVME_INVALID_CTRL_ID | NVME_DNR;
6696     }
6697 
6698     nvme_get_virt_res_num(n, rt, &num_total, &num_prim, &num_sec);
6699 
6700     if (nr > num_total) {
6701         return NVME_INVALID_NUM_RESOURCES | NVME_DNR;
6702     }
6703 
6704     if (nr > num_total - num_sec) {
6705         return NVME_INVALID_RESOURCE_ID | NVME_DNR;
6706     }
6707 
6708     if (rt) {
6709         n->next_pri_ctrl_cap.virfap = cpu_to_le16(nr);
6710     } else {
6711         n->next_pri_ctrl_cap.vqrfap = cpu_to_le16(nr);
6712     }
6713 
6714     req->cqe.result = cpu_to_le32(nr);
6715     return req->status;
6716 }
6717 
6718 static void nvme_update_virt_res(NvmeCtrl *n, NvmeSecCtrlEntry *sctrl,
6719                                  uint8_t rt, int nr)
6720 {
6721     int prev_nr, prev_total;
6722 
6723     if (rt) {
6724         prev_nr = le16_to_cpu(sctrl->nvi);
6725         prev_total = le32_to_cpu(n->pri_ctrl_cap.virfa);
6726         sctrl->nvi = cpu_to_le16(nr);
6727         n->pri_ctrl_cap.virfa = cpu_to_le32(prev_total + nr - prev_nr);
6728     } else {
6729         prev_nr = le16_to_cpu(sctrl->nvq);
6730         prev_total = le32_to_cpu(n->pri_ctrl_cap.vqrfa);
6731         sctrl->nvq = cpu_to_le16(nr);
6732         n->pri_ctrl_cap.vqrfa = cpu_to_le32(prev_total + nr - prev_nr);
6733     }
6734 }
6735 
6736 static uint16_t nvme_assign_virt_res_to_sec(NvmeCtrl *n, NvmeRequest *req,
6737                                             uint16_t cntlid, uint8_t rt, int nr)
6738 {
6739     int num_total, num_prim, num_sec, num_free, diff, limit;
6740     NvmeSecCtrlEntry *sctrl;
6741 
6742     sctrl = nvme_sctrl_for_cntlid(n, cntlid);
6743     if (!sctrl) {
6744         return NVME_INVALID_CTRL_ID | NVME_DNR;
6745     }
6746 
6747     if (sctrl->scs) {
6748         return NVME_INVALID_SEC_CTRL_STATE | NVME_DNR;
6749     }
6750 
6751     limit = le16_to_cpu(rt ? n->pri_ctrl_cap.vifrsm : n->pri_ctrl_cap.vqfrsm);
6752     if (nr > limit) {
6753         return NVME_INVALID_NUM_RESOURCES | NVME_DNR;
6754     }
6755 
6756     nvme_get_virt_res_num(n, rt, &num_total, &num_prim, &num_sec);
6757     num_free = num_total - num_prim - num_sec;
6758     diff = nr - le16_to_cpu(rt ? sctrl->nvi : sctrl->nvq);
6759 
6760     if (diff > num_free) {
6761         return NVME_INVALID_RESOURCE_ID | NVME_DNR;
6762     }
6763 
6764     nvme_update_virt_res(n, sctrl, rt, nr);
6765     req->cqe.result = cpu_to_le32(nr);
6766 
6767     return req->status;
6768 }
6769 
6770 static uint16_t nvme_virt_set_state(NvmeCtrl *n, uint16_t cntlid, bool online)
6771 {
6772     PCIDevice *pci = PCI_DEVICE(n);
6773     NvmeCtrl *sn = NULL;
6774     NvmeSecCtrlEntry *sctrl;
6775     int vf_index;
6776 
6777     sctrl = nvme_sctrl_for_cntlid(n, cntlid);
6778     if (!sctrl) {
6779         return NVME_INVALID_CTRL_ID | NVME_DNR;
6780     }
6781 
6782     if (!pci_is_vf(pci)) {
6783         vf_index = le16_to_cpu(sctrl->vfn) - 1;
6784         sn = NVME(pcie_sriov_get_vf_at_index(pci, vf_index));
6785     }
6786 
6787     if (online) {
6788         if (!sctrl->nvi || (le16_to_cpu(sctrl->nvq) < 2) || !sn) {
6789             return NVME_INVALID_SEC_CTRL_STATE | NVME_DNR;
6790         }
6791 
6792         if (!sctrl->scs) {
6793             sctrl->scs = 0x1;
6794             nvme_ctrl_reset(sn, NVME_RESET_FUNCTION);
6795         }
6796     } else {
6797         nvme_update_virt_res(n, sctrl, NVME_VIRT_RES_INTERRUPT, 0);
6798         nvme_update_virt_res(n, sctrl, NVME_VIRT_RES_QUEUE, 0);
6799 
6800         if (sctrl->scs) {
6801             sctrl->scs = 0x0;
6802             if (sn) {
6803                 nvme_ctrl_reset(sn, NVME_RESET_FUNCTION);
6804             }
6805         }
6806     }
6807 
6808     return NVME_SUCCESS;
6809 }
6810 
6811 static uint16_t nvme_virt_mngmt(NvmeCtrl *n, NvmeRequest *req)
6812 {
6813     uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6814     uint32_t dw11 = le32_to_cpu(req->cmd.cdw11);
6815     uint8_t act = dw10 & 0xf;
6816     uint8_t rt = (dw10 >> 8) & 0x7;
6817     uint16_t cntlid = (dw10 >> 16) & 0xffff;
6818     int nr = dw11 & 0xffff;
6819 
6820     trace_pci_nvme_virt_mngmt(nvme_cid(req), act, cntlid, rt ? "VI" : "VQ", nr);
6821 
6822     if (rt != NVME_VIRT_RES_QUEUE && rt != NVME_VIRT_RES_INTERRUPT) {
6823         return NVME_INVALID_RESOURCE_ID | NVME_DNR;
6824     }
6825 
6826     switch (act) {
6827     case NVME_VIRT_MNGMT_ACTION_SEC_ASSIGN:
6828         return nvme_assign_virt_res_to_sec(n, req, cntlid, rt, nr);
6829     case NVME_VIRT_MNGMT_ACTION_PRM_ALLOC:
6830         return nvme_assign_virt_res_to_prim(n, req, cntlid, rt, nr);
6831     case NVME_VIRT_MNGMT_ACTION_SEC_ONLINE:
6832         return nvme_virt_set_state(n, cntlid, true);
6833     case NVME_VIRT_MNGMT_ACTION_SEC_OFFLINE:
6834         return nvme_virt_set_state(n, cntlid, false);
6835     default:
6836         return NVME_INVALID_FIELD | NVME_DNR;
6837     }
6838 }
6839 
6840 static uint16_t nvme_dbbuf_config(NvmeCtrl *n, const NvmeRequest *req)
6841 {
6842     PCIDevice *pci = PCI_DEVICE(n);
6843     uint64_t dbs_addr = le64_to_cpu(req->cmd.dptr.prp1);
6844     uint64_t eis_addr = le64_to_cpu(req->cmd.dptr.prp2);
6845     int i;
6846 
6847     /* Address should be page aligned */
6848     if (dbs_addr & (n->page_size - 1) || eis_addr & (n->page_size - 1)) {
6849         return NVME_INVALID_FIELD | NVME_DNR;
6850     }
6851 
6852     /* Save shadow buffer base addr for use during queue creation */
6853     n->dbbuf_dbs = dbs_addr;
6854     n->dbbuf_eis = eis_addr;
6855     n->dbbuf_enabled = true;
6856 
6857     for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
6858         NvmeSQueue *sq = n->sq[i];
6859         NvmeCQueue *cq = n->cq[i];
6860 
6861         if (sq) {
6862             /*
6863              * CAP.DSTRD is 0, so offset of ith sq db_addr is (i<<3)
6864              * nvme_process_db() uses this hard-coded way to calculate
6865              * doorbell offsets. Be consistent with that here.
6866              */
6867             sq->db_addr = dbs_addr + (i << 3);
6868             sq->ei_addr = eis_addr + (i << 3);
6869             stl_le_pci_dma(pci, sq->db_addr, sq->tail, MEMTXATTRS_UNSPECIFIED);
6870 
6871             if (n->params.ioeventfd && sq->sqid != 0) {
6872                 if (!nvme_init_sq_ioeventfd(sq)) {
6873                     sq->ioeventfd_enabled = true;
6874                 }
6875             }
6876         }
6877 
6878         if (cq) {
6879             /* CAP.DSTRD is 0, so offset of ith cq db_addr is (i<<3)+(1<<2) */
6880             cq->db_addr = dbs_addr + (i << 3) + (1 << 2);
6881             cq->ei_addr = eis_addr + (i << 3) + (1 << 2);
6882             stl_le_pci_dma(pci, cq->db_addr, cq->head, MEMTXATTRS_UNSPECIFIED);
6883 
6884             if (n->params.ioeventfd && cq->cqid != 0) {
6885                 if (!nvme_init_cq_ioeventfd(cq)) {
6886                     cq->ioeventfd_enabled = true;
6887                 }
6888             }
6889         }
6890     }
6891 
6892     trace_pci_nvme_dbbuf_config(dbs_addr, eis_addr);
6893 
6894     return NVME_SUCCESS;
6895 }
6896 
6897 static uint16_t nvme_directive_send(NvmeCtrl *n, NvmeRequest *req)
6898 {
6899     return NVME_INVALID_FIELD | NVME_DNR;
6900 }
6901 
6902 static uint16_t nvme_directive_receive(NvmeCtrl *n, NvmeRequest *req)
6903 {
6904     NvmeNamespace *ns;
6905     uint32_t dw10 = le32_to_cpu(req->cmd.cdw10);
6906     uint32_t dw11 = le32_to_cpu(req->cmd.cdw11);
6907     uint32_t nsid = le32_to_cpu(req->cmd.nsid);
6908     uint8_t doper, dtype;
6909     uint32_t numd, trans_len;
6910     NvmeDirectiveIdentify id = {
6911         .supported = 1 << NVME_DIRECTIVE_IDENTIFY,
6912         .enabled = 1 << NVME_DIRECTIVE_IDENTIFY,
6913     };
6914 
6915     numd = dw10 + 1;
6916     doper = dw11 & 0xff;
6917     dtype = (dw11 >> 8) & 0xff;
6918 
6919     trans_len = MIN(sizeof(NvmeDirectiveIdentify), numd << 2);
6920 
6921     if (nsid == NVME_NSID_BROADCAST || dtype != NVME_DIRECTIVE_IDENTIFY ||
6922         doper != NVME_DIRECTIVE_RETURN_PARAMS) {
6923         return NVME_INVALID_FIELD | NVME_DNR;
6924     }
6925 
6926     ns = nvme_ns(n, nsid);
6927     if (!ns) {
6928         return NVME_INVALID_FIELD | NVME_DNR;
6929     }
6930 
6931     switch (dtype) {
6932     case NVME_DIRECTIVE_IDENTIFY:
6933         switch (doper) {
6934         case NVME_DIRECTIVE_RETURN_PARAMS:
6935             if (ns->endgrp && ns->endgrp->fdp.enabled) {
6936                 id.supported |= 1 << NVME_DIRECTIVE_DATA_PLACEMENT;
6937                 id.enabled |= 1 << NVME_DIRECTIVE_DATA_PLACEMENT;
6938                 id.persistent |= 1 << NVME_DIRECTIVE_DATA_PLACEMENT;
6939             }
6940 
6941             return nvme_c2h(n, (uint8_t *)&id, trans_len, req);
6942 
6943         default:
6944             return NVME_INVALID_FIELD | NVME_DNR;
6945         }
6946 
6947     default:
6948         return NVME_INVALID_FIELD;
6949     }
6950 }
6951 
6952 static uint16_t nvme_admin_cmd(NvmeCtrl *n, NvmeRequest *req)
6953 {
6954     trace_pci_nvme_admin_cmd(nvme_cid(req), nvme_sqid(req), req->cmd.opcode,
6955                              nvme_adm_opc_str(req->cmd.opcode));
6956 
6957     if (!(nvme_cse_acs[req->cmd.opcode] & NVME_CMD_EFF_CSUPP)) {
6958         trace_pci_nvme_err_invalid_admin_opc(req->cmd.opcode);
6959         return NVME_INVALID_OPCODE | NVME_DNR;
6960     }
6961 
6962     /* SGLs shall not be used for Admin commands in NVMe over PCIe */
6963     if (NVME_CMD_FLAGS_PSDT(req->cmd.flags) != NVME_PSDT_PRP) {
6964         return NVME_INVALID_FIELD | NVME_DNR;
6965     }
6966 
6967     if (NVME_CMD_FLAGS_FUSE(req->cmd.flags)) {
6968         return NVME_INVALID_FIELD;
6969     }
6970 
6971     switch (req->cmd.opcode) {
6972     case NVME_ADM_CMD_DELETE_SQ:
6973         return nvme_del_sq(n, req);
6974     case NVME_ADM_CMD_CREATE_SQ:
6975         return nvme_create_sq(n, req);
6976     case NVME_ADM_CMD_GET_LOG_PAGE:
6977         return nvme_get_log(n, req);
6978     case NVME_ADM_CMD_DELETE_CQ:
6979         return nvme_del_cq(n, req);
6980     case NVME_ADM_CMD_CREATE_CQ:
6981         return nvme_create_cq(n, req);
6982     case NVME_ADM_CMD_IDENTIFY:
6983         return nvme_identify(n, req);
6984     case NVME_ADM_CMD_ABORT:
6985         return nvme_abort(n, req);
6986     case NVME_ADM_CMD_SET_FEATURES:
6987         return nvme_set_feature(n, req);
6988     case NVME_ADM_CMD_GET_FEATURES:
6989         return nvme_get_feature(n, req);
6990     case NVME_ADM_CMD_ASYNC_EV_REQ:
6991         return nvme_aer(n, req);
6992     case NVME_ADM_CMD_NS_ATTACHMENT:
6993         return nvme_ns_attachment(n, req);
6994     case NVME_ADM_CMD_VIRT_MNGMT:
6995         return nvme_virt_mngmt(n, req);
6996     case NVME_ADM_CMD_DBBUF_CONFIG:
6997         return nvme_dbbuf_config(n, req);
6998     case NVME_ADM_CMD_FORMAT_NVM:
6999         return nvme_format(n, req);
7000     case NVME_ADM_CMD_DIRECTIVE_SEND:
7001         return nvme_directive_send(n, req);
7002     case NVME_ADM_CMD_DIRECTIVE_RECV:
7003         return nvme_directive_receive(n, req);
7004     default:
7005         assert(false);
7006     }
7007 
7008     return NVME_INVALID_OPCODE | NVME_DNR;
7009 }
7010 
7011 static void nvme_update_sq_eventidx(const NvmeSQueue *sq)
7012 {
7013     trace_pci_nvme_update_sq_eventidx(sq->sqid, sq->tail);
7014 
7015     stl_le_pci_dma(PCI_DEVICE(sq->ctrl), sq->ei_addr, sq->tail,
7016                    MEMTXATTRS_UNSPECIFIED);
7017 }
7018 
7019 static void nvme_update_sq_tail(NvmeSQueue *sq)
7020 {
7021     ldl_le_pci_dma(PCI_DEVICE(sq->ctrl), sq->db_addr, &sq->tail,
7022                    MEMTXATTRS_UNSPECIFIED);
7023 
7024     trace_pci_nvme_update_sq_tail(sq->sqid, sq->tail);
7025 }
7026 
7027 static void nvme_process_sq(void *opaque)
7028 {
7029     NvmeSQueue *sq = opaque;
7030     NvmeCtrl *n = sq->ctrl;
7031     NvmeCQueue *cq = n->cq[sq->cqid];
7032 
7033     uint16_t status;
7034     hwaddr addr;
7035     NvmeCmd cmd;
7036     NvmeRequest *req;
7037 
7038     if (n->dbbuf_enabled) {
7039         nvme_update_sq_tail(sq);
7040     }
7041 
7042     while (!(nvme_sq_empty(sq) || QTAILQ_EMPTY(&sq->req_list))) {
7043         addr = sq->dma_addr + (sq->head << NVME_SQES);
7044         if (nvme_addr_read(n, addr, (void *)&cmd, sizeof(cmd))) {
7045             trace_pci_nvme_err_addr_read(addr);
7046             trace_pci_nvme_err_cfs();
7047             stl_le_p(&n->bar.csts, NVME_CSTS_FAILED);
7048             break;
7049         }
7050         nvme_inc_sq_head(sq);
7051 
7052         req = QTAILQ_FIRST(&sq->req_list);
7053         QTAILQ_REMOVE(&sq->req_list, req, entry);
7054         QTAILQ_INSERT_TAIL(&sq->out_req_list, req, entry);
7055         nvme_req_clear(req);
7056         req->cqe.cid = cmd.cid;
7057         memcpy(&req->cmd, &cmd, sizeof(NvmeCmd));
7058 
7059         status = sq->sqid ? nvme_io_cmd(n, req) :
7060             nvme_admin_cmd(n, req);
7061         if (status != NVME_NO_COMPLETE) {
7062             req->status = status;
7063             nvme_enqueue_req_completion(cq, req);
7064         }
7065 
7066         if (n->dbbuf_enabled) {
7067             nvme_update_sq_eventidx(sq);
7068             nvme_update_sq_tail(sq);
7069         }
7070     }
7071 }
7072 
7073 static void nvme_update_msixcap_ts(PCIDevice *pci_dev, uint32_t table_size)
7074 {
7075     uint8_t *config;
7076 
7077     if (!msix_present(pci_dev)) {
7078         return;
7079     }
7080 
7081     assert(table_size > 0 && table_size <= pci_dev->msix_entries_nr);
7082 
7083     config = pci_dev->config + pci_dev->msix_cap;
7084     pci_set_word_by_mask(config + PCI_MSIX_FLAGS, PCI_MSIX_FLAGS_QSIZE,
7085                          table_size - 1);
7086 }
7087 
7088 static void nvme_activate_virt_res(NvmeCtrl *n)
7089 {
7090     PCIDevice *pci_dev = PCI_DEVICE(n);
7091     NvmePriCtrlCap *cap = &n->pri_ctrl_cap;
7092     NvmeSecCtrlEntry *sctrl;
7093 
7094     /* -1 to account for the admin queue */
7095     if (pci_is_vf(pci_dev)) {
7096         sctrl = nvme_sctrl(n);
7097         cap->vqprt = sctrl->nvq;
7098         cap->viprt = sctrl->nvi;
7099         n->conf_ioqpairs = sctrl->nvq ? le16_to_cpu(sctrl->nvq) - 1 : 0;
7100         n->conf_msix_qsize = sctrl->nvi ? le16_to_cpu(sctrl->nvi) : 1;
7101     } else {
7102         cap->vqrfap = n->next_pri_ctrl_cap.vqrfap;
7103         cap->virfap = n->next_pri_ctrl_cap.virfap;
7104         n->conf_ioqpairs = le16_to_cpu(cap->vqprt) +
7105                            le16_to_cpu(cap->vqrfap) - 1;
7106         n->conf_msix_qsize = le16_to_cpu(cap->viprt) +
7107                              le16_to_cpu(cap->virfap);
7108     }
7109 }
7110 
7111 static void nvme_ctrl_reset(NvmeCtrl *n, NvmeResetType rst)
7112 {
7113     PCIDevice *pci_dev = PCI_DEVICE(n);
7114     NvmeSecCtrlEntry *sctrl;
7115     NvmeNamespace *ns;
7116     int i;
7117 
7118     for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
7119         ns = nvme_ns(n, i);
7120         if (!ns) {
7121             continue;
7122         }
7123 
7124         nvme_ns_drain(ns);
7125     }
7126 
7127     for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
7128         if (n->sq[i] != NULL) {
7129             nvme_free_sq(n->sq[i], n);
7130         }
7131     }
7132     for (i = 0; i < n->params.max_ioqpairs + 1; i++) {
7133         if (n->cq[i] != NULL) {
7134             nvme_free_cq(n->cq[i], n);
7135         }
7136     }
7137 
7138     while (!QTAILQ_EMPTY(&n->aer_queue)) {
7139         NvmeAsyncEvent *event = QTAILQ_FIRST(&n->aer_queue);
7140         QTAILQ_REMOVE(&n->aer_queue, event, entry);
7141         g_free(event);
7142     }
7143 
7144     if (n->params.sriov_max_vfs) {
7145         if (!pci_is_vf(pci_dev)) {
7146             for (i = 0; i < n->nr_sec_ctrls; i++) {
7147                 sctrl = &n->sec_ctrl_list[i];
7148                 nvme_virt_set_state(n, le16_to_cpu(sctrl->scid), false);
7149             }
7150         }
7151 
7152         if (rst != NVME_RESET_CONTROLLER) {
7153             nvme_activate_virt_res(n);
7154         }
7155     }
7156 
7157     n->aer_queued = 0;
7158     n->aer_mask = 0;
7159     n->outstanding_aers = 0;
7160     n->qs_created = false;
7161 
7162     nvme_update_msixcap_ts(pci_dev, n->conf_msix_qsize);
7163 
7164     if (pci_is_vf(pci_dev)) {
7165         sctrl = nvme_sctrl(n);
7166 
7167         stl_le_p(&n->bar.csts, sctrl->scs ? 0 : NVME_CSTS_FAILED);
7168     } else {
7169         stl_le_p(&n->bar.csts, 0);
7170     }
7171 
7172     stl_le_p(&n->bar.intms, 0);
7173     stl_le_p(&n->bar.intmc, 0);
7174     stl_le_p(&n->bar.cc, 0);
7175 
7176     n->dbbuf_dbs = 0;
7177     n->dbbuf_eis = 0;
7178     n->dbbuf_enabled = false;
7179 }
7180 
7181 static void nvme_ctrl_shutdown(NvmeCtrl *n)
7182 {
7183     NvmeNamespace *ns;
7184     int i;
7185 
7186     if (n->pmr.dev) {
7187         memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
7188     }
7189 
7190     for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
7191         ns = nvme_ns(n, i);
7192         if (!ns) {
7193             continue;
7194         }
7195 
7196         nvme_ns_shutdown(ns);
7197     }
7198 }
7199 
7200 static void nvme_select_iocs(NvmeCtrl *n)
7201 {
7202     NvmeNamespace *ns;
7203     int i;
7204 
7205     for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
7206         ns = nvme_ns(n, i);
7207         if (!ns) {
7208             continue;
7209         }
7210 
7211         nvme_select_iocs_ns(n, ns);
7212     }
7213 }
7214 
7215 static int nvme_start_ctrl(NvmeCtrl *n)
7216 {
7217     uint64_t cap = ldq_le_p(&n->bar.cap);
7218     uint32_t cc = ldl_le_p(&n->bar.cc);
7219     uint32_t aqa = ldl_le_p(&n->bar.aqa);
7220     uint64_t asq = ldq_le_p(&n->bar.asq);
7221     uint64_t acq = ldq_le_p(&n->bar.acq);
7222     uint32_t page_bits = NVME_CC_MPS(cc) + 12;
7223     uint32_t page_size = 1 << page_bits;
7224     NvmeSecCtrlEntry *sctrl = nvme_sctrl(n);
7225 
7226     if (pci_is_vf(PCI_DEVICE(n)) && !sctrl->scs) {
7227         trace_pci_nvme_err_startfail_virt_state(le16_to_cpu(sctrl->nvi),
7228                                                 le16_to_cpu(sctrl->nvq));
7229         return -1;
7230     }
7231     if (unlikely(n->cq[0])) {
7232         trace_pci_nvme_err_startfail_cq();
7233         return -1;
7234     }
7235     if (unlikely(n->sq[0])) {
7236         trace_pci_nvme_err_startfail_sq();
7237         return -1;
7238     }
7239     if (unlikely(asq & (page_size - 1))) {
7240         trace_pci_nvme_err_startfail_asq_misaligned(asq);
7241         return -1;
7242     }
7243     if (unlikely(acq & (page_size - 1))) {
7244         trace_pci_nvme_err_startfail_acq_misaligned(acq);
7245         return -1;
7246     }
7247     if (unlikely(!(NVME_CAP_CSS(cap) & (1 << NVME_CC_CSS(cc))))) {
7248         trace_pci_nvme_err_startfail_css(NVME_CC_CSS(cc));
7249         return -1;
7250     }
7251     if (unlikely(NVME_CC_MPS(cc) < NVME_CAP_MPSMIN(cap))) {
7252         trace_pci_nvme_err_startfail_page_too_small(
7253                     NVME_CC_MPS(cc),
7254                     NVME_CAP_MPSMIN(cap));
7255         return -1;
7256     }
7257     if (unlikely(NVME_CC_MPS(cc) >
7258                  NVME_CAP_MPSMAX(cap))) {
7259         trace_pci_nvme_err_startfail_page_too_large(
7260                     NVME_CC_MPS(cc),
7261                     NVME_CAP_MPSMAX(cap));
7262         return -1;
7263     }
7264     if (unlikely(!NVME_AQA_ASQS(aqa))) {
7265         trace_pci_nvme_err_startfail_asqent_sz_zero();
7266         return -1;
7267     }
7268     if (unlikely(!NVME_AQA_ACQS(aqa))) {
7269         trace_pci_nvme_err_startfail_acqent_sz_zero();
7270         return -1;
7271     }
7272 
7273     n->page_bits = page_bits;
7274     n->page_size = page_size;
7275     n->max_prp_ents = n->page_size / sizeof(uint64_t);
7276     nvme_init_cq(&n->admin_cq, n, acq, 0, 0, NVME_AQA_ACQS(aqa) + 1, 1);
7277     nvme_init_sq(&n->admin_sq, n, asq, 0, 0, NVME_AQA_ASQS(aqa) + 1);
7278 
7279     nvme_set_timestamp(n, 0ULL);
7280 
7281     nvme_select_iocs(n);
7282 
7283     return 0;
7284 }
7285 
7286 static void nvme_cmb_enable_regs(NvmeCtrl *n)
7287 {
7288     uint32_t cmbloc = ldl_le_p(&n->bar.cmbloc);
7289     uint32_t cmbsz = ldl_le_p(&n->bar.cmbsz);
7290 
7291     NVME_CMBLOC_SET_CDPCILS(cmbloc, 1);
7292     NVME_CMBLOC_SET_CDPMLS(cmbloc, 1);
7293     NVME_CMBLOC_SET_BIR(cmbloc, NVME_CMB_BIR);
7294     stl_le_p(&n->bar.cmbloc, cmbloc);
7295 
7296     NVME_CMBSZ_SET_SQS(cmbsz, 1);
7297     NVME_CMBSZ_SET_CQS(cmbsz, 0);
7298     NVME_CMBSZ_SET_LISTS(cmbsz, 1);
7299     NVME_CMBSZ_SET_RDS(cmbsz, 1);
7300     NVME_CMBSZ_SET_WDS(cmbsz, 1);
7301     NVME_CMBSZ_SET_SZU(cmbsz, 2); /* MBs */
7302     NVME_CMBSZ_SET_SZ(cmbsz, n->params.cmb_size_mb);
7303     stl_le_p(&n->bar.cmbsz, cmbsz);
7304 }
7305 
7306 static void nvme_write_bar(NvmeCtrl *n, hwaddr offset, uint64_t data,
7307                            unsigned size)
7308 {
7309     PCIDevice *pci = PCI_DEVICE(n);
7310     uint64_t cap = ldq_le_p(&n->bar.cap);
7311     uint32_t cc = ldl_le_p(&n->bar.cc);
7312     uint32_t intms = ldl_le_p(&n->bar.intms);
7313     uint32_t csts = ldl_le_p(&n->bar.csts);
7314     uint32_t pmrsts = ldl_le_p(&n->bar.pmrsts);
7315 
7316     if (unlikely(offset & (sizeof(uint32_t) - 1))) {
7317         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_misaligned32,
7318                        "MMIO write not 32-bit aligned,"
7319                        " offset=0x%"PRIx64"", offset);
7320         /* should be ignored, fall through for now */
7321     }
7322 
7323     if (unlikely(size < sizeof(uint32_t))) {
7324         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_toosmall,
7325                        "MMIO write smaller than 32-bits,"
7326                        " offset=0x%"PRIx64", size=%u",
7327                        offset, size);
7328         /* should be ignored, fall through for now */
7329     }
7330 
7331     switch (offset) {
7332     case NVME_REG_INTMS:
7333         if (unlikely(msix_enabled(pci))) {
7334             NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
7335                            "undefined access to interrupt mask set"
7336                            " when MSI-X is enabled");
7337             /* should be ignored, fall through for now */
7338         }
7339         intms |= data;
7340         stl_le_p(&n->bar.intms, intms);
7341         n->bar.intmc = n->bar.intms;
7342         trace_pci_nvme_mmio_intm_set(data & 0xffffffff, intms);
7343         nvme_irq_check(n);
7344         break;
7345     case NVME_REG_INTMC:
7346         if (unlikely(msix_enabled(pci))) {
7347             NVME_GUEST_ERR(pci_nvme_ub_mmiowr_intmask_with_msix,
7348                            "undefined access to interrupt mask clr"
7349                            " when MSI-X is enabled");
7350             /* should be ignored, fall through for now */
7351         }
7352         intms &= ~data;
7353         stl_le_p(&n->bar.intms, intms);
7354         n->bar.intmc = n->bar.intms;
7355         trace_pci_nvme_mmio_intm_clr(data & 0xffffffff, intms);
7356         nvme_irq_check(n);
7357         break;
7358     case NVME_REG_CC:
7359         stl_le_p(&n->bar.cc, data);
7360 
7361         trace_pci_nvme_mmio_cfg(data & 0xffffffff);
7362 
7363         if (NVME_CC_SHN(data) && !(NVME_CC_SHN(cc))) {
7364             trace_pci_nvme_mmio_shutdown_set();
7365             nvme_ctrl_shutdown(n);
7366             csts &= ~(CSTS_SHST_MASK << CSTS_SHST_SHIFT);
7367             csts |= NVME_CSTS_SHST_COMPLETE;
7368         } else if (!NVME_CC_SHN(data) && NVME_CC_SHN(cc)) {
7369             trace_pci_nvme_mmio_shutdown_cleared();
7370             csts &= ~(CSTS_SHST_MASK << CSTS_SHST_SHIFT);
7371         }
7372 
7373         if (NVME_CC_EN(data) && !NVME_CC_EN(cc)) {
7374             if (unlikely(nvme_start_ctrl(n))) {
7375                 trace_pci_nvme_err_startfail();
7376                 csts = NVME_CSTS_FAILED;
7377             } else {
7378                 trace_pci_nvme_mmio_start_success();
7379                 csts = NVME_CSTS_READY;
7380             }
7381         } else if (!NVME_CC_EN(data) && NVME_CC_EN(cc)) {
7382             trace_pci_nvme_mmio_stopped();
7383             nvme_ctrl_reset(n, NVME_RESET_CONTROLLER);
7384 
7385             break;
7386         }
7387 
7388         stl_le_p(&n->bar.csts, csts);
7389 
7390         break;
7391     case NVME_REG_CSTS:
7392         if (data & (1 << 4)) {
7393             NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ssreset_w1c_unsupported,
7394                            "attempted to W1C CSTS.NSSRO"
7395                            " but CAP.NSSRS is zero (not supported)");
7396         } else if (data != 0) {
7397             NVME_GUEST_ERR(pci_nvme_ub_mmiowr_ro_csts,
7398                            "attempted to set a read only bit"
7399                            " of controller status");
7400         }
7401         break;
7402     case NVME_REG_NSSR:
7403         if (data == 0x4e564d65) {
7404             trace_pci_nvme_ub_mmiowr_ssreset_unsupported();
7405         } else {
7406             /* The spec says that writes of other values have no effect */
7407             return;
7408         }
7409         break;
7410     case NVME_REG_AQA:
7411         stl_le_p(&n->bar.aqa, data);
7412         trace_pci_nvme_mmio_aqattr(data & 0xffffffff);
7413         break;
7414     case NVME_REG_ASQ:
7415         stn_le_p(&n->bar.asq, size, data);
7416         trace_pci_nvme_mmio_asqaddr(data);
7417         break;
7418     case NVME_REG_ASQ + 4:
7419         stl_le_p((uint8_t *)&n->bar.asq + 4, data);
7420         trace_pci_nvme_mmio_asqaddr_hi(data, ldq_le_p(&n->bar.asq));
7421         break;
7422     case NVME_REG_ACQ:
7423         trace_pci_nvme_mmio_acqaddr(data);
7424         stn_le_p(&n->bar.acq, size, data);
7425         break;
7426     case NVME_REG_ACQ + 4:
7427         stl_le_p((uint8_t *)&n->bar.acq + 4, data);
7428         trace_pci_nvme_mmio_acqaddr_hi(data, ldq_le_p(&n->bar.acq));
7429         break;
7430     case NVME_REG_CMBLOC:
7431         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbloc_reserved,
7432                        "invalid write to reserved CMBLOC"
7433                        " when CMBSZ is zero, ignored");
7434         return;
7435     case NVME_REG_CMBSZ:
7436         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_cmbsz_readonly,
7437                        "invalid write to read only CMBSZ, ignored");
7438         return;
7439     case NVME_REG_CMBMSC:
7440         if (!NVME_CAP_CMBS(cap)) {
7441             return;
7442         }
7443 
7444         stn_le_p(&n->bar.cmbmsc, size, data);
7445         n->cmb.cmse = false;
7446 
7447         if (NVME_CMBMSC_CRE(data)) {
7448             nvme_cmb_enable_regs(n);
7449 
7450             if (NVME_CMBMSC_CMSE(data)) {
7451                 uint64_t cmbmsc = ldq_le_p(&n->bar.cmbmsc);
7452                 hwaddr cba = NVME_CMBMSC_CBA(cmbmsc) << CMBMSC_CBA_SHIFT;
7453                 if (cba + int128_get64(n->cmb.mem.size) < cba) {
7454                     uint32_t cmbsts = ldl_le_p(&n->bar.cmbsts);
7455                     NVME_CMBSTS_SET_CBAI(cmbsts, 1);
7456                     stl_le_p(&n->bar.cmbsts, cmbsts);
7457                     return;
7458                 }
7459 
7460                 n->cmb.cba = cba;
7461                 n->cmb.cmse = true;
7462             }
7463         } else {
7464             n->bar.cmbsz = 0;
7465             n->bar.cmbloc = 0;
7466         }
7467 
7468         return;
7469     case NVME_REG_CMBMSC + 4:
7470         stl_le_p((uint8_t *)&n->bar.cmbmsc + 4, data);
7471         return;
7472 
7473     case NVME_REG_PMRCAP:
7474         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrcap_readonly,
7475                        "invalid write to PMRCAP register, ignored");
7476         return;
7477     case NVME_REG_PMRCTL:
7478         if (!NVME_CAP_PMRS(cap)) {
7479             return;
7480         }
7481 
7482         stl_le_p(&n->bar.pmrctl, data);
7483         if (NVME_PMRCTL_EN(data)) {
7484             memory_region_set_enabled(&n->pmr.dev->mr, true);
7485             pmrsts = 0;
7486         } else {
7487             memory_region_set_enabled(&n->pmr.dev->mr, false);
7488             NVME_PMRSTS_SET_NRDY(pmrsts, 1);
7489             n->pmr.cmse = false;
7490         }
7491         stl_le_p(&n->bar.pmrsts, pmrsts);
7492         return;
7493     case NVME_REG_PMRSTS:
7494         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrsts_readonly,
7495                        "invalid write to PMRSTS register, ignored");
7496         return;
7497     case NVME_REG_PMREBS:
7498         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrebs_readonly,
7499                        "invalid write to PMREBS register, ignored");
7500         return;
7501     case NVME_REG_PMRSWTP:
7502         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_pmrswtp_readonly,
7503                        "invalid write to PMRSWTP register, ignored");
7504         return;
7505     case NVME_REG_PMRMSCL:
7506         if (!NVME_CAP_PMRS(cap)) {
7507             return;
7508         }
7509 
7510         stl_le_p(&n->bar.pmrmscl, data);
7511         n->pmr.cmse = false;
7512 
7513         if (NVME_PMRMSCL_CMSE(data)) {
7514             uint64_t pmrmscu = ldl_le_p(&n->bar.pmrmscu);
7515             hwaddr cba = pmrmscu << 32 |
7516                 (NVME_PMRMSCL_CBA(data) << PMRMSCL_CBA_SHIFT);
7517             if (cba + int128_get64(n->pmr.dev->mr.size) < cba) {
7518                 NVME_PMRSTS_SET_CBAI(pmrsts, 1);
7519                 stl_le_p(&n->bar.pmrsts, pmrsts);
7520                 return;
7521             }
7522 
7523             n->pmr.cmse = true;
7524             n->pmr.cba = cba;
7525         }
7526 
7527         return;
7528     case NVME_REG_PMRMSCU:
7529         if (!NVME_CAP_PMRS(cap)) {
7530             return;
7531         }
7532 
7533         stl_le_p(&n->bar.pmrmscu, data);
7534         return;
7535     default:
7536         NVME_GUEST_ERR(pci_nvme_ub_mmiowr_invalid,
7537                        "invalid MMIO write,"
7538                        " offset=0x%"PRIx64", data=%"PRIx64"",
7539                        offset, data);
7540         break;
7541     }
7542 }
7543 
7544 static uint64_t nvme_mmio_read(void *opaque, hwaddr addr, unsigned size)
7545 {
7546     NvmeCtrl *n = (NvmeCtrl *)opaque;
7547     uint8_t *ptr = (uint8_t *)&n->bar;
7548 
7549     trace_pci_nvme_mmio_read(addr, size);
7550 
7551     if (unlikely(addr & (sizeof(uint32_t) - 1))) {
7552         NVME_GUEST_ERR(pci_nvme_ub_mmiord_misaligned32,
7553                        "MMIO read not 32-bit aligned,"
7554                        " offset=0x%"PRIx64"", addr);
7555         /* should RAZ, fall through for now */
7556     } else if (unlikely(size < sizeof(uint32_t))) {
7557         NVME_GUEST_ERR(pci_nvme_ub_mmiord_toosmall,
7558                        "MMIO read smaller than 32-bits,"
7559                        " offset=0x%"PRIx64"", addr);
7560         /* should RAZ, fall through for now */
7561     }
7562 
7563     if (addr > sizeof(n->bar) - size) {
7564         NVME_GUEST_ERR(pci_nvme_ub_mmiord_invalid_ofs,
7565                        "MMIO read beyond last register,"
7566                        " offset=0x%"PRIx64", returning 0", addr);
7567 
7568         return 0;
7569     }
7570 
7571     if (pci_is_vf(PCI_DEVICE(n)) && !nvme_sctrl(n)->scs &&
7572         addr != NVME_REG_CSTS) {
7573         trace_pci_nvme_err_ignored_mmio_vf_offline(addr, size);
7574         return 0;
7575     }
7576 
7577     /*
7578      * When PMRWBM bit 1 is set then read from
7579      * from PMRSTS should ensure prior writes
7580      * made it to persistent media
7581      */
7582     if (addr == NVME_REG_PMRSTS &&
7583         (NVME_PMRCAP_PMRWBM(ldl_le_p(&n->bar.pmrcap)) & 0x02)) {
7584         memory_region_msync(&n->pmr.dev->mr, 0, n->pmr.dev->size);
7585     }
7586 
7587     return ldn_le_p(ptr + addr, size);
7588 }
7589 
7590 static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)
7591 {
7592     PCIDevice *pci = PCI_DEVICE(n);
7593     uint32_t qid;
7594 
7595     if (unlikely(addr & ((1 << 2) - 1))) {
7596         NVME_GUEST_ERR(pci_nvme_ub_db_wr_misaligned,
7597                        "doorbell write not 32-bit aligned,"
7598                        " offset=0x%"PRIx64", ignoring", addr);
7599         return;
7600     }
7601 
7602     if (((addr - 0x1000) >> 2) & 1) {
7603         /* Completion queue doorbell write */
7604 
7605         uint16_t new_head = val & 0xffff;
7606         int start_sqs;
7607         NvmeCQueue *cq;
7608 
7609         qid = (addr - (0x1000 + (1 << 2))) >> 3;
7610         if (unlikely(nvme_check_cqid(n, qid))) {
7611             NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cq,
7612                            "completion queue doorbell write"
7613                            " for nonexistent queue,"
7614                            " sqid=%"PRIu32", ignoring", qid);
7615 
7616             /*
7617              * NVM Express v1.3d, Section 4.1 state: "If host software writes
7618              * an invalid value to the Submission Queue Tail Doorbell or
7619              * Completion Queue Head Doorbell register and an Asynchronous Event
7620              * Request command is outstanding, then an asynchronous event is
7621              * posted to the Admin Completion Queue with a status code of
7622              * Invalid Doorbell Write Value."
7623              *
7624              * Also note that the spec includes the "Invalid Doorbell Register"
7625              * status code, but nowhere does it specify when to use it.
7626              * However, it seems reasonable to use it here in a similar
7627              * fashion.
7628              */
7629             if (n->outstanding_aers) {
7630                 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7631                                    NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
7632                                    NVME_LOG_ERROR_INFO);
7633             }
7634 
7635             return;
7636         }
7637 
7638         cq = n->cq[qid];
7639         if (unlikely(new_head >= cq->size)) {
7640             NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_cqhead,
7641                            "completion queue doorbell write value"
7642                            " beyond queue size, sqid=%"PRIu32","
7643                            " new_head=%"PRIu16", ignoring",
7644                            qid, new_head);
7645 
7646             if (n->outstanding_aers) {
7647                 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7648                                    NVME_AER_INFO_ERR_INVALID_DB_VALUE,
7649                                    NVME_LOG_ERROR_INFO);
7650             }
7651 
7652             return;
7653         }
7654 
7655         trace_pci_nvme_mmio_doorbell_cq(cq->cqid, new_head);
7656 
7657         start_sqs = nvme_cq_full(cq) ? 1 : 0;
7658         cq->head = new_head;
7659         if (!qid && n->dbbuf_enabled) {
7660             stl_le_pci_dma(pci, cq->db_addr, cq->head, MEMTXATTRS_UNSPECIFIED);
7661         }
7662         if (start_sqs) {
7663             NvmeSQueue *sq;
7664             QTAILQ_FOREACH(sq, &cq->sq_list, entry) {
7665                 qemu_bh_schedule(sq->bh);
7666             }
7667             qemu_bh_schedule(cq->bh);
7668         }
7669 
7670         if (cq->tail == cq->head) {
7671             if (cq->irq_enabled) {
7672                 n->cq_pending--;
7673             }
7674 
7675             nvme_irq_deassert(n, cq);
7676         }
7677     } else {
7678         /* Submission queue doorbell write */
7679 
7680         uint16_t new_tail = val & 0xffff;
7681         NvmeSQueue *sq;
7682 
7683         qid = (addr - 0x1000) >> 3;
7684         if (unlikely(nvme_check_sqid(n, qid))) {
7685             NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sq,
7686                            "submission queue doorbell write"
7687                            " for nonexistent queue,"
7688                            " sqid=%"PRIu32", ignoring", qid);
7689 
7690             if (n->outstanding_aers) {
7691                 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7692                                    NVME_AER_INFO_ERR_INVALID_DB_REGISTER,
7693                                    NVME_LOG_ERROR_INFO);
7694             }
7695 
7696             return;
7697         }
7698 
7699         sq = n->sq[qid];
7700         if (unlikely(new_tail >= sq->size)) {
7701             NVME_GUEST_ERR(pci_nvme_ub_db_wr_invalid_sqtail,
7702                            "submission queue doorbell write value"
7703                            " beyond queue size, sqid=%"PRIu32","
7704                            " new_tail=%"PRIu16", ignoring",
7705                            qid, new_tail);
7706 
7707             if (n->outstanding_aers) {
7708                 nvme_enqueue_event(n, NVME_AER_TYPE_ERROR,
7709                                    NVME_AER_INFO_ERR_INVALID_DB_VALUE,
7710                                    NVME_LOG_ERROR_INFO);
7711             }
7712 
7713             return;
7714         }
7715 
7716         trace_pci_nvme_mmio_doorbell_sq(sq->sqid, new_tail);
7717 
7718         sq->tail = new_tail;
7719         if (!qid && n->dbbuf_enabled) {
7720             /*
7721              * The spec states "the host shall also update the controller's
7722              * corresponding doorbell property to match the value of that entry
7723              * in the Shadow Doorbell buffer."
7724              *
7725              * Since this context is currently a VM trap, we can safely enforce
7726              * the requirement from the device side in case the host is
7727              * misbehaving.
7728              *
7729              * Note, we shouldn't have to do this, but various drivers
7730              * including ones that run on Linux, are not updating Admin Queues,
7731              * so we can't trust reading it for an appropriate sq tail.
7732              */
7733             stl_le_pci_dma(pci, sq->db_addr, sq->tail, MEMTXATTRS_UNSPECIFIED);
7734         }
7735 
7736         qemu_bh_schedule(sq->bh);
7737     }
7738 }
7739 
7740 static void nvme_mmio_write(void *opaque, hwaddr addr, uint64_t data,
7741                             unsigned size)
7742 {
7743     NvmeCtrl *n = (NvmeCtrl *)opaque;
7744 
7745     trace_pci_nvme_mmio_write(addr, data, size);
7746 
7747     if (pci_is_vf(PCI_DEVICE(n)) && !nvme_sctrl(n)->scs &&
7748         addr != NVME_REG_CSTS) {
7749         trace_pci_nvme_err_ignored_mmio_vf_offline(addr, size);
7750         return;
7751     }
7752 
7753     if (addr < sizeof(n->bar)) {
7754         nvme_write_bar(n, addr, data, size);
7755     } else {
7756         nvme_process_db(n, addr, data);
7757     }
7758 }
7759 
7760 static const MemoryRegionOps nvme_mmio_ops = {
7761     .read = nvme_mmio_read,
7762     .write = nvme_mmio_write,
7763     .endianness = DEVICE_LITTLE_ENDIAN,
7764     .impl = {
7765         .min_access_size = 2,
7766         .max_access_size = 8,
7767     },
7768 };
7769 
7770 static void nvme_cmb_write(void *opaque, hwaddr addr, uint64_t data,
7771                            unsigned size)
7772 {
7773     NvmeCtrl *n = (NvmeCtrl *)opaque;
7774     stn_le_p(&n->cmb.buf[addr], size, data);
7775 }
7776 
7777 static uint64_t nvme_cmb_read(void *opaque, hwaddr addr, unsigned size)
7778 {
7779     NvmeCtrl *n = (NvmeCtrl *)opaque;
7780     return ldn_le_p(&n->cmb.buf[addr], size);
7781 }
7782 
7783 static const MemoryRegionOps nvme_cmb_ops = {
7784     .read = nvme_cmb_read,
7785     .write = nvme_cmb_write,
7786     .endianness = DEVICE_LITTLE_ENDIAN,
7787     .impl = {
7788         .min_access_size = 1,
7789         .max_access_size = 8,
7790     },
7791 };
7792 
7793 static bool nvme_check_params(NvmeCtrl *n, Error **errp)
7794 {
7795     NvmeParams *params = &n->params;
7796 
7797     if (params->num_queues) {
7798         warn_report("num_queues is deprecated; please use max_ioqpairs "
7799                     "instead");
7800 
7801         params->max_ioqpairs = params->num_queues - 1;
7802     }
7803 
7804     if (n->namespace.blkconf.blk && n->subsys) {
7805         error_setg(errp, "subsystem support is unavailable with legacy "
7806                    "namespace ('drive' property)");
7807         return false;
7808     }
7809 
7810     if (params->max_ioqpairs < 1 ||
7811         params->max_ioqpairs > NVME_MAX_IOQPAIRS) {
7812         error_setg(errp, "max_ioqpairs must be between 1 and %d",
7813                    NVME_MAX_IOQPAIRS);
7814         return false;
7815     }
7816 
7817     if (params->msix_qsize < 1 ||
7818         params->msix_qsize > PCI_MSIX_FLAGS_QSIZE + 1) {
7819         error_setg(errp, "msix_qsize must be between 1 and %d",
7820                    PCI_MSIX_FLAGS_QSIZE + 1);
7821         return false;
7822     }
7823 
7824     if (!params->serial) {
7825         error_setg(errp, "serial property not set");
7826         return false;
7827     }
7828 
7829     if (params->mqes < 1) {
7830         error_setg(errp, "mqes property cannot be less than 1");
7831         return false;
7832     }
7833 
7834     if (n->pmr.dev) {
7835         if (params->msix_exclusive_bar) {
7836             error_setg(errp, "not enough BARs available to enable PMR");
7837             return false;
7838         }
7839 
7840         if (host_memory_backend_is_mapped(n->pmr.dev)) {
7841             error_setg(errp, "can't use already busy memdev: %s",
7842                        object_get_canonical_path_component(OBJECT(n->pmr.dev)));
7843             return false;
7844         }
7845 
7846         if (!is_power_of_2(n->pmr.dev->size)) {
7847             error_setg(errp, "pmr backend size needs to be power of 2 in size");
7848             return false;
7849         }
7850 
7851         host_memory_backend_set_mapped(n->pmr.dev, true);
7852     }
7853 
7854     if (n->params.zasl > n->params.mdts) {
7855         error_setg(errp, "zoned.zasl (Zone Append Size Limit) must be less "
7856                    "than or equal to mdts (Maximum Data Transfer Size)");
7857         return false;
7858     }
7859 
7860     if (!n->params.vsl) {
7861         error_setg(errp, "vsl must be non-zero");
7862         return false;
7863     }
7864 
7865     if (params->sriov_max_vfs) {
7866         if (!n->subsys) {
7867             error_setg(errp, "subsystem is required for the use of SR-IOV");
7868             return false;
7869         }
7870 
7871         if (params->cmb_size_mb) {
7872             error_setg(errp, "CMB is not supported with SR-IOV");
7873             return false;
7874         }
7875 
7876         if (n->pmr.dev) {
7877             error_setg(errp, "PMR is not supported with SR-IOV");
7878             return false;
7879         }
7880 
7881         if (!params->sriov_vq_flexible || !params->sriov_vi_flexible) {
7882             error_setg(errp, "both sriov_vq_flexible and sriov_vi_flexible"
7883                        " must be set for the use of SR-IOV");
7884             return false;
7885         }
7886 
7887         if (params->sriov_vq_flexible < params->sriov_max_vfs * 2) {
7888             error_setg(errp, "sriov_vq_flexible must be greater than or equal"
7889                        " to %d (sriov_max_vfs * 2)", params->sriov_max_vfs * 2);
7890             return false;
7891         }
7892 
7893         if (params->max_ioqpairs < params->sriov_vq_flexible + 2) {
7894             error_setg(errp, "(max_ioqpairs - sriov_vq_flexible) must be"
7895                        " greater than or equal to 2");
7896             return false;
7897         }
7898 
7899         if (params->sriov_vi_flexible < params->sriov_max_vfs) {
7900             error_setg(errp, "sriov_vi_flexible must be greater than or equal"
7901                        " to %d (sriov_max_vfs)", params->sriov_max_vfs);
7902             return false;
7903         }
7904 
7905         if (params->msix_qsize < params->sriov_vi_flexible + 1) {
7906             error_setg(errp, "(msix_qsize - sriov_vi_flexible) must be"
7907                        " greater than or equal to 1");
7908             return false;
7909         }
7910 
7911         if (params->sriov_max_vi_per_vf &&
7912             (params->sriov_max_vi_per_vf - 1) % NVME_VF_RES_GRANULARITY) {
7913             error_setg(errp, "sriov_max_vi_per_vf must meet:"
7914                        " (sriov_max_vi_per_vf - 1) %% %d == 0 and"
7915                        " sriov_max_vi_per_vf >= 1", NVME_VF_RES_GRANULARITY);
7916             return false;
7917         }
7918 
7919         if (params->sriov_max_vq_per_vf &&
7920             (params->sriov_max_vq_per_vf < 2 ||
7921              (params->sriov_max_vq_per_vf - 1) % NVME_VF_RES_GRANULARITY)) {
7922             error_setg(errp, "sriov_max_vq_per_vf must meet:"
7923                        " (sriov_max_vq_per_vf - 1) %% %d == 0 and"
7924                        " sriov_max_vq_per_vf >= 2", NVME_VF_RES_GRANULARITY);
7925             return false;
7926         }
7927     }
7928 
7929     return true;
7930 }
7931 
7932 static void nvme_init_state(NvmeCtrl *n)
7933 {
7934     NvmePriCtrlCap *cap = &n->pri_ctrl_cap;
7935     NvmeSecCtrlEntry *list = n->sec_ctrl_list;
7936     NvmeSecCtrlEntry *sctrl;
7937     PCIDevice *pci = PCI_DEVICE(n);
7938     uint8_t max_vfs;
7939     int i;
7940 
7941     if (pci_is_vf(pci)) {
7942         sctrl = nvme_sctrl(n);
7943         max_vfs = 0;
7944         n->conf_ioqpairs = sctrl->nvq ? le16_to_cpu(sctrl->nvq) - 1 : 0;
7945         n->conf_msix_qsize = sctrl->nvi ? le16_to_cpu(sctrl->nvi) : 1;
7946     } else {
7947         max_vfs = n->params.sriov_max_vfs;
7948         n->conf_ioqpairs = n->params.max_ioqpairs;
7949         n->conf_msix_qsize = n->params.msix_qsize;
7950     }
7951 
7952     n->sq = g_new0(NvmeSQueue *, n->params.max_ioqpairs + 1);
7953     n->cq = g_new0(NvmeCQueue *, n->params.max_ioqpairs + 1);
7954     n->temperature = NVME_TEMPERATURE;
7955     n->features.temp_thresh_hi = NVME_TEMPERATURE_WARNING;
7956     n->starttime_ms = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
7957     n->aer_reqs = g_new0(NvmeRequest *, n->params.aerl + 1);
7958     QTAILQ_INIT(&n->aer_queue);
7959 
7960     n->nr_sec_ctrls = max_vfs;
7961     for (i = 0; i < max_vfs; i++) {
7962         sctrl = &list[i];
7963         sctrl->pcid = cpu_to_le16(n->cntlid);
7964         sctrl->vfn = cpu_to_le16(i + 1);
7965     }
7966 
7967     cap->cntlid = cpu_to_le16(n->cntlid);
7968     cap->crt = NVME_CRT_VQ | NVME_CRT_VI;
7969 
7970     if (pci_is_vf(pci)) {
7971         cap->vqprt = cpu_to_le16(1 + n->conf_ioqpairs);
7972     } else {
7973         cap->vqprt = cpu_to_le16(1 + n->params.max_ioqpairs -
7974                                  n->params.sriov_vq_flexible);
7975         cap->vqfrt = cpu_to_le32(n->params.sriov_vq_flexible);
7976         cap->vqrfap = cap->vqfrt;
7977         cap->vqgran = cpu_to_le16(NVME_VF_RES_GRANULARITY);
7978         cap->vqfrsm = n->params.sriov_max_vq_per_vf ?
7979                         cpu_to_le16(n->params.sriov_max_vq_per_vf) :
7980                         cap->vqfrt / MAX(max_vfs, 1);
7981     }
7982 
7983     if (pci_is_vf(pci)) {
7984         cap->viprt = cpu_to_le16(n->conf_msix_qsize);
7985     } else {
7986         cap->viprt = cpu_to_le16(n->params.msix_qsize -
7987                                  n->params.sriov_vi_flexible);
7988         cap->vifrt = cpu_to_le32(n->params.sriov_vi_flexible);
7989         cap->virfap = cap->vifrt;
7990         cap->vigran = cpu_to_le16(NVME_VF_RES_GRANULARITY);
7991         cap->vifrsm = n->params.sriov_max_vi_per_vf ?
7992                         cpu_to_le16(n->params.sriov_max_vi_per_vf) :
7993                         cap->vifrt / MAX(max_vfs, 1);
7994     }
7995 }
7996 
7997 static void nvme_init_cmb(NvmeCtrl *n, PCIDevice *pci_dev)
7998 {
7999     uint64_t cmb_size = n->params.cmb_size_mb * MiB;
8000     uint64_t cap = ldq_le_p(&n->bar.cap);
8001 
8002     n->cmb.buf = g_malloc0(cmb_size);
8003     memory_region_init_io(&n->cmb.mem, OBJECT(n), &nvme_cmb_ops, n,
8004                           "nvme-cmb", cmb_size);
8005     pci_register_bar(pci_dev, NVME_CMB_BIR,
8006                      PCI_BASE_ADDRESS_SPACE_MEMORY |
8007                      PCI_BASE_ADDRESS_MEM_TYPE_64 |
8008                      PCI_BASE_ADDRESS_MEM_PREFETCH, &n->cmb.mem);
8009 
8010     NVME_CAP_SET_CMBS(cap, 1);
8011     stq_le_p(&n->bar.cap, cap);
8012 
8013     if (n->params.legacy_cmb) {
8014         nvme_cmb_enable_regs(n);
8015         n->cmb.cmse = true;
8016     }
8017 }
8018 
8019 static void nvme_init_pmr(NvmeCtrl *n, PCIDevice *pci_dev)
8020 {
8021     uint32_t pmrcap = ldl_le_p(&n->bar.pmrcap);
8022 
8023     NVME_PMRCAP_SET_RDS(pmrcap, 1);
8024     NVME_PMRCAP_SET_WDS(pmrcap, 1);
8025     NVME_PMRCAP_SET_BIR(pmrcap, NVME_PMR_BIR);
8026     /* Turn on bit 1 support */
8027     NVME_PMRCAP_SET_PMRWBM(pmrcap, 0x02);
8028     NVME_PMRCAP_SET_CMSS(pmrcap, 1);
8029     stl_le_p(&n->bar.pmrcap, pmrcap);
8030 
8031     pci_register_bar(pci_dev, NVME_PMR_BIR,
8032                      PCI_BASE_ADDRESS_SPACE_MEMORY |
8033                      PCI_BASE_ADDRESS_MEM_TYPE_64 |
8034                      PCI_BASE_ADDRESS_MEM_PREFETCH, &n->pmr.dev->mr);
8035 
8036     memory_region_set_enabled(&n->pmr.dev->mr, false);
8037 }
8038 
8039 static uint64_t nvme_mbar_size(unsigned total_queues, unsigned total_irqs,
8040                                unsigned *msix_table_offset,
8041                                unsigned *msix_pba_offset)
8042 {
8043     uint64_t bar_size, msix_table_size;
8044 
8045     bar_size = sizeof(NvmeBar) + 2 * total_queues * NVME_DB_SIZE;
8046 
8047     if (total_irqs == 0) {
8048         goto out;
8049     }
8050 
8051     bar_size = QEMU_ALIGN_UP(bar_size, 4 * KiB);
8052 
8053     if (msix_table_offset) {
8054         *msix_table_offset = bar_size;
8055     }
8056 
8057     msix_table_size = PCI_MSIX_ENTRY_SIZE * total_irqs;
8058     bar_size += msix_table_size;
8059     bar_size = QEMU_ALIGN_UP(bar_size, 4 * KiB);
8060 
8061     if (msix_pba_offset) {
8062         *msix_pba_offset = bar_size;
8063     }
8064 
8065     bar_size += QEMU_ALIGN_UP(total_irqs, 64) / 8;
8066 
8067 out:
8068     return pow2ceil(bar_size);
8069 }
8070 
8071 static bool nvme_init_sriov(NvmeCtrl *n, PCIDevice *pci_dev, uint16_t offset,
8072                             Error **errp)
8073 {
8074     uint16_t vf_dev_id = n->params.use_intel_id ?
8075                          PCI_DEVICE_ID_INTEL_NVME : PCI_DEVICE_ID_REDHAT_NVME;
8076     NvmePriCtrlCap *cap = &n->pri_ctrl_cap;
8077     uint64_t bar_size = nvme_mbar_size(le16_to_cpu(cap->vqfrsm),
8078                                       le16_to_cpu(cap->vifrsm),
8079                                       NULL, NULL);
8080 
8081     if (!pcie_sriov_pf_init(pci_dev, offset, "nvme", vf_dev_id,
8082                             n->params.sriov_max_vfs, n->params.sriov_max_vfs,
8083                             NVME_VF_OFFSET, NVME_VF_STRIDE,
8084                             errp)) {
8085         return false;
8086     }
8087 
8088     pcie_sriov_pf_init_vf_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |
8089                               PCI_BASE_ADDRESS_MEM_TYPE_64, bar_size);
8090 
8091     return true;
8092 }
8093 
8094 static int nvme_add_pm_capability(PCIDevice *pci_dev, uint8_t offset)
8095 {
8096     Error *err = NULL;
8097     int ret;
8098 
8099     ret = pci_add_capability(pci_dev, PCI_CAP_ID_PM, offset,
8100                              PCI_PM_SIZEOF, &err);
8101     if (err) {
8102         error_report_err(err);
8103         return ret;
8104     }
8105 
8106     pci_set_word(pci_dev->config + offset + PCI_PM_PMC,
8107                  PCI_PM_CAP_VER_1_2);
8108     pci_set_word(pci_dev->config + offset + PCI_PM_CTRL,
8109                  PCI_PM_CTRL_NO_SOFT_RESET);
8110     pci_set_word(pci_dev->wmask + offset + PCI_PM_CTRL,
8111                  PCI_PM_CTRL_STATE_MASK);
8112 
8113     return 0;
8114 }
8115 
8116 static bool nvme_init_pci(NvmeCtrl *n, PCIDevice *pci_dev, Error **errp)
8117 {
8118     ERRP_GUARD();
8119     uint8_t *pci_conf = pci_dev->config;
8120     uint64_t bar_size;
8121     unsigned msix_table_offset = 0, msix_pba_offset = 0;
8122     unsigned nr_vectors;
8123     int ret;
8124 
8125     pci_conf[PCI_INTERRUPT_PIN] = 1;
8126     pci_config_set_prog_interface(pci_conf, 0x2);
8127 
8128     if (n->params.use_intel_id) {
8129         pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);
8130         pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_INTEL_NVME);
8131     } else {
8132         pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REDHAT);
8133         pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REDHAT_NVME);
8134     }
8135 
8136     pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_EXPRESS);
8137     nvme_add_pm_capability(pci_dev, 0x60);
8138     pcie_endpoint_cap_init(pci_dev, 0x80);
8139     pcie_cap_flr_init(pci_dev);
8140     if (n->params.sriov_max_vfs) {
8141         pcie_ari_init(pci_dev, 0x100);
8142     }
8143 
8144     if (n->params.msix_exclusive_bar && !pci_is_vf(pci_dev)) {
8145         bar_size = nvme_mbar_size(n->params.max_ioqpairs + 1, 0, NULL, NULL);
8146         memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, "nvme",
8147                               bar_size);
8148         pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |
8149                          PCI_BASE_ADDRESS_MEM_TYPE_64, &n->iomem);
8150         ret = msix_init_exclusive_bar(pci_dev, n->params.msix_qsize, 4, errp);
8151     } else {
8152         assert(n->params.msix_qsize >= 1);
8153 
8154         /* add one to max_ioqpairs to account for the admin queue pair */
8155         if (!pci_is_vf(pci_dev)) {
8156             nr_vectors = n->params.msix_qsize;
8157             bar_size = nvme_mbar_size(n->params.max_ioqpairs + 1,
8158                                       nr_vectors, &msix_table_offset,
8159                                       &msix_pba_offset);
8160         } else {
8161             NvmeCtrl *pn = NVME(pcie_sriov_get_pf(pci_dev));
8162             NvmePriCtrlCap *cap = &pn->pri_ctrl_cap;
8163 
8164             nr_vectors = le16_to_cpu(cap->vifrsm);
8165             bar_size = nvme_mbar_size(le16_to_cpu(cap->vqfrsm), nr_vectors,
8166                                       &msix_table_offset, &msix_pba_offset);
8167         }
8168 
8169         memory_region_init(&n->bar0, OBJECT(n), "nvme-bar0", bar_size);
8170         memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, "nvme",
8171                               msix_table_offset);
8172         memory_region_add_subregion(&n->bar0, 0, &n->iomem);
8173 
8174         if (pci_is_vf(pci_dev)) {
8175             pcie_sriov_vf_register_bar(pci_dev, 0, &n->bar0);
8176         } else {
8177             pci_register_bar(pci_dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY |
8178                              PCI_BASE_ADDRESS_MEM_TYPE_64, &n->bar0);
8179         }
8180 
8181         ret = msix_init(pci_dev, nr_vectors,
8182                         &n->bar0, 0, msix_table_offset,
8183                         &n->bar0, 0, msix_pba_offset, 0, errp);
8184     }
8185 
8186     if (ret == -ENOTSUP) {
8187         /* report that msix is not supported, but do not error out */
8188         warn_report_err(*errp);
8189         *errp = NULL;
8190     } else if (ret < 0) {
8191         /* propagate error to caller */
8192         return false;
8193     }
8194 
8195     if (!pci_is_vf(pci_dev) && n->params.sriov_max_vfs &&
8196         !nvme_init_sriov(n, pci_dev, 0x120, errp)) {
8197         msix_uninit(pci_dev, &n->bar0, &n->bar0);
8198         return false;
8199     }
8200 
8201     nvme_update_msixcap_ts(pci_dev, n->conf_msix_qsize);
8202 
8203     if (n->params.cmb_size_mb) {
8204         nvme_init_cmb(n, pci_dev);
8205     }
8206 
8207     if (n->pmr.dev) {
8208         nvme_init_pmr(n, pci_dev);
8209     }
8210 
8211     return true;
8212 }
8213 
8214 static void nvme_init_subnqn(NvmeCtrl *n)
8215 {
8216     NvmeSubsystem *subsys = n->subsys;
8217     NvmeIdCtrl *id = &n->id_ctrl;
8218 
8219     if (!subsys) {
8220         snprintf((char *)id->subnqn, sizeof(id->subnqn),
8221                  "nqn.2019-08.org.qemu:%s", n->params.serial);
8222     } else {
8223         pstrcpy((char *)id->subnqn, sizeof(id->subnqn), (char*)subsys->subnqn);
8224     }
8225 }
8226 
8227 static void nvme_init_ctrl(NvmeCtrl *n, PCIDevice *pci_dev)
8228 {
8229     NvmeIdCtrl *id = &n->id_ctrl;
8230     uint8_t *pci_conf = pci_dev->config;
8231     uint64_t cap = ldq_le_p(&n->bar.cap);
8232     NvmeSecCtrlEntry *sctrl = nvme_sctrl(n);
8233     uint32_t ctratt;
8234 
8235     id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID));
8236     id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID));
8237     strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' ');
8238     strpadcpy((char *)id->fr, sizeof(id->fr), QEMU_VERSION, ' ');
8239     strpadcpy((char *)id->sn, sizeof(id->sn), n->params.serial, ' ');
8240 
8241     id->cntlid = cpu_to_le16(n->cntlid);
8242 
8243     id->oaes = cpu_to_le32(NVME_OAES_NS_ATTR);
8244     ctratt = NVME_CTRATT_ELBAS;
8245 
8246     id->rab = 6;
8247 
8248     if (n->params.use_intel_id) {
8249         id->ieee[0] = 0xb3;
8250         id->ieee[1] = 0x02;
8251         id->ieee[2] = 0x00;
8252     } else {
8253         id->ieee[0] = 0x00;
8254         id->ieee[1] = 0x54;
8255         id->ieee[2] = 0x52;
8256     }
8257 
8258     id->mdts = n->params.mdts;
8259     id->ver = cpu_to_le32(NVME_SPEC_VER);
8260     id->oacs =
8261         cpu_to_le16(NVME_OACS_NS_MGMT | NVME_OACS_FORMAT | NVME_OACS_DBBUF |
8262                     NVME_OACS_DIRECTIVES);
8263     id->cntrltype = 0x1;
8264 
8265     /*
8266      * Because the controller always completes the Abort command immediately,
8267      * there can never be more than one concurrently executing Abort command,
8268      * so this value is never used for anything. Note that there can easily be
8269      * many Abort commands in the queues, but they are not considered
8270      * "executing" until processed by nvme_abort.
8271      *
8272      * The specification recommends a value of 3 for Abort Command Limit (four
8273      * concurrently outstanding Abort commands), so lets use that though it is
8274      * inconsequential.
8275      */
8276     id->acl = 3;
8277     id->aerl = n->params.aerl;
8278     id->frmw = (NVME_NUM_FW_SLOTS << 1) | NVME_FRMW_SLOT1_RO;
8279     id->lpa = NVME_LPA_NS_SMART | NVME_LPA_CSE | NVME_LPA_EXTENDED;
8280 
8281     /* recommended default value (~70 C) */
8282     id->wctemp = cpu_to_le16(NVME_TEMPERATURE_WARNING);
8283     id->cctemp = cpu_to_le16(NVME_TEMPERATURE_CRITICAL);
8284 
8285     id->sqes = (NVME_SQES << 4) | NVME_SQES;
8286     id->cqes = (NVME_CQES << 4) | NVME_CQES;
8287     id->nn = cpu_to_le32(NVME_MAX_NAMESPACES);
8288     id->oncs = cpu_to_le16(NVME_ONCS_WRITE_ZEROES | NVME_ONCS_TIMESTAMP |
8289                            NVME_ONCS_FEATURES | NVME_ONCS_DSM |
8290                            NVME_ONCS_COMPARE | NVME_ONCS_COPY);
8291 
8292     /*
8293      * NOTE: If this device ever supports a command set that does NOT use 0x0
8294      * as a Flush-equivalent operation, support for the broadcast NSID in Flush
8295      * should probably be removed.
8296      *
8297      * See comment in nvme_io_cmd.
8298      */
8299     id->vwc = NVME_VWC_NSID_BROADCAST_SUPPORT | NVME_VWC_PRESENT;
8300 
8301     id->ocfs = cpu_to_le16(NVME_OCFS_COPY_FORMAT_0 | NVME_OCFS_COPY_FORMAT_1);
8302     id->sgls = cpu_to_le32(NVME_CTRL_SGLS_SUPPORT_NO_ALIGN);
8303 
8304     nvme_init_subnqn(n);
8305 
8306     id->psd[0].mp = cpu_to_le16(0x9c4);
8307     id->psd[0].enlat = cpu_to_le32(0x10);
8308     id->psd[0].exlat = cpu_to_le32(0x4);
8309 
8310     if (n->subsys) {
8311         id->cmic |= NVME_CMIC_MULTI_CTRL;
8312         ctratt |= NVME_CTRATT_ENDGRPS;
8313 
8314         id->endgidmax = cpu_to_le16(0x1);
8315 
8316         if (n->subsys->endgrp.fdp.enabled) {
8317             ctratt |= NVME_CTRATT_FDPS;
8318         }
8319     }
8320 
8321     id->ctratt = cpu_to_le32(ctratt);
8322 
8323     NVME_CAP_SET_MQES(cap, n->params.mqes);
8324     NVME_CAP_SET_CQR(cap, 1);
8325     NVME_CAP_SET_TO(cap, 0xf);
8326     NVME_CAP_SET_CSS(cap, NVME_CAP_CSS_NVM);
8327     NVME_CAP_SET_CSS(cap, NVME_CAP_CSS_CSI_SUPP);
8328     NVME_CAP_SET_CSS(cap, NVME_CAP_CSS_ADMIN_ONLY);
8329     NVME_CAP_SET_MPSMAX(cap, 4);
8330     NVME_CAP_SET_CMBS(cap, n->params.cmb_size_mb ? 1 : 0);
8331     NVME_CAP_SET_PMRS(cap, n->pmr.dev ? 1 : 0);
8332     stq_le_p(&n->bar.cap, cap);
8333 
8334     stl_le_p(&n->bar.vs, NVME_SPEC_VER);
8335     n->bar.intmc = n->bar.intms = 0;
8336 
8337     if (pci_is_vf(pci_dev) && !sctrl->scs) {
8338         stl_le_p(&n->bar.csts, NVME_CSTS_FAILED);
8339     }
8340 }
8341 
8342 static int nvme_init_subsys(NvmeCtrl *n, Error **errp)
8343 {
8344     int cntlid;
8345 
8346     if (!n->subsys) {
8347         return 0;
8348     }
8349 
8350     cntlid = nvme_subsys_register_ctrl(n, errp);
8351     if (cntlid < 0) {
8352         return -1;
8353     }
8354 
8355     n->cntlid = cntlid;
8356 
8357     return 0;
8358 }
8359 
8360 void nvme_attach_ns(NvmeCtrl *n, NvmeNamespace *ns)
8361 {
8362     uint32_t nsid = ns->params.nsid;
8363     assert(nsid && nsid <= NVME_MAX_NAMESPACES);
8364 
8365     n->namespaces[nsid] = ns;
8366     ns->attached++;
8367 
8368     n->dmrsl = MIN_NON_ZERO(n->dmrsl,
8369                             BDRV_REQUEST_MAX_BYTES / nvme_l2b(ns, 1));
8370 }
8371 
8372 static void nvme_realize(PCIDevice *pci_dev, Error **errp)
8373 {
8374     NvmeCtrl *n = NVME(pci_dev);
8375     DeviceState *dev = DEVICE(pci_dev);
8376     NvmeNamespace *ns;
8377     NvmeCtrl *pn = NVME(pcie_sriov_get_pf(pci_dev));
8378 
8379     if (pci_is_vf(pci_dev)) {
8380         /*
8381          * VFs derive settings from the parent. PF's lifespan exceeds
8382          * that of VF's.
8383          */
8384         memcpy(&n->params, &pn->params, sizeof(NvmeParams));
8385 
8386         /*
8387          * Set PF's serial value to a new string memory to prevent 'serial'
8388          * property object release of PF when a VF is removed from the system.
8389          */
8390         n->params.serial = g_strdup(pn->params.serial);
8391         n->subsys = pn->subsys;
8392     }
8393 
8394     if (!nvme_check_params(n, errp)) {
8395         return;
8396     }
8397 
8398     qbus_init(&n->bus, sizeof(NvmeBus), TYPE_NVME_BUS, dev, dev->id);
8399 
8400     if (nvme_init_subsys(n, errp)) {
8401         return;
8402     }
8403     nvme_init_state(n);
8404     if (!nvme_init_pci(n, pci_dev, errp)) {
8405         return;
8406     }
8407     nvme_init_ctrl(n, pci_dev);
8408 
8409     /* setup a namespace if the controller drive property was given */
8410     if (n->namespace.blkconf.blk) {
8411         ns = &n->namespace;
8412         ns->params.nsid = 1;
8413 
8414         if (nvme_ns_setup(ns, errp)) {
8415             return;
8416         }
8417 
8418         nvme_attach_ns(n, ns);
8419     }
8420 }
8421 
8422 static void nvme_exit(PCIDevice *pci_dev)
8423 {
8424     NvmeCtrl *n = NVME(pci_dev);
8425     NvmeNamespace *ns;
8426     int i;
8427 
8428     nvme_ctrl_reset(n, NVME_RESET_FUNCTION);
8429 
8430     if (n->subsys) {
8431         for (i = 1; i <= NVME_MAX_NAMESPACES; i++) {
8432             ns = nvme_ns(n, i);
8433             if (ns) {
8434                 ns->attached--;
8435             }
8436         }
8437 
8438         nvme_subsys_unregister_ctrl(n->subsys, n);
8439     }
8440 
8441     g_free(n->cq);
8442     g_free(n->sq);
8443     g_free(n->aer_reqs);
8444 
8445     if (n->params.cmb_size_mb) {
8446         g_free(n->cmb.buf);
8447     }
8448 
8449     if (n->pmr.dev) {
8450         host_memory_backend_set_mapped(n->pmr.dev, false);
8451     }
8452 
8453     if (!pci_is_vf(pci_dev) && n->params.sriov_max_vfs) {
8454         pcie_sriov_pf_exit(pci_dev);
8455     }
8456 
8457     msix_uninit(pci_dev, &n->bar0, &n->bar0);
8458     memory_region_del_subregion(&n->bar0, &n->iomem);
8459 }
8460 
8461 static Property nvme_props[] = {
8462     DEFINE_BLOCK_PROPERTIES(NvmeCtrl, namespace.blkconf),
8463     DEFINE_PROP_LINK("pmrdev", NvmeCtrl, pmr.dev, TYPE_MEMORY_BACKEND,
8464                      HostMemoryBackend *),
8465     DEFINE_PROP_LINK("subsys", NvmeCtrl, subsys, TYPE_NVME_SUBSYS,
8466                      NvmeSubsystem *),
8467     DEFINE_PROP_STRING("serial", NvmeCtrl, params.serial),
8468     DEFINE_PROP_UINT32("cmb_size_mb", NvmeCtrl, params.cmb_size_mb, 0),
8469     DEFINE_PROP_UINT32("num_queues", NvmeCtrl, params.num_queues, 0),
8470     DEFINE_PROP_UINT32("max_ioqpairs", NvmeCtrl, params.max_ioqpairs, 64),
8471     DEFINE_PROP_UINT16("msix_qsize", NvmeCtrl, params.msix_qsize, 65),
8472     DEFINE_PROP_UINT8("aerl", NvmeCtrl, params.aerl, 3),
8473     DEFINE_PROP_UINT32("aer_max_queued", NvmeCtrl, params.aer_max_queued, 64),
8474     DEFINE_PROP_UINT8("mdts", NvmeCtrl, params.mdts, 7),
8475     DEFINE_PROP_UINT8("vsl", NvmeCtrl, params.vsl, 7),
8476     DEFINE_PROP_BOOL("use-intel-id", NvmeCtrl, params.use_intel_id, false),
8477     DEFINE_PROP_BOOL("legacy-cmb", NvmeCtrl, params.legacy_cmb, false),
8478     DEFINE_PROP_BOOL("ioeventfd", NvmeCtrl, params.ioeventfd, false),
8479     DEFINE_PROP_UINT8("zoned.zasl", NvmeCtrl, params.zasl, 0),
8480     DEFINE_PROP_BOOL("zoned.auto_transition", NvmeCtrl,
8481                      params.auto_transition_zones, true),
8482     DEFINE_PROP_UINT16("sriov_max_vfs", NvmeCtrl, params.sriov_max_vfs, 0),
8483     DEFINE_PROP_UINT16("sriov_vq_flexible", NvmeCtrl,
8484                        params.sriov_vq_flexible, 0),
8485     DEFINE_PROP_UINT16("sriov_vi_flexible", NvmeCtrl,
8486                        params.sriov_vi_flexible, 0),
8487     DEFINE_PROP_UINT32("sriov_max_vi_per_vf", NvmeCtrl,
8488                        params.sriov_max_vi_per_vf, 0),
8489     DEFINE_PROP_UINT32("sriov_max_vq_per_vf", NvmeCtrl,
8490                        params.sriov_max_vq_per_vf, 0),
8491     DEFINE_PROP_BOOL("msix-exclusive-bar", NvmeCtrl, params.msix_exclusive_bar,
8492                      false),
8493     DEFINE_PROP_UINT16("mqes", NvmeCtrl, params.mqes, 0x7ff),
8494     DEFINE_PROP_END_OF_LIST(),
8495 };
8496 
8497 static void nvme_get_smart_warning(Object *obj, Visitor *v, const char *name,
8498                                    void *opaque, Error **errp)
8499 {
8500     NvmeCtrl *n = NVME(obj);
8501     uint8_t value = n->smart_critical_warning;
8502 
8503     visit_type_uint8(v, name, &value, errp);
8504 }
8505 
8506 static void nvme_set_smart_warning(Object *obj, Visitor *v, const char *name,
8507                                    void *opaque, Error **errp)
8508 {
8509     NvmeCtrl *n = NVME(obj);
8510     uint8_t value, old_value, cap = 0, index, event;
8511 
8512     if (!visit_type_uint8(v, name, &value, errp)) {
8513         return;
8514     }
8515 
8516     cap = NVME_SMART_SPARE | NVME_SMART_TEMPERATURE | NVME_SMART_RELIABILITY
8517           | NVME_SMART_MEDIA_READ_ONLY | NVME_SMART_FAILED_VOLATILE_MEDIA;
8518     if (NVME_CAP_PMRS(ldq_le_p(&n->bar.cap))) {
8519         cap |= NVME_SMART_PMR_UNRELIABLE;
8520     }
8521 
8522     if ((value & cap) != value) {
8523         error_setg(errp, "unsupported smart critical warning bits: 0x%x",
8524                    value & ~cap);
8525         return;
8526     }
8527 
8528     old_value = n->smart_critical_warning;
8529     n->smart_critical_warning = value;
8530 
8531     /* only inject new bits of smart critical warning */
8532     for (index = 0; index < NVME_SMART_WARN_MAX; index++) {
8533         event = 1 << index;
8534         if (value & ~old_value & event)
8535             nvme_smart_event(n, event);
8536     }
8537 }
8538 
8539 static void nvme_pci_reset(DeviceState *qdev)
8540 {
8541     PCIDevice *pci_dev = PCI_DEVICE(qdev);
8542     NvmeCtrl *n = NVME(pci_dev);
8543 
8544     trace_pci_nvme_pci_reset();
8545     nvme_ctrl_reset(n, NVME_RESET_FUNCTION);
8546 }
8547 
8548 static void nvme_sriov_post_write_config(PCIDevice *dev, uint16_t old_num_vfs)
8549 {
8550     NvmeCtrl *n = NVME(dev);
8551     NvmeSecCtrlEntry *sctrl;
8552     int i;
8553 
8554     for (i = pcie_sriov_num_vfs(dev); i < old_num_vfs; i++) {
8555         sctrl = &n->sec_ctrl_list[i];
8556         nvme_virt_set_state(n, le16_to_cpu(sctrl->scid), false);
8557     }
8558 }
8559 
8560 static void nvme_pci_write_config(PCIDevice *dev, uint32_t address,
8561                                   uint32_t val, int len)
8562 {
8563     uint16_t old_num_vfs = pcie_sriov_num_vfs(dev);
8564 
8565     pci_default_write_config(dev, address, val, len);
8566     pcie_cap_flr_write_config(dev, address, val, len);
8567     nvme_sriov_post_write_config(dev, old_num_vfs);
8568 }
8569 
8570 static const VMStateDescription nvme_vmstate = {
8571     .name = "nvme",
8572     .unmigratable = 1,
8573 };
8574 
8575 static void nvme_class_init(ObjectClass *oc, void *data)
8576 {
8577     DeviceClass *dc = DEVICE_CLASS(oc);
8578     PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc);
8579 
8580     pc->realize = nvme_realize;
8581     pc->config_write = nvme_pci_write_config;
8582     pc->exit = nvme_exit;
8583     pc->class_id = PCI_CLASS_STORAGE_EXPRESS;
8584     pc->revision = 2;
8585 
8586     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
8587     dc->desc = "Non-Volatile Memory Express";
8588     device_class_set_props(dc, nvme_props);
8589     dc->vmsd = &nvme_vmstate;
8590     dc->reset = nvme_pci_reset;
8591 }
8592 
8593 static void nvme_instance_init(Object *obj)
8594 {
8595     NvmeCtrl *n = NVME(obj);
8596 
8597     device_add_bootindex_property(obj, &n->namespace.blkconf.bootindex,
8598                                   "bootindex", "/namespace@1,0",
8599                                   DEVICE(obj));
8600 
8601     object_property_add(obj, "smart_critical_warning", "uint8",
8602                         nvme_get_smart_warning,
8603                         nvme_set_smart_warning, NULL, NULL);
8604 }
8605 
8606 static const TypeInfo nvme_info = {
8607     .name          = TYPE_NVME,
8608     .parent        = TYPE_PCI_DEVICE,
8609     .instance_size = sizeof(NvmeCtrl),
8610     .instance_init = nvme_instance_init,
8611     .class_init    = nvme_class_init,
8612     .interfaces = (InterfaceInfo[]) {
8613         { INTERFACE_PCIE_DEVICE },
8614         { }
8615     },
8616 };
8617 
8618 static const TypeInfo nvme_bus_info = {
8619     .name = TYPE_NVME_BUS,
8620     .parent = TYPE_BUS,
8621     .instance_size = sizeof(NvmeBus),
8622 };
8623 
8624 static void nvme_register_types(void)
8625 {
8626     type_register_static(&nvme_info);
8627     type_register_static(&nvme_bus_info);
8628 }
8629 
8630 type_init(nvme_register_types)
8631