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