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