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