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