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