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