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