xref: /spdk/lib/nvmf/ctrlr.c (revision 9544fe07aad355262fcaa65dc27f9965a8ea4617)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation. All rights reserved.
5  *   Copyright (c) 2019, 2020 Mellanox Technologies LTD. All rights reserved.
6  *   Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
7  *
8  *   Redistribution and use in source and binary forms, with or without
9  *   modification, are permitted provided that the following conditions
10  *   are met:
11  *
12  *     * Redistributions of source code must retain the above copyright
13  *       notice, this list of conditions and the following disclaimer.
14  *     * Redistributions in binary form must reproduce the above copyright
15  *       notice, this list of conditions and the following disclaimer in
16  *       the documentation and/or other materials provided with the
17  *       distribution.
18  *     * Neither the name of Intel Corporation nor the names of its
19  *       contributors may be used to endorse or promote products derived
20  *       from this software without specific prior written permission.
21  *
22  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include "spdk/stdinc.h"
36 
37 #include "nvmf_internal.h"
38 #include "transport.h"
39 
40 #include "spdk/bit_array.h"
41 #include "spdk/endian.h"
42 #include "spdk/thread.h"
43 #include "spdk/nvme_spec.h"
44 #include "spdk/nvmf_cmd.h"
45 #include "spdk/string.h"
46 #include "spdk/util.h"
47 #include "spdk/version.h"
48 #include "spdk/log.h"
49 #include "spdk_internal/usdt.h"
50 
51 #define MIN_KEEP_ALIVE_TIMEOUT_IN_MS 10000
52 #define NVMF_DISC_KATO_IN_MS 120000
53 #define KAS_TIME_UNIT_IN_MS 100
54 #define KAS_DEFAULT_VALUE (MIN_KEEP_ALIVE_TIMEOUT_IN_MS / KAS_TIME_UNIT_IN_MS)
55 
56 /*
57  * Report the SPDK version as the firmware revision.
58  * SPDK_VERSION_STRING won't fit into FR (only 8 bytes), so try to fit the most important parts.
59  */
60 #define FW_VERSION SPDK_VERSION_MAJOR_STRING SPDK_VERSION_MINOR_STRING SPDK_VERSION_PATCH_STRING
61 
62 #define ANA_TRANSITION_TIME_IN_SEC 10
63 
64 /*
65  * Support for custom admin command handlers
66  */
67 struct spdk_nvmf_custom_admin_cmd {
68 	spdk_nvmf_custom_cmd_hdlr hdlr;
69 	uint32_t nsid; /* nsid to forward */
70 };
71 
72 static struct spdk_nvmf_custom_admin_cmd g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_MAX_OPC + 1];
73 
74 static void _nvmf_request_complete(void *ctx);
75 
76 static inline void
77 nvmf_invalid_connect_response(struct spdk_nvmf_fabric_connect_rsp *rsp,
78 			      uint8_t iattr, uint16_t ipo)
79 {
80 	rsp->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
81 	rsp->status.sc = SPDK_NVMF_FABRIC_SC_INVALID_PARAM;
82 	rsp->status_code_specific.invalid.iattr = iattr;
83 	rsp->status_code_specific.invalid.ipo = ipo;
84 }
85 
86 #define SPDK_NVMF_INVALID_CONNECT_CMD(rsp, field)	\
87 	nvmf_invalid_connect_response(rsp, 0, offsetof(struct spdk_nvmf_fabric_connect_cmd, field))
88 #define SPDK_NVMF_INVALID_CONNECT_DATA(rsp, field)	\
89 	nvmf_invalid_connect_response(rsp, 1, offsetof(struct spdk_nvmf_fabric_connect_data, field))
90 
91 
92 static void
93 nvmf_ctrlr_stop_keep_alive_timer(struct spdk_nvmf_ctrlr *ctrlr)
94 {
95 	if (!ctrlr) {
96 		SPDK_ERRLOG("Controller is NULL\n");
97 		return;
98 	}
99 
100 	if (ctrlr->keep_alive_poller == NULL) {
101 		return;
102 	}
103 
104 	SPDK_DEBUGLOG(nvmf, "Stop keep alive poller\n");
105 	spdk_poller_unregister(&ctrlr->keep_alive_poller);
106 }
107 
108 static void
109 nvmf_ctrlr_stop_association_timer(struct spdk_nvmf_ctrlr *ctrlr)
110 {
111 	if (!ctrlr) {
112 		SPDK_ERRLOG("Controller is NULL\n");
113 		assert(false);
114 		return;
115 	}
116 
117 	if (ctrlr->association_timer == NULL) {
118 		return;
119 	}
120 
121 	SPDK_DEBUGLOG(nvmf, "Stop association timer\n");
122 	spdk_poller_unregister(&ctrlr->association_timer);
123 }
124 
125 static void
126 nvmf_ctrlr_disconnect_qpairs_done(struct spdk_io_channel_iter *i, int status)
127 {
128 	if (status == 0) {
129 		SPDK_DEBUGLOG(nvmf, "ctrlr disconnect qpairs complete successfully\n");
130 	} else {
131 		SPDK_ERRLOG("Fail to disconnect ctrlr qpairs\n");
132 	}
133 }
134 
135 static int
136 _nvmf_ctrlr_disconnect_qpairs_on_pg(struct spdk_io_channel_iter *i, bool include_admin)
137 {
138 	int rc = 0;
139 	struct spdk_nvmf_ctrlr *ctrlr;
140 	struct spdk_nvmf_qpair *qpair, *temp_qpair;
141 	struct spdk_io_channel *ch;
142 	struct spdk_nvmf_poll_group *group;
143 
144 	ctrlr = spdk_io_channel_iter_get_ctx(i);
145 	ch = spdk_io_channel_iter_get_channel(i);
146 	group = spdk_io_channel_get_ctx(ch);
147 
148 	TAILQ_FOREACH_SAFE(qpair, &group->qpairs, link, temp_qpair) {
149 		if (qpair->ctrlr == ctrlr && (include_admin || !nvmf_qpair_is_admin_queue(qpair))) {
150 			rc = spdk_nvmf_qpair_disconnect(qpair, NULL, NULL);
151 			if (rc) {
152 				SPDK_ERRLOG("Qpair disconnect failed\n");
153 				return rc;
154 			}
155 		}
156 	}
157 
158 	return rc;
159 }
160 
161 static void
162 nvmf_ctrlr_disconnect_qpairs_on_pg(struct spdk_io_channel_iter *i)
163 {
164 	spdk_for_each_channel_continue(i, _nvmf_ctrlr_disconnect_qpairs_on_pg(i, true));
165 }
166 
167 static void
168 nvmf_ctrlr_disconnect_io_qpairs_on_pg(struct spdk_io_channel_iter *i)
169 {
170 	spdk_for_each_channel_continue(i, _nvmf_ctrlr_disconnect_qpairs_on_pg(i, false));
171 }
172 
173 static int
174 nvmf_ctrlr_keep_alive_poll(void *ctx)
175 {
176 	uint64_t keep_alive_timeout_tick;
177 	uint64_t now = spdk_get_ticks();
178 	struct spdk_nvmf_ctrlr *ctrlr = ctx;
179 
180 	if (ctrlr->in_destruct) {
181 		nvmf_ctrlr_stop_keep_alive_timer(ctrlr);
182 		return SPDK_POLLER_IDLE;
183 	}
184 
185 	SPDK_DEBUGLOG(nvmf, "Polling ctrlr keep alive timeout\n");
186 
187 	/* If the Keep alive feature is in use and the timer expires */
188 	keep_alive_timeout_tick = ctrlr->last_keep_alive_tick +
189 				  ctrlr->feat.keep_alive_timer.bits.kato * spdk_get_ticks_hz() / UINT64_C(1000);
190 	if (now > keep_alive_timeout_tick) {
191 		SPDK_NOTICELOG("Disconnecting host %s from subsystem %s due to keep alive timeout.\n",
192 			       ctrlr->hostnqn, ctrlr->subsys->subnqn);
193 		/* set the Controller Fatal Status bit to '1' */
194 		if (ctrlr->vcprop.csts.bits.cfs == 0) {
195 			ctrlr->vcprop.csts.bits.cfs = 1;
196 
197 			/*
198 			 * disconnect qpairs, terminate Transport connection
199 			 * destroy ctrlr, break the host to controller association
200 			 * disconnect qpairs with qpair->ctrlr == ctrlr
201 			 */
202 			spdk_for_each_channel(ctrlr->subsys->tgt,
203 					      nvmf_ctrlr_disconnect_qpairs_on_pg,
204 					      ctrlr,
205 					      nvmf_ctrlr_disconnect_qpairs_done);
206 			return SPDK_POLLER_BUSY;
207 		}
208 	}
209 
210 	return SPDK_POLLER_IDLE;
211 }
212 
213 static void
214 nvmf_ctrlr_start_keep_alive_timer(struct spdk_nvmf_ctrlr *ctrlr)
215 {
216 	if (!ctrlr) {
217 		SPDK_ERRLOG("Controller is NULL\n");
218 		return;
219 	}
220 
221 	/* if cleared to 0 then the Keep Alive Timer is disabled */
222 	if (ctrlr->feat.keep_alive_timer.bits.kato != 0) {
223 
224 		ctrlr->last_keep_alive_tick = spdk_get_ticks();
225 
226 		SPDK_DEBUGLOG(nvmf, "Ctrlr add keep alive poller\n");
227 		ctrlr->keep_alive_poller = SPDK_POLLER_REGISTER(nvmf_ctrlr_keep_alive_poll, ctrlr,
228 					   ctrlr->feat.keep_alive_timer.bits.kato * 1000);
229 	}
230 }
231 
232 static void
233 ctrlr_add_qpair_and_update_rsp(struct spdk_nvmf_qpair *qpair,
234 			       struct spdk_nvmf_ctrlr *ctrlr,
235 			       struct spdk_nvmf_fabric_connect_rsp *rsp)
236 {
237 	assert(ctrlr->admin_qpair->group->thread == spdk_get_thread());
238 
239 	/* check if we would exceed ctrlr connection limit */
240 	if (qpair->qid >= spdk_bit_array_capacity(ctrlr->qpair_mask)) {
241 		SPDK_ERRLOG("Requested QID %u but Max QID is %u\n",
242 			    qpair->qid, spdk_bit_array_capacity(ctrlr->qpair_mask) - 1);
243 		rsp->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
244 		rsp->status.sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
245 		return;
246 	}
247 
248 	if (spdk_bit_array_get(ctrlr->qpair_mask, qpair->qid)) {
249 		SPDK_ERRLOG("Got I/O connect with duplicate QID %u\n", qpair->qid);
250 		rsp->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
251 		rsp->status.sc = SPDK_NVME_SC_INVALID_QUEUE_IDENTIFIER;
252 		return;
253 	}
254 
255 	qpair->ctrlr = ctrlr;
256 	spdk_bit_array_set(ctrlr->qpair_mask, qpair->qid);
257 
258 	rsp->status.sc = SPDK_NVME_SC_SUCCESS;
259 	rsp->status_code_specific.success.cntlid = ctrlr->cntlid;
260 	SPDK_DEBUGLOG(nvmf, "connect capsule response: cntlid = 0x%04x\n",
261 		      rsp->status_code_specific.success.cntlid);
262 
263 	SPDK_DTRACE_PROBE4(nvmf_ctrlr_add_qpair, qpair, qpair->qid, ctrlr->subsys->subnqn,
264 			   ctrlr->hostnqn);
265 }
266 
267 static void
268 _nvmf_ctrlr_add_admin_qpair(void *ctx)
269 {
270 	struct spdk_nvmf_request *req = ctx;
271 	struct spdk_nvmf_fabric_connect_rsp *rsp = &req->rsp->connect_rsp;
272 	struct spdk_nvmf_qpair *qpair = req->qpair;
273 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
274 
275 	ctrlr->admin_qpair = qpair;
276 	ctrlr->association_timeout = qpair->transport->opts.association_timeout;
277 	nvmf_ctrlr_start_keep_alive_timer(ctrlr);
278 	ctrlr_add_qpair_and_update_rsp(qpair, ctrlr, rsp);
279 	_nvmf_request_complete(req);
280 }
281 
282 static void
283 _nvmf_subsystem_add_ctrlr(void *ctx)
284 {
285 	struct spdk_nvmf_request *req = ctx;
286 	struct spdk_nvmf_qpair *qpair = req->qpair;
287 	struct spdk_nvmf_fabric_connect_rsp *rsp = &req->rsp->connect_rsp;
288 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
289 
290 	if (nvmf_subsystem_add_ctrlr(ctrlr->subsys, ctrlr)) {
291 		SPDK_ERRLOG("Unable to add controller to subsystem\n");
292 		spdk_bit_array_free(&ctrlr->qpair_mask);
293 		free(ctrlr);
294 		qpair->ctrlr = NULL;
295 		rsp->status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
296 		spdk_nvmf_request_complete(req);
297 		return;
298 	}
299 
300 	spdk_thread_send_msg(ctrlr->thread, _nvmf_ctrlr_add_admin_qpair, req);
301 }
302 
303 static void
304 nvmf_ctrlr_cdata_init(struct spdk_nvmf_transport *transport, struct spdk_nvmf_subsystem *subsystem,
305 		      struct spdk_nvmf_ctrlr_data *cdata)
306 {
307 	cdata->kas = KAS_DEFAULT_VALUE;
308 	cdata->oncs.reservations = 1;
309 	cdata->sgls.supported = 1;
310 	cdata->sgls.keyed_sgl = 1;
311 	cdata->sgls.sgl_offset = 1;
312 	cdata->nvmf_specific.ioccsz = sizeof(struct spdk_nvme_cmd) / 16;
313 	cdata->nvmf_specific.ioccsz += transport->opts.in_capsule_data_size / 16;
314 	cdata->nvmf_specific.iorcsz = sizeof(struct spdk_nvme_cpl) / 16;
315 	cdata->nvmf_specific.icdoff = 0; /* offset starts directly after SQE */
316 	cdata->nvmf_specific.ctrattr.ctrlr_model = SPDK_NVMF_CTRLR_MODEL_DYNAMIC;
317 	cdata->nvmf_specific.msdbd = 1;
318 
319 	if (transport->ops->cdata_init) {
320 		transport->ops->cdata_init(transport, subsystem, cdata);
321 	}
322 }
323 
324 static struct spdk_nvmf_ctrlr *
325 nvmf_ctrlr_create(struct spdk_nvmf_subsystem *subsystem,
326 		  struct spdk_nvmf_request *req,
327 		  struct spdk_nvmf_fabric_connect_cmd *connect_cmd,
328 		  struct spdk_nvmf_fabric_connect_data *connect_data)
329 {
330 	struct spdk_nvmf_ctrlr	*ctrlr;
331 	struct spdk_nvmf_transport *transport;
332 	struct spdk_nvme_transport_id listen_trid = {};
333 
334 	ctrlr = calloc(1, sizeof(*ctrlr));
335 	if (ctrlr == NULL) {
336 		SPDK_ERRLOG("Memory allocation failed\n");
337 		return NULL;
338 	}
339 
340 	STAILQ_INIT(&ctrlr->async_events);
341 	TAILQ_INIT(&ctrlr->log_head);
342 	ctrlr->subsys = subsystem;
343 	ctrlr->thread = req->qpair->group->thread;
344 	ctrlr->disconnect_in_progress = false;
345 
346 	transport = req->qpair->transport;
347 	ctrlr->qpair_mask = spdk_bit_array_create(transport->opts.max_qpairs_per_ctrlr);
348 	if (!ctrlr->qpair_mask) {
349 		SPDK_ERRLOG("Failed to allocate controller qpair mask\n");
350 		goto err_qpair_mask;
351 	}
352 
353 	nvmf_ctrlr_cdata_init(transport, subsystem, &ctrlr->cdata);
354 
355 	/*
356 	 * KAS: This field indicates the granularity of the Keep Alive Timer in 100ms units.
357 	 * If this field is cleared to 0h, then Keep Alive is not supported.
358 	 */
359 	if (ctrlr->cdata.kas) {
360 		ctrlr->feat.keep_alive_timer.bits.kato = spdk_divide_round_up(connect_cmd->kato,
361 				KAS_DEFAULT_VALUE * KAS_TIME_UNIT_IN_MS) *
362 				KAS_DEFAULT_VALUE * KAS_TIME_UNIT_IN_MS;
363 	}
364 
365 	ctrlr->feat.async_event_configuration.bits.ns_attr_notice = 1;
366 	if (ctrlr->subsys->flags.ana_reporting) {
367 		ctrlr->feat.async_event_configuration.bits.ana_change_notice = 1;
368 	}
369 	ctrlr->feat.volatile_write_cache.bits.wce = 1;
370 	/* Coalescing Disable */
371 	ctrlr->feat.interrupt_vector_configuration.bits.cd = 1;
372 
373 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
374 		/*
375 		 * If keep-alive timeout is not set, discovery controllers use some
376 		 * arbitrary high value in order to cleanup stale discovery sessions
377 		 *
378 		 * From the 1.0a nvme-of spec:
379 		 * "The Keep Alive command is reserved for
380 		 * Discovery controllers. A transport may specify a
381 		 * fixed Discovery controller activity timeout value
382 		 * (e.g., 2 minutes). If no commands are received
383 		 * by a Discovery controller within that time
384 		 * period, the controller may perform the
385 		 * actions for Keep Alive Timer expiration".
386 		 *
387 		 * From the 1.1 nvme-of spec:
388 		 * "A host requests an explicit persistent connection
389 		 * to a Discovery controller and Asynchronous Event Notifications from
390 		 * the Discovery controller on that persistent connection by specifying
391 		 * a non-zero Keep Alive Timer value in the Connect command."
392 		 *
393 		 * In case non-zero KATO is used, we enable discovery_log_change_notice
394 		 * otherwise we disable it and use default discovery controller KATO.
395 		 * KATO is in millisecond.
396 		 */
397 		if (ctrlr->feat.keep_alive_timer.bits.kato == 0) {
398 			ctrlr->feat.keep_alive_timer.bits.kato = NVMF_DISC_KATO_IN_MS;
399 			ctrlr->feat.async_event_configuration.bits.discovery_log_change_notice = 0;
400 		} else {
401 			ctrlr->feat.async_event_configuration.bits.discovery_log_change_notice = 1;
402 		}
403 	}
404 
405 	/* Subtract 1 for admin queue, 1 for 0's based */
406 	ctrlr->feat.number_of_queues.bits.ncqr = transport->opts.max_qpairs_per_ctrlr - 1 -
407 			1;
408 	ctrlr->feat.number_of_queues.bits.nsqr = transport->opts.max_qpairs_per_ctrlr - 1 -
409 			1;
410 
411 	spdk_uuid_copy(&ctrlr->hostid, (struct spdk_uuid *)connect_data->hostid);
412 	memcpy(ctrlr->hostnqn, connect_data->hostnqn, sizeof(ctrlr->hostnqn));
413 
414 	ctrlr->vcprop.cap.raw = 0;
415 	ctrlr->vcprop.cap.bits.cqr = 1; /* NVMe-oF specification required */
416 	ctrlr->vcprop.cap.bits.mqes = transport->opts.max_queue_depth -
417 				      1; /* max queue depth */
418 	ctrlr->vcprop.cap.bits.ams = 0; /* optional arb mechanisms */
419 	ctrlr->vcprop.cap.bits.to = 1; /* ready timeout - 500 msec units */
420 	ctrlr->vcprop.cap.bits.dstrd = 0; /* fixed to 0 for NVMe-oF */
421 	ctrlr->vcprop.cap.bits.css = SPDK_NVME_CAP_CSS_NVM; /* NVM command set */
422 	ctrlr->vcprop.cap.bits.mpsmin = 0; /* 2 ^ (12 + mpsmin) == 4k */
423 	ctrlr->vcprop.cap.bits.mpsmax = 0; /* 2 ^ (12 + mpsmax) == 4k */
424 
425 	/* Version Supported: 1.3 */
426 	ctrlr->vcprop.vs.bits.mjr = 1;
427 	ctrlr->vcprop.vs.bits.mnr = 3;
428 	ctrlr->vcprop.vs.bits.ter = 0;
429 
430 	ctrlr->vcprop.cc.raw = 0;
431 	ctrlr->vcprop.cc.bits.en = 0; /* Init controller disabled */
432 
433 	ctrlr->vcprop.csts.raw = 0;
434 	ctrlr->vcprop.csts.bits.rdy = 0; /* Init controller as not ready */
435 
436 	SPDK_DEBUGLOG(nvmf, "cap 0x%" PRIx64 "\n", ctrlr->vcprop.cap.raw);
437 	SPDK_DEBUGLOG(nvmf, "vs 0x%x\n", ctrlr->vcprop.vs.raw);
438 	SPDK_DEBUGLOG(nvmf, "cc 0x%x\n", ctrlr->vcprop.cc.raw);
439 	SPDK_DEBUGLOG(nvmf, "csts 0x%x\n", ctrlr->vcprop.csts.raw);
440 
441 	ctrlr->dif_insert_or_strip = transport->opts.dif_insert_or_strip;
442 
443 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_NVME) {
444 		if (spdk_nvmf_qpair_get_listen_trid(req->qpair, &listen_trid) != 0) {
445 			SPDK_ERRLOG("Could not get listener transport ID\n");
446 			goto err_listener;
447 		}
448 
449 		ctrlr->listener = nvmf_subsystem_find_listener(ctrlr->subsys, &listen_trid);
450 		if (!ctrlr->listener) {
451 			SPDK_ERRLOG("Listener was not found\n");
452 			goto err_listener;
453 		}
454 	}
455 
456 	req->qpair->ctrlr = ctrlr;
457 	spdk_thread_send_msg(subsystem->thread, _nvmf_subsystem_add_ctrlr, req);
458 
459 	return ctrlr;
460 err_listener:
461 	spdk_bit_array_free(&ctrlr->qpair_mask);
462 err_qpair_mask:
463 	free(ctrlr);
464 	return NULL;
465 }
466 
467 static void
468 _nvmf_ctrlr_destruct(void *ctx)
469 {
470 	struct spdk_nvmf_ctrlr *ctrlr = ctx;
471 	struct spdk_nvmf_reservation_log *log, *log_tmp;
472 	struct spdk_nvmf_async_event_completion *event, *event_tmp;
473 
474 	assert(spdk_get_thread() == ctrlr->thread);
475 	assert(ctrlr->in_destruct);
476 
477 	if (ctrlr->disconnect_in_progress) {
478 		SPDK_ERRLOG("freeing ctrlr with disconnect in progress\n");
479 		spdk_thread_send_msg(ctrlr->thread, _nvmf_ctrlr_destruct, ctrlr);
480 		return;
481 	}
482 
483 	nvmf_ctrlr_stop_keep_alive_timer(ctrlr);
484 	nvmf_ctrlr_stop_association_timer(ctrlr);
485 	spdk_bit_array_free(&ctrlr->qpair_mask);
486 
487 	TAILQ_FOREACH_SAFE(log, &ctrlr->log_head, link, log_tmp) {
488 		TAILQ_REMOVE(&ctrlr->log_head, log, link);
489 		free(log);
490 	}
491 	STAILQ_FOREACH_SAFE(event, &ctrlr->async_events, link, event_tmp) {
492 		STAILQ_REMOVE(&ctrlr->async_events, event, spdk_nvmf_async_event_completion, link);
493 		free(event);
494 	}
495 	free(ctrlr);
496 }
497 
498 void
499 nvmf_ctrlr_destruct(struct spdk_nvmf_ctrlr *ctrlr)
500 {
501 	nvmf_subsystem_remove_ctrlr(ctrlr->subsys, ctrlr);
502 
503 	spdk_thread_send_msg(ctrlr->thread, _nvmf_ctrlr_destruct, ctrlr);
504 }
505 
506 static void
507 nvmf_ctrlr_add_io_qpair(void *ctx)
508 {
509 	struct spdk_nvmf_request *req = ctx;
510 	struct spdk_nvmf_fabric_connect_rsp *rsp = &req->rsp->connect_rsp;
511 	struct spdk_nvmf_qpair *qpair = req->qpair;
512 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
513 	struct spdk_nvmf_qpair *admin_qpair = ctrlr->admin_qpair;
514 
515 	/* Unit test will check qpair->ctrlr after calling spdk_nvmf_ctrlr_connect.
516 	  * For error case, the value should be NULL. So set it to NULL at first.
517 	  */
518 	qpair->ctrlr = NULL;
519 
520 	/* Make sure the controller is not being destroyed. */
521 	if (ctrlr->in_destruct) {
522 		SPDK_ERRLOG("Got I/O connect while ctrlr was being destroyed.\n");
523 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
524 		goto end;
525 	}
526 
527 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
528 		SPDK_ERRLOG("I/O connect not allowed on discovery controller\n");
529 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
530 		goto end;
531 	}
532 
533 	if (!ctrlr->vcprop.cc.bits.en) {
534 		SPDK_ERRLOG("Got I/O connect before ctrlr was enabled\n");
535 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
536 		goto end;
537 	}
538 
539 	if (1u << ctrlr->vcprop.cc.bits.iosqes != sizeof(struct spdk_nvme_cmd)) {
540 		SPDK_ERRLOG("Got I/O connect with invalid IOSQES %u\n",
541 			    ctrlr->vcprop.cc.bits.iosqes);
542 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
543 		goto end;
544 	}
545 
546 	if (1u << ctrlr->vcprop.cc.bits.iocqes != sizeof(struct spdk_nvme_cpl)) {
547 		SPDK_ERRLOG("Got I/O connect with invalid IOCQES %u\n",
548 			    ctrlr->vcprop.cc.bits.iocqes);
549 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
550 		goto end;
551 	}
552 
553 	if (admin_qpair->state != SPDK_NVMF_QPAIR_ACTIVE || admin_qpair->group == NULL) {
554 		/* There is a chance that admin qpair is being destroyed at this moment due to e.g.
555 		 * expired keep alive timer. Part of the qpair destruction process is change of qpair's
556 		 * state to DEACTIVATING and removing it from poll group */
557 		SPDK_ERRLOG("Inactive admin qpair (state %d, group %p)\n", admin_qpair->state, admin_qpair->group);
558 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
559 		goto end;
560 	}
561 
562 	ctrlr_add_qpair_and_update_rsp(qpair, ctrlr, rsp);
563 end:
564 	spdk_nvmf_request_complete(req);
565 }
566 
567 static void
568 _nvmf_ctrlr_add_io_qpair(void *ctx)
569 {
570 	struct spdk_nvmf_request *req = ctx;
571 	struct spdk_nvmf_fabric_connect_rsp *rsp = &req->rsp->connect_rsp;
572 	struct spdk_nvmf_fabric_connect_data *data = req->data;
573 	struct spdk_nvmf_ctrlr *ctrlr;
574 	struct spdk_nvmf_qpair *qpair = req->qpair;
575 	struct spdk_nvmf_qpair *admin_qpair;
576 	struct spdk_nvmf_tgt *tgt = qpair->transport->tgt;
577 	struct spdk_nvmf_subsystem *subsystem;
578 	struct spdk_nvme_transport_id listen_trid = {};
579 	const struct spdk_nvmf_subsystem_listener *listener;
580 
581 	SPDK_DEBUGLOG(nvmf, "Connect I/O Queue for controller id 0x%x\n", data->cntlid);
582 
583 	subsystem = spdk_nvmf_tgt_find_subsystem(tgt, data->subnqn);
584 	/* We already checked this in spdk_nvmf_ctrlr_connect */
585 	assert(subsystem != NULL);
586 
587 	ctrlr = nvmf_subsystem_get_ctrlr(subsystem, data->cntlid);
588 	if (ctrlr == NULL) {
589 		SPDK_ERRLOG("Unknown controller ID 0x%x\n", data->cntlid);
590 		SPDK_NVMF_INVALID_CONNECT_DATA(rsp, cntlid);
591 		spdk_nvmf_request_complete(req);
592 		return;
593 	}
594 
595 	/* fail before passing a message to the controller thread. */
596 	if (ctrlr->in_destruct) {
597 		SPDK_ERRLOG("Got I/O connect while ctrlr was being destroyed.\n");
598 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
599 		spdk_nvmf_request_complete(req);
600 		return;
601 	}
602 
603 	/* If ANA reporting is enabled, check if I/O connect is on the same listener. */
604 	if (subsystem->flags.ana_reporting) {
605 		if (spdk_nvmf_qpair_get_listen_trid(req->qpair, &listen_trid) != 0) {
606 			SPDK_ERRLOG("Could not get listener transport ID\n");
607 			SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
608 			spdk_nvmf_request_complete(req);
609 			return;
610 		}
611 
612 		listener = nvmf_subsystem_find_listener(subsystem, &listen_trid);
613 		if (listener != ctrlr->listener) {
614 			SPDK_ERRLOG("I/O connect is on a listener different from admin connect\n");
615 			SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
616 			spdk_nvmf_request_complete(req);
617 			return;
618 		}
619 	}
620 
621 	admin_qpair = ctrlr->admin_qpair;
622 	if (admin_qpair->state != SPDK_NVMF_QPAIR_ACTIVE || admin_qpair->group == NULL) {
623 		/* There is a chance that admin qpair is being destroyed at this moment due to e.g.
624 		 * expired keep alive timer. Part of the qpair destruction process is change of qpair's
625 		 * state to DEACTIVATING and removing it from poll group */
626 		SPDK_ERRLOG("Inactive admin qpair (state %d, group %p)\n", admin_qpair->state, admin_qpair->group);
627 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, qid);
628 		spdk_nvmf_request_complete(req);
629 		return;
630 	}
631 	qpair->ctrlr = ctrlr;
632 	spdk_thread_send_msg(admin_qpair->group->thread, nvmf_ctrlr_add_io_qpair, req);
633 }
634 
635 static bool
636 nvmf_qpair_access_allowed(struct spdk_nvmf_qpair *qpair, struct spdk_nvmf_subsystem *subsystem,
637 			  const char *hostnqn)
638 {
639 	struct spdk_nvme_transport_id listen_trid = {};
640 
641 	if (!spdk_nvmf_subsystem_host_allowed(subsystem, hostnqn)) {
642 		SPDK_ERRLOG("Subsystem '%s' does not allow host '%s'\n", subsystem->subnqn, hostnqn);
643 		return false;
644 	}
645 
646 	if (spdk_nvmf_qpair_get_listen_trid(qpair, &listen_trid)) {
647 		SPDK_ERRLOG("Subsystem '%s' is unable to enforce access control due to an internal error.\n",
648 			    subsystem->subnqn);
649 		return false;
650 	}
651 
652 	if (!spdk_nvmf_subsystem_listener_allowed(subsystem, &listen_trid)) {
653 		SPDK_ERRLOG("Subsystem '%s' does not allow host '%s' to connect at this address.\n",
654 			    subsystem->subnqn, hostnqn);
655 		return false;
656 	}
657 
658 	return true;
659 }
660 
661 static int
662 _nvmf_ctrlr_connect(struct spdk_nvmf_request *req)
663 {
664 	struct spdk_nvmf_fabric_connect_data *data = req->data;
665 	struct spdk_nvmf_fabric_connect_cmd *cmd = &req->cmd->connect_cmd;
666 	struct spdk_nvmf_fabric_connect_rsp *rsp = &req->rsp->connect_rsp;
667 	struct spdk_nvmf_qpair *qpair = req->qpair;
668 	struct spdk_nvmf_transport *transport = qpair->transport;
669 	struct spdk_nvmf_ctrlr *ctrlr;
670 	struct spdk_nvmf_subsystem *subsystem;
671 
672 	SPDK_DEBUGLOG(nvmf, "recfmt 0x%x qid %u sqsize %u\n",
673 		      cmd->recfmt, cmd->qid, cmd->sqsize);
674 
675 	SPDK_DEBUGLOG(nvmf, "Connect data:\n");
676 	SPDK_DEBUGLOG(nvmf, "  cntlid:  0x%04x\n", data->cntlid);
677 	SPDK_DEBUGLOG(nvmf, "  hostid: %08x-%04x-%04x-%02x%02x-%04x%08x ***\n",
678 		      ntohl(*(uint32_t *)&data->hostid[0]),
679 		      ntohs(*(uint16_t *)&data->hostid[4]),
680 		      ntohs(*(uint16_t *)&data->hostid[6]),
681 		      data->hostid[8],
682 		      data->hostid[9],
683 		      ntohs(*(uint16_t *)&data->hostid[10]),
684 		      ntohl(*(uint32_t *)&data->hostid[12]));
685 	SPDK_DEBUGLOG(nvmf, "  subnqn: \"%s\"\n", data->subnqn);
686 	SPDK_DEBUGLOG(nvmf, "  hostnqn: \"%s\"\n", data->hostnqn);
687 
688 	subsystem = spdk_nvmf_tgt_find_subsystem(transport->tgt, data->subnqn);
689 	if (!subsystem) {
690 		SPDK_NVMF_INVALID_CONNECT_DATA(rsp, subnqn);
691 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
692 	}
693 
694 	if (cmd->recfmt != 0) {
695 		SPDK_ERRLOG("Connect command unsupported RECFMT %u\n", cmd->recfmt);
696 		rsp->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
697 		rsp->status.sc = SPDK_NVMF_FABRIC_SC_INCOMPATIBLE_FORMAT;
698 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
699 	}
700 
701 	/*
702 	 * SQSIZE is a 0-based value, so it must be at least 1 (minimum queue depth is 2) and
703 	 * strictly less than max_aq_depth (admin queues) or max_queue_depth (io queues).
704 	 */
705 	if (cmd->sqsize == 0) {
706 		SPDK_ERRLOG("Invalid SQSIZE = 0\n");
707 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, sqsize);
708 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
709 	}
710 
711 	if (cmd->qid == 0) {
712 		if (cmd->sqsize >= transport->opts.max_aq_depth) {
713 			SPDK_ERRLOG("Invalid SQSIZE for admin queue %u (min 1, max %u)\n",
714 				    cmd->sqsize, transport->opts.max_aq_depth - 1);
715 			SPDK_NVMF_INVALID_CONNECT_CMD(rsp, sqsize);
716 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
717 		}
718 	} else if (cmd->sqsize >= transport->opts.max_queue_depth) {
719 		SPDK_ERRLOG("Invalid SQSIZE %u (min 1, max %u)\n",
720 			    cmd->sqsize, transport->opts.max_queue_depth - 1);
721 		SPDK_NVMF_INVALID_CONNECT_CMD(rsp, sqsize);
722 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
723 	}
724 
725 	qpair->sq_head_max = cmd->sqsize;
726 	qpair->qid = cmd->qid;
727 
728 	if (0 == qpair->qid) {
729 		qpair->group->stat.admin_qpairs++;
730 		qpair->group->stat.current_admin_qpairs++;
731 	} else {
732 		qpair->group->stat.io_qpairs++;
733 		qpair->group->stat.current_io_qpairs++;
734 	}
735 
736 	if (cmd->qid == 0) {
737 		SPDK_DEBUGLOG(nvmf, "Connect Admin Queue for controller ID 0x%x\n", data->cntlid);
738 
739 		if (data->cntlid != 0xFFFF) {
740 			/* This NVMf target only supports dynamic mode. */
741 			SPDK_ERRLOG("The NVMf target only supports dynamic mode (CNTLID = 0x%x).\n", data->cntlid);
742 			SPDK_NVMF_INVALID_CONNECT_DATA(rsp, cntlid);
743 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
744 		}
745 
746 		/* Establish a new ctrlr */
747 		ctrlr = nvmf_ctrlr_create(subsystem, req, cmd, data);
748 		if (!ctrlr) {
749 			SPDK_ERRLOG("nvmf_ctrlr_create() failed\n");
750 			rsp->status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
751 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
752 		} else {
753 			return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
754 		}
755 	} else {
756 		spdk_thread_send_msg(subsystem->thread, _nvmf_ctrlr_add_io_qpair, req);
757 		return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
758 	}
759 }
760 
761 static inline bool
762 nvmf_request_is_fabric_connect(struct spdk_nvmf_request *req)
763 {
764 	return req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC &&
765 	       req->cmd->nvmf_cmd.fctype == SPDK_NVMF_FABRIC_COMMAND_CONNECT;
766 }
767 
768 static struct spdk_nvmf_subsystem_poll_group *
769 nvmf_subsystem_pg_from_connect_cmd(struct spdk_nvmf_request *req)
770 {
771 	struct spdk_nvmf_fabric_connect_data *data;
772 	struct spdk_nvmf_subsystem *subsystem;
773 	struct spdk_nvmf_tgt *tgt;
774 
775 	assert(nvmf_request_is_fabric_connect(req));
776 	assert(req->qpair->ctrlr == NULL);
777 
778 	data = req->data;
779 	tgt = req->qpair->transport->tgt;
780 
781 	subsystem = spdk_nvmf_tgt_find_subsystem(tgt, data->subnqn);
782 	if (subsystem == NULL) {
783 		return NULL;
784 	}
785 
786 	return &req->qpair->group->sgroups[subsystem->id];
787 }
788 
789 static void
790 nvmf_add_to_outstanding_queue(struct spdk_nvmf_request *req)
791 {
792 	if (!spdk_nvmf_using_zcopy(req->zcopy_phase)) {
793 		/* if using zcopy then request has been added when the start zcopy was actioned */
794 		struct spdk_nvmf_qpair *qpair = req->qpair;
795 		TAILQ_INSERT_TAIL(&qpair->outstanding, req, link);
796 	}
797 }
798 
799 int
800 spdk_nvmf_ctrlr_connect(struct spdk_nvmf_request *req)
801 {
802 	struct spdk_nvmf_fabric_connect_rsp *rsp = &req->rsp->connect_rsp;
803 	struct spdk_nvmf_subsystem_poll_group *sgroup;
804 	enum spdk_nvmf_request_exec_status status;
805 
806 	sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
807 	if (!sgroup) {
808 		SPDK_NVMF_INVALID_CONNECT_DATA(rsp, subnqn);
809 		status = SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
810 		goto out;
811 	}
812 
813 	sgroup->mgmt_io_outstanding++;
814 	nvmf_add_to_outstanding_queue(req);
815 
816 	status = _nvmf_ctrlr_connect(req);
817 
818 out:
819 	if (status == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
820 		_nvmf_request_complete(req);
821 	}
822 
823 	return status;
824 }
825 
826 static int nvmf_ctrlr_cmd_connect(struct spdk_nvmf_request *req);
827 
828 static int
829 retry_connect(void *arg)
830 {
831 	struct spdk_nvmf_request *req = arg;
832 	struct spdk_nvmf_subsystem_poll_group *sgroup;
833 	int rc;
834 
835 	sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
836 	assert(sgroup != NULL);
837 	sgroup->mgmt_io_outstanding++;
838 	spdk_poller_unregister(&req->poller);
839 	rc = nvmf_ctrlr_cmd_connect(req);
840 	if (rc == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
841 		_nvmf_request_complete(req);
842 	}
843 	return SPDK_POLLER_BUSY;
844 }
845 
846 static int
847 nvmf_ctrlr_cmd_connect(struct spdk_nvmf_request *req)
848 {
849 	struct spdk_nvmf_fabric_connect_data *data = req->data;
850 	struct spdk_nvmf_fabric_connect_rsp *rsp = &req->rsp->connect_rsp;
851 	struct spdk_nvmf_transport *transport = req->qpair->transport;
852 	struct spdk_nvmf_subsystem *subsystem;
853 
854 	if (req->length < sizeof(struct spdk_nvmf_fabric_connect_data)) {
855 		SPDK_ERRLOG("Connect command data length 0x%x too small\n", req->length);
856 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
857 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
858 	}
859 
860 	subsystem = spdk_nvmf_tgt_find_subsystem(transport->tgt, data->subnqn);
861 	if (!subsystem) {
862 		SPDK_NVMF_INVALID_CONNECT_DATA(rsp, subnqn);
863 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
864 	}
865 
866 	if ((subsystem->state == SPDK_NVMF_SUBSYSTEM_INACTIVE) ||
867 	    (subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSING) ||
868 	    (subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSED) ||
869 	    (subsystem->state == SPDK_NVMF_SUBSYSTEM_DEACTIVATING)) {
870 		struct spdk_nvmf_subsystem_poll_group *sgroup;
871 
872 		if (req->timeout_tsc == 0) {
873 			/* We will only retry the request up to 1 second. */
874 			req->timeout_tsc = spdk_get_ticks() + spdk_get_ticks_hz();
875 		} else if (spdk_get_ticks() > req->timeout_tsc) {
876 			SPDK_ERRLOG("Subsystem '%s' was not ready for 1 second\n", subsystem->subnqn);
877 			rsp->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
878 			rsp->status.sc = SPDK_NVMF_FABRIC_SC_CONTROLLER_BUSY;
879 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
880 		}
881 
882 		/* Subsystem is not ready to handle a connect. Use a poller to retry it
883 		 * again later. Decrement the mgmt_io_outstanding to avoid the
884 		 * subsystem waiting for this command to complete before unpausing.
885 		 */
886 		sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
887 		assert(sgroup != NULL);
888 		sgroup->mgmt_io_outstanding--;
889 		SPDK_DEBUGLOG(nvmf, "Subsystem '%s' is not ready for connect, retrying...\n", subsystem->subnqn);
890 		req->poller = SPDK_POLLER_REGISTER(retry_connect, req, 100);
891 		return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
892 	}
893 
894 	/* Ensure that hostnqn is null terminated */
895 	if (!memchr(data->hostnqn, '\0', SPDK_NVMF_NQN_MAX_LEN + 1)) {
896 		SPDK_ERRLOG("Connect HOSTNQN is not null terminated\n");
897 		SPDK_NVMF_INVALID_CONNECT_DATA(rsp, hostnqn);
898 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
899 	}
900 
901 	if (!nvmf_qpair_access_allowed(req->qpair, subsystem, data->hostnqn)) {
902 		rsp->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
903 		rsp->status.sc = SPDK_NVMF_FABRIC_SC_INVALID_HOST;
904 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
905 	}
906 
907 	return _nvmf_ctrlr_connect(req);
908 }
909 
910 static int
911 nvmf_ctrlr_association_remove(void *ctx)
912 {
913 	struct spdk_nvmf_ctrlr *ctrlr = ctx;
914 	int rc;
915 
916 	nvmf_ctrlr_stop_association_timer(ctrlr);
917 
918 	if (ctrlr->in_destruct) {
919 		return SPDK_POLLER_IDLE;
920 	}
921 	SPDK_DEBUGLOG(nvmf, "Disconnecting host from subsystem %s due to association timeout.\n",
922 		      ctrlr->subsys->subnqn);
923 
924 	rc = spdk_nvmf_qpair_disconnect(ctrlr->admin_qpair, NULL, NULL);
925 	if (rc < 0) {
926 		SPDK_ERRLOG("Fail to disconnect admin ctrlr qpair\n");
927 		assert(false);
928 	}
929 
930 	return SPDK_POLLER_BUSY;
931 }
932 
933 static void
934 nvmf_ctrlr_cc_shn_done(struct spdk_io_channel_iter *i, int status)
935 {
936 	struct spdk_nvmf_ctrlr *ctrlr = spdk_io_channel_iter_get_ctx(i);
937 
938 	if (status < 0) {
939 		SPDK_ERRLOG("Fail to disconnect io ctrlr qpairs\n");
940 		assert(false);
941 	}
942 
943 	ctrlr->vcprop.csts.bits.shst = SPDK_NVME_SHST_COMPLETE;
944 
945 	/* After CC.EN transitions to 0 (due to shutdown or reset), the association
946 	 * between the host and controller shall be preserved for at least 2 minutes */
947 	if (ctrlr->association_timer) {
948 		SPDK_DEBUGLOG(nvmf, "Association timer already set\n");
949 		nvmf_ctrlr_stop_association_timer(ctrlr);
950 	}
951 	if (ctrlr->association_timeout) {
952 		ctrlr->association_timer = SPDK_POLLER_REGISTER(nvmf_ctrlr_association_remove, ctrlr,
953 					   ctrlr->association_timeout * 1000);
954 	}
955 	ctrlr->disconnect_in_progress = false;
956 }
957 
958 static void
959 nvmf_ctrlr_cc_reset_done(struct spdk_io_channel_iter *i, int status)
960 {
961 	struct spdk_nvmf_ctrlr *ctrlr = spdk_io_channel_iter_get_ctx(i);
962 
963 	if (status < 0) {
964 		SPDK_ERRLOG("Fail to disconnect io ctrlr qpairs\n");
965 		assert(false);
966 	}
967 
968 	/* Only a subset of the registers are cleared out on a reset */
969 	ctrlr->vcprop.cc.raw = 0;
970 	ctrlr->vcprop.csts.raw = 0;
971 
972 	/* After CC.EN transitions to 0 (due to shutdown or reset), the association
973 	 * between the host and controller shall be preserved for at least 2 minutes */
974 	if (ctrlr->association_timer) {
975 		SPDK_DEBUGLOG(nvmf, "Association timer already set\n");
976 		nvmf_ctrlr_stop_association_timer(ctrlr);
977 	}
978 	if (ctrlr->association_timeout) {
979 		ctrlr->association_timer = SPDK_POLLER_REGISTER(nvmf_ctrlr_association_remove, ctrlr,
980 					   ctrlr->association_timeout * 1000);
981 	}
982 	ctrlr->disconnect_in_progress = false;
983 }
984 
985 const struct spdk_nvmf_registers *
986 spdk_nvmf_ctrlr_get_regs(struct spdk_nvmf_ctrlr *ctrlr)
987 {
988 	return &ctrlr->vcprop;
989 }
990 
991 static uint64_t
992 nvmf_prop_get_cap(struct spdk_nvmf_ctrlr *ctrlr)
993 {
994 	return ctrlr->vcprop.cap.raw;
995 }
996 
997 static uint64_t
998 nvmf_prop_get_vs(struct spdk_nvmf_ctrlr *ctrlr)
999 {
1000 	return ctrlr->vcprop.vs.raw;
1001 }
1002 
1003 static uint64_t
1004 nvmf_prop_get_cc(struct spdk_nvmf_ctrlr *ctrlr)
1005 {
1006 	return ctrlr->vcprop.cc.raw;
1007 }
1008 
1009 static bool
1010 nvmf_prop_set_cc(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value)
1011 {
1012 	union spdk_nvme_cc_register cc, diff;
1013 
1014 	cc.raw = value;
1015 
1016 	SPDK_DEBUGLOG(nvmf, "cur CC: 0x%08x\n", ctrlr->vcprop.cc.raw);
1017 	SPDK_DEBUGLOG(nvmf, "new CC: 0x%08x\n", cc.raw);
1018 
1019 	/*
1020 	 * Calculate which bits changed between the current and new CC.
1021 	 * Mark each bit as 0 once it is handled to determine if any unhandled bits were changed.
1022 	 */
1023 	diff.raw = cc.raw ^ ctrlr->vcprop.cc.raw;
1024 
1025 	if (diff.bits.en) {
1026 		if (cc.bits.en) {
1027 			SPDK_DEBUGLOG(nvmf, "Property Set CC Enable!\n");
1028 			nvmf_ctrlr_stop_association_timer(ctrlr);
1029 
1030 			ctrlr->vcprop.cc.bits.en = 1;
1031 			ctrlr->vcprop.csts.bits.rdy = 1;
1032 		} else {
1033 			SPDK_DEBUGLOG(nvmf, "Property Set CC Disable!\n");
1034 			ctrlr->vcprop.cc.bits.en = 0;
1035 			ctrlr->disconnect_in_progress = true;
1036 			spdk_for_each_channel(ctrlr->subsys->tgt,
1037 					      nvmf_ctrlr_disconnect_io_qpairs_on_pg,
1038 					      ctrlr,
1039 					      nvmf_ctrlr_cc_reset_done);
1040 		}
1041 		diff.bits.en = 0;
1042 	}
1043 
1044 	if (diff.bits.shn) {
1045 		if (cc.bits.shn == SPDK_NVME_SHN_NORMAL ||
1046 		    cc.bits.shn == SPDK_NVME_SHN_ABRUPT) {
1047 			SPDK_DEBUGLOG(nvmf, "Property Set CC Shutdown %u%ub!\n",
1048 				      cc.bits.shn >> 1, cc.bits.shn & 1);
1049 			ctrlr->vcprop.cc.bits.shn = cc.bits.shn;
1050 			ctrlr->disconnect_in_progress = true;
1051 			spdk_for_each_channel(ctrlr->subsys->tgt,
1052 					      nvmf_ctrlr_disconnect_io_qpairs_on_pg,
1053 					      ctrlr,
1054 					      nvmf_ctrlr_cc_shn_done);
1055 
1056 			/* From the time a shutdown is initiated the controller shall disable
1057 			 * Keep Alive timer */
1058 			nvmf_ctrlr_stop_keep_alive_timer(ctrlr);
1059 		} else if (cc.bits.shn == 0) {
1060 			ctrlr->vcprop.cc.bits.shn = 0;
1061 		} else {
1062 			SPDK_ERRLOG("Prop Set CC: Invalid SHN value %u%ub\n",
1063 				    cc.bits.shn >> 1, cc.bits.shn & 1);
1064 			return false;
1065 		}
1066 		diff.bits.shn = 0;
1067 	}
1068 
1069 	if (diff.bits.iosqes) {
1070 		SPDK_DEBUGLOG(nvmf, "Prop Set IOSQES = %u (%u bytes)\n",
1071 			      cc.bits.iosqes, 1u << cc.bits.iosqes);
1072 		ctrlr->vcprop.cc.bits.iosqes = cc.bits.iosqes;
1073 		diff.bits.iosqes = 0;
1074 	}
1075 
1076 	if (diff.bits.iocqes) {
1077 		SPDK_DEBUGLOG(nvmf, "Prop Set IOCQES = %u (%u bytes)\n",
1078 			      cc.bits.iocqes, 1u << cc.bits.iocqes);
1079 		ctrlr->vcprop.cc.bits.iocqes = cc.bits.iocqes;
1080 		diff.bits.iocqes = 0;
1081 	}
1082 
1083 	if (diff.bits.ams) {
1084 		SPDK_ERRLOG("Arbitration Mechanism Selected (AMS) 0x%x not supported!\n", cc.bits.ams);
1085 		return false;
1086 	}
1087 
1088 	if (diff.bits.mps) {
1089 		SPDK_ERRLOG("Memory Page Size (MPS) %u KiB not supported!\n", (1 << (2 + cc.bits.mps)));
1090 		return false;
1091 	}
1092 
1093 	if (diff.bits.css) {
1094 		SPDK_ERRLOG("I/O Command Set Selected (CSS) 0x%x not supported!\n", cc.bits.css);
1095 		return false;
1096 	}
1097 
1098 	if (diff.raw != 0) {
1099 		/* Print an error message, but don't fail the command in this case.
1100 		 * If we did want to fail in this case, we'd need to ensure we acted
1101 		 * on no other bits or the initiator gets confused. */
1102 		SPDK_ERRLOG("Prop Set CC toggled reserved bits 0x%x!\n", diff.raw);
1103 	}
1104 
1105 	return true;
1106 }
1107 
1108 static uint64_t
1109 nvmf_prop_get_csts(struct spdk_nvmf_ctrlr *ctrlr)
1110 {
1111 	return ctrlr->vcprop.csts.raw;
1112 }
1113 
1114 static uint64_t
1115 nvmf_prop_get_aqa(struct spdk_nvmf_ctrlr *ctrlr)
1116 {
1117 	return ctrlr->vcprop.aqa.raw;
1118 }
1119 
1120 static bool
1121 nvmf_prop_set_aqa(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value)
1122 {
1123 	union spdk_nvme_aqa_register aqa;
1124 
1125 	aqa.raw = value;
1126 
1127 	if (aqa.bits.asqs < SPDK_NVME_ADMIN_QUEUE_MIN_ENTRIES - 1 ||
1128 	    aqa.bits.acqs < SPDK_NVME_ADMIN_QUEUE_MIN_ENTRIES - 1 ||
1129 	    aqa.bits.reserved1 != 0 || aqa.bits.reserved2 != 0) {
1130 		return false;
1131 	}
1132 
1133 	ctrlr->vcprop.aqa.raw = value;
1134 
1135 	return true;
1136 }
1137 
1138 static uint64_t
1139 nvmf_prop_get_asq(struct spdk_nvmf_ctrlr *ctrlr)
1140 {
1141 	return ctrlr->vcprop.asq;
1142 }
1143 
1144 static bool
1145 nvmf_prop_set_asq_lower(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value)
1146 {
1147 	ctrlr->vcprop.asq = (ctrlr->vcprop.asq & (0xFFFFFFFFULL << 32ULL)) | value;
1148 
1149 	return true;
1150 }
1151 
1152 static bool
1153 nvmf_prop_set_asq_upper(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value)
1154 {
1155 	ctrlr->vcprop.asq = (ctrlr->vcprop.asq & 0xFFFFFFFFULL) | ((uint64_t)value << 32ULL);
1156 
1157 	return true;
1158 }
1159 
1160 static uint64_t
1161 nvmf_prop_get_acq(struct spdk_nvmf_ctrlr *ctrlr)
1162 {
1163 	return ctrlr->vcprop.acq;
1164 }
1165 
1166 static bool
1167 nvmf_prop_set_acq_lower(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value)
1168 {
1169 	ctrlr->vcprop.acq = (ctrlr->vcprop.acq & (0xFFFFFFFFULL << 32ULL)) | value;
1170 
1171 	return true;
1172 }
1173 
1174 static bool
1175 nvmf_prop_set_acq_upper(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value)
1176 {
1177 	ctrlr->vcprop.acq = (ctrlr->vcprop.acq & 0xFFFFFFFFULL) | ((uint64_t)value << 32ULL);
1178 
1179 	return true;
1180 }
1181 
1182 struct nvmf_prop {
1183 	uint32_t ofst;
1184 	uint8_t size;
1185 	char name[11];
1186 	uint64_t (*get_cb)(struct spdk_nvmf_ctrlr *ctrlr);
1187 	bool (*set_cb)(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value);
1188 	bool (*set_upper_cb)(struct spdk_nvmf_ctrlr *ctrlr, uint32_t value);
1189 };
1190 
1191 #define PROP(field, size, get_cb, set_cb, set_upper_cb) \
1192 	{ \
1193 		offsetof(struct spdk_nvme_registers, field), \
1194 		size, \
1195 		#field, \
1196 		get_cb, set_cb, set_upper_cb \
1197 	}
1198 
1199 static const struct nvmf_prop nvmf_props[] = {
1200 	PROP(cap,  8, nvmf_prop_get_cap,  NULL,                    NULL),
1201 	PROP(vs,   4, nvmf_prop_get_vs,   NULL,                    NULL),
1202 	PROP(cc,   4, nvmf_prop_get_cc,   nvmf_prop_set_cc,        NULL),
1203 	PROP(csts, 4, nvmf_prop_get_csts, NULL,                    NULL),
1204 	PROP(aqa,  4, nvmf_prop_get_aqa,  nvmf_prop_set_aqa,       NULL),
1205 	PROP(asq,  8, nvmf_prop_get_asq,  nvmf_prop_set_asq_lower, nvmf_prop_set_asq_upper),
1206 	PROP(acq,  8, nvmf_prop_get_acq,  nvmf_prop_set_acq_lower, nvmf_prop_set_acq_upper),
1207 };
1208 
1209 static const struct nvmf_prop *
1210 find_prop(uint32_t ofst, uint8_t size)
1211 {
1212 	size_t i;
1213 
1214 	for (i = 0; i < SPDK_COUNTOF(nvmf_props); i++) {
1215 		const struct nvmf_prop *prop = &nvmf_props[i];
1216 
1217 		if ((ofst >= prop->ofst) && (ofst + size <= prop->ofst + prop->size)) {
1218 			return prop;
1219 		}
1220 	}
1221 
1222 	return NULL;
1223 }
1224 
1225 static int
1226 nvmf_property_get(struct spdk_nvmf_request *req)
1227 {
1228 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1229 	struct spdk_nvmf_fabric_prop_get_cmd *cmd = &req->cmd->prop_get_cmd;
1230 	struct spdk_nvmf_fabric_prop_get_rsp *response = &req->rsp->prop_get_rsp;
1231 	const struct nvmf_prop *prop;
1232 	uint8_t size;
1233 
1234 	response->status.sc = 0;
1235 	response->value.u64 = 0;
1236 
1237 	SPDK_DEBUGLOG(nvmf, "size %d, offset 0x%x\n",
1238 		      cmd->attrib.size, cmd->ofst);
1239 
1240 	switch (cmd->attrib.size) {
1241 	case SPDK_NVMF_PROP_SIZE_4:
1242 		size = 4;
1243 		break;
1244 	case SPDK_NVMF_PROP_SIZE_8:
1245 		size = 8;
1246 		break;
1247 	default:
1248 		SPDK_ERRLOG("Invalid size value %d\n", cmd->attrib.size);
1249 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1250 		response->status.sc = SPDK_NVMF_FABRIC_SC_INVALID_PARAM;
1251 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1252 	}
1253 
1254 	prop = find_prop(cmd->ofst, size);
1255 	if (prop == NULL || prop->get_cb == NULL) {
1256 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1257 		response->status.sc = SPDK_NVMF_FABRIC_SC_INVALID_PARAM;
1258 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1259 	}
1260 
1261 	SPDK_DEBUGLOG(nvmf, "name: %s\n", prop->name);
1262 
1263 	response->value.u64 = prop->get_cb(ctrlr);
1264 
1265 	if (size != prop->size) {
1266 		/* The size must be 4 and the prop->size is 8. Figure out which part of the property to read. */
1267 		assert(size == 4);
1268 		assert(prop->size == 8);
1269 
1270 		if (cmd->ofst == prop->ofst) {
1271 			/* Keep bottom 4 bytes only */
1272 			response->value.u64 &= 0xFFFFFFFF;
1273 		} else {
1274 			/* Keep top 4 bytes only */
1275 			response->value.u64 >>= 32;
1276 		}
1277 	}
1278 
1279 	SPDK_DEBUGLOG(nvmf, "response value: 0x%" PRIx64 "\n", response->value.u64);
1280 
1281 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1282 }
1283 
1284 static int
1285 nvmf_property_set(struct spdk_nvmf_request *req)
1286 {
1287 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1288 	struct spdk_nvmf_fabric_prop_set_cmd *cmd = &req->cmd->prop_set_cmd;
1289 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
1290 	const struct nvmf_prop *prop;
1291 	uint64_t value;
1292 	uint8_t size;
1293 	bool ret;
1294 
1295 	SPDK_DEBUGLOG(nvmf, "size %d, offset 0x%x, value 0x%" PRIx64 "\n",
1296 		      cmd->attrib.size, cmd->ofst, cmd->value.u64);
1297 
1298 	switch (cmd->attrib.size) {
1299 	case SPDK_NVMF_PROP_SIZE_4:
1300 		size = 4;
1301 		break;
1302 	case SPDK_NVMF_PROP_SIZE_8:
1303 		size = 8;
1304 		break;
1305 	default:
1306 		SPDK_ERRLOG("Invalid size value %d\n", cmd->attrib.size);
1307 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1308 		response->status.sc = SPDK_NVMF_FABRIC_SC_INVALID_PARAM;
1309 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1310 	}
1311 
1312 	prop = find_prop(cmd->ofst, size);
1313 	if (prop == NULL || prop->set_cb == NULL) {
1314 		SPDK_INFOLOG(nvmf, "Invalid offset 0x%x\n", cmd->ofst);
1315 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1316 		response->status.sc = SPDK_NVMF_FABRIC_SC_INVALID_PARAM;
1317 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1318 	}
1319 
1320 	SPDK_DEBUGLOG(nvmf, "name: %s\n", prop->name);
1321 
1322 	value = cmd->value.u64;
1323 
1324 	if (prop->size == 4) {
1325 		ret = prop->set_cb(ctrlr, (uint32_t)value);
1326 	} else if (size != prop->size) {
1327 		/* The size must be 4 and the prop->size is 8. Figure out which part of the property to write. */
1328 		assert(size == 4);
1329 		assert(prop->size == 8);
1330 
1331 		if (cmd->ofst == prop->ofst) {
1332 			ret = prop->set_cb(ctrlr, (uint32_t)value);
1333 		} else {
1334 			ret = prop->set_upper_cb(ctrlr, (uint32_t)value);
1335 		}
1336 	} else {
1337 		ret = prop->set_cb(ctrlr, (uint32_t)value);
1338 		if (ret) {
1339 			ret = prop->set_upper_cb(ctrlr, (uint32_t)(value >> 32));
1340 		}
1341 	}
1342 
1343 	if (!ret) {
1344 		SPDK_ERRLOG("prop set_cb failed\n");
1345 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1346 		response->status.sc = SPDK_NVMF_FABRIC_SC_INVALID_PARAM;
1347 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1348 	}
1349 
1350 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1351 }
1352 
1353 static int
1354 nvmf_ctrlr_set_features_arbitration(struct spdk_nvmf_request *req)
1355 {
1356 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1357 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1358 
1359 	SPDK_DEBUGLOG(nvmf, "Set Features - Arbitration (cdw11 = 0x%0x)\n", cmd->cdw11);
1360 
1361 	ctrlr->feat.arbitration.raw = cmd->cdw11;
1362 	ctrlr->feat.arbitration.bits.reserved = 0;
1363 
1364 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1365 }
1366 
1367 static int
1368 nvmf_ctrlr_set_features_power_management(struct spdk_nvmf_request *req)
1369 {
1370 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1371 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1372 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1373 
1374 	SPDK_DEBUGLOG(nvmf, "Set Features - Power Management (cdw11 = 0x%0x)\n", cmd->cdw11);
1375 
1376 	/* Only PS = 0 is allowed, since we report NPSS = 0 */
1377 	if (cmd->cdw11_bits.feat_power_management.bits.ps != 0) {
1378 		SPDK_ERRLOG("Invalid power state %u\n", cmd->cdw11_bits.feat_power_management.bits.ps);
1379 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
1380 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1381 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1382 	}
1383 
1384 	ctrlr->feat.power_management.raw = cmd->cdw11;
1385 	ctrlr->feat.power_management.bits.reserved = 0;
1386 
1387 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1388 }
1389 
1390 static bool
1391 temp_threshold_opts_valid(const union spdk_nvme_feat_temperature_threshold *opts)
1392 {
1393 	/*
1394 	 * Valid TMPSEL values:
1395 	 *  0000b - 1000b: temperature sensors
1396 	 *  1111b: set all implemented temperature sensors
1397 	 */
1398 	if (opts->bits.tmpsel >= 9 && opts->bits.tmpsel != 15) {
1399 		/* 1001b - 1110b: reserved */
1400 		SPDK_ERRLOG("Invalid TMPSEL %u\n", opts->bits.tmpsel);
1401 		return false;
1402 	}
1403 
1404 	/*
1405 	 * Valid THSEL values:
1406 	 *  00b: over temperature threshold
1407 	 *  01b: under temperature threshold
1408 	 */
1409 	if (opts->bits.thsel > 1) {
1410 		/* 10b - 11b: reserved */
1411 		SPDK_ERRLOG("Invalid THSEL %u\n", opts->bits.thsel);
1412 		return false;
1413 	}
1414 
1415 	return true;
1416 }
1417 
1418 static int
1419 nvmf_ctrlr_set_features_temperature_threshold(struct spdk_nvmf_request *req)
1420 {
1421 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1422 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1423 
1424 	SPDK_DEBUGLOG(nvmf, "Set Features - Temperature Threshold (cdw11 = 0x%0x)\n", cmd->cdw11);
1425 
1426 	if (!temp_threshold_opts_valid(&cmd->cdw11_bits.feat_temp_threshold)) {
1427 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
1428 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1429 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1430 	}
1431 
1432 	/* TODO: no sensors implemented - ignore new values */
1433 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1434 }
1435 
1436 static int
1437 nvmf_ctrlr_get_features_temperature_threshold(struct spdk_nvmf_request *req)
1438 {
1439 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1440 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1441 
1442 	SPDK_DEBUGLOG(nvmf, "Get Features - Temperature Threshold (cdw11 = 0x%0x)\n", cmd->cdw11);
1443 
1444 	if (!temp_threshold_opts_valid(&cmd->cdw11_bits.feat_temp_threshold)) {
1445 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
1446 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1447 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1448 	}
1449 
1450 	/* TODO: no sensors implemented - return 0 for all thresholds */
1451 	rsp->cdw0 = 0;
1452 
1453 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1454 }
1455 
1456 static int
1457 nvmf_ctrlr_get_features_interrupt_vector_configuration(struct spdk_nvmf_request *req)
1458 {
1459 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1460 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1461 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1462 	union spdk_nvme_feat_interrupt_vector_configuration iv_conf = {};
1463 
1464 	SPDK_DEBUGLOG(nvmf, "Get Features - Interrupt Vector Configuration (cdw11 = 0x%0x)\n", cmd->cdw11);
1465 
1466 	iv_conf.bits.iv = cmd->cdw11_bits.feat_interrupt_vector_configuration.bits.iv;
1467 	iv_conf.bits.cd = ctrlr->feat.interrupt_vector_configuration.bits.cd;
1468 	rsp->cdw0 = iv_conf.raw;
1469 
1470 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1471 }
1472 
1473 static int
1474 nvmf_ctrlr_set_features_error_recovery(struct spdk_nvmf_request *req)
1475 {
1476 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1477 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1478 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1479 
1480 	SPDK_DEBUGLOG(nvmf, "Set Features - Error Recovery (cdw11 = 0x%0x)\n", cmd->cdw11);
1481 
1482 	if (cmd->cdw11_bits.feat_error_recovery.bits.dulbe) {
1483 		/*
1484 		 * Host is not allowed to set this bit, since we don't advertise it in
1485 		 * Identify Namespace.
1486 		 */
1487 		SPDK_ERRLOG("Host set unsupported DULBE bit\n");
1488 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
1489 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1490 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1491 	}
1492 
1493 	ctrlr->feat.error_recovery.raw = cmd->cdw11;
1494 	ctrlr->feat.error_recovery.bits.reserved = 0;
1495 
1496 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1497 }
1498 
1499 static int
1500 nvmf_ctrlr_set_features_volatile_write_cache(struct spdk_nvmf_request *req)
1501 {
1502 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1503 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1504 
1505 	SPDK_DEBUGLOG(nvmf, "Set Features - Volatile Write Cache (cdw11 = 0x%0x)\n", cmd->cdw11);
1506 
1507 	ctrlr->feat.volatile_write_cache.raw = cmd->cdw11;
1508 	ctrlr->feat.volatile_write_cache.bits.reserved = 0;
1509 
1510 	SPDK_DEBUGLOG(nvmf, "Set Features - Volatile Write Cache %s\n",
1511 		      ctrlr->feat.volatile_write_cache.bits.wce ? "Enabled" : "Disabled");
1512 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1513 }
1514 
1515 static int
1516 nvmf_ctrlr_set_features_write_atomicity(struct spdk_nvmf_request *req)
1517 {
1518 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1519 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1520 
1521 	SPDK_DEBUGLOG(nvmf, "Set Features - Write Atomicity (cdw11 = 0x%0x)\n", cmd->cdw11);
1522 
1523 	ctrlr->feat.write_atomicity.raw = cmd->cdw11;
1524 	ctrlr->feat.write_atomicity.bits.reserved = 0;
1525 
1526 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1527 }
1528 
1529 static int
1530 nvmf_ctrlr_set_features_host_identifier(struct spdk_nvmf_request *req)
1531 {
1532 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
1533 
1534 	SPDK_ERRLOG("Set Features - Host Identifier not allowed\n");
1535 	response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
1536 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1537 }
1538 
1539 static int
1540 nvmf_ctrlr_get_features_host_identifier(struct spdk_nvmf_request *req)
1541 {
1542 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1543 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1544 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
1545 
1546 	SPDK_DEBUGLOG(nvmf, "Get Features - Host Identifier\n");
1547 
1548 	if (!cmd->cdw11_bits.feat_host_identifier.bits.exhid) {
1549 		/* NVMe over Fabrics requires EXHID=1 (128-bit/16-byte host ID) */
1550 		SPDK_ERRLOG("Get Features - Host Identifier with EXHID=0 not allowed\n");
1551 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1552 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1553 	}
1554 
1555 	if (req->data == NULL || req->length < sizeof(ctrlr->hostid)) {
1556 		SPDK_ERRLOG("Invalid data buffer for Get Features - Host Identifier\n");
1557 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1558 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1559 	}
1560 
1561 	spdk_uuid_copy((struct spdk_uuid *)req->data, &ctrlr->hostid);
1562 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1563 }
1564 
1565 static int
1566 nvmf_ctrlr_get_features_reservation_notification_mask(struct spdk_nvmf_request *req)
1567 {
1568 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1569 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1570 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1571 	struct spdk_nvmf_ns *ns;
1572 
1573 	SPDK_DEBUGLOG(nvmf, "get Features - Reservation Notificaton Mask\n");
1574 
1575 	if (cmd->nsid == SPDK_NVME_GLOBAL_NS_TAG) {
1576 		SPDK_ERRLOG("get Features - Invalid Namespace ID\n");
1577 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1578 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1579 	}
1580 
1581 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, cmd->nsid);
1582 	if (ns == NULL) {
1583 		SPDK_ERRLOG("Set Features - Invalid Namespace ID\n");
1584 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1585 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1586 	}
1587 	rsp->cdw0 = ns->mask;
1588 
1589 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1590 }
1591 
1592 static int
1593 nvmf_ctrlr_set_features_reservation_notification_mask(struct spdk_nvmf_request *req)
1594 {
1595 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1596 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
1597 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1598 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1599 	struct spdk_nvmf_ns *ns;
1600 
1601 	SPDK_DEBUGLOG(nvmf, "Set Features - Reservation Notificaton Mask\n");
1602 
1603 	if (cmd->nsid == SPDK_NVME_GLOBAL_NS_TAG) {
1604 		for (ns = spdk_nvmf_subsystem_get_first_ns(subsystem); ns != NULL;
1605 		     ns = spdk_nvmf_subsystem_get_next_ns(subsystem, ns)) {
1606 			ns->mask = cmd->cdw11;
1607 		}
1608 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1609 	}
1610 
1611 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, cmd->nsid);
1612 	if (ns == NULL) {
1613 		SPDK_ERRLOG("Set Features - Invalid Namespace ID\n");
1614 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1615 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1616 	}
1617 	ns->mask = cmd->cdw11;
1618 
1619 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1620 }
1621 
1622 static int
1623 nvmf_ctrlr_get_features_reservation_persistence(struct spdk_nvmf_request *req)
1624 {
1625 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1626 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1627 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
1628 	struct spdk_nvmf_ns *ns;
1629 
1630 	SPDK_DEBUGLOG(nvmf, "Get Features - Reservation Persistence\n");
1631 
1632 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, cmd->nsid);
1633 	/* NSID with SPDK_NVME_GLOBAL_NS_TAG (=0xffffffff) also included */
1634 	if (ns == NULL) {
1635 		SPDK_ERRLOG("Get Features - Invalid Namespace ID\n");
1636 		response->status.sct = SPDK_NVME_SCT_GENERIC;
1637 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1638 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1639 	}
1640 
1641 	response->cdw0 = ns->ptpl_activated;
1642 
1643 	response->status.sct = SPDK_NVME_SCT_GENERIC;
1644 	response->status.sc = SPDK_NVME_SC_SUCCESS;
1645 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1646 }
1647 
1648 static int
1649 nvmf_ctrlr_set_features_reservation_persistence(struct spdk_nvmf_request *req)
1650 {
1651 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1652 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1653 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
1654 	struct spdk_nvmf_ns *ns;
1655 	bool ptpl;
1656 
1657 	SPDK_DEBUGLOG(nvmf, "Set Features - Reservation Persistence\n");
1658 
1659 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, cmd->nsid);
1660 	ptpl = cmd->cdw11_bits.feat_rsv_persistence.bits.ptpl;
1661 
1662 	if (cmd->nsid != SPDK_NVME_GLOBAL_NS_TAG && ns && ns->ptpl_file) {
1663 		ns->ptpl_activated = ptpl;
1664 	} else if (cmd->nsid == SPDK_NVME_GLOBAL_NS_TAG) {
1665 		for (ns = spdk_nvmf_subsystem_get_first_ns(ctrlr->subsys); ns && ns->ptpl_file;
1666 		     ns = spdk_nvmf_subsystem_get_next_ns(ctrlr->subsys, ns)) {
1667 			ns->ptpl_activated = ptpl;
1668 		}
1669 	} else {
1670 		SPDK_ERRLOG("Set Features - Invalid Namespace ID or Reservation Configuration\n");
1671 		response->status.sct = SPDK_NVME_SCT_GENERIC;
1672 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1673 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1674 	}
1675 
1676 	/* TODO: Feature not changeable for now */
1677 	response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1678 	response->status.sc = SPDK_NVME_SC_FEATURE_ID_NOT_SAVEABLE;
1679 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1680 }
1681 
1682 static int
1683 nvmf_ctrlr_set_features_host_behavior_support(struct spdk_nvmf_request *req)
1684 {
1685 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1686 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
1687 	struct spdk_nvme_host_behavior *host_behavior;
1688 
1689 	SPDK_DEBUGLOG(nvmf, "Set Features - Host Behavior Support\n");
1690 	if (req->iovcnt != 1) {
1691 		SPDK_ERRLOG("Host Behavior Support invalid iovcnt: %d\n", req->iovcnt);
1692 		response->status.sct = SPDK_NVME_SCT_GENERIC;
1693 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1694 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1695 	}
1696 	if (req->iov[0].iov_len != sizeof(struct spdk_nvme_host_behavior)) {
1697 		SPDK_ERRLOG("Host Behavior Support invalid iov_len: %zd\n", req->iov[0].iov_len);
1698 		response->status.sct = SPDK_NVME_SCT_GENERIC;
1699 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1700 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1701 	}
1702 
1703 	host_behavior = (struct spdk_nvme_host_behavior *)req->iov[0].iov_base;
1704 	if (host_behavior->acre == 0) {
1705 		ctrlr->acre_enabled = false;
1706 	} else if (host_behavior->acre == 1) {
1707 		ctrlr->acre_enabled = true;
1708 	} else {
1709 		SPDK_ERRLOG("Host Behavior Support invalid acre: 0x%02x\n", host_behavior->acre);
1710 		response->status.sct = SPDK_NVME_SCT_GENERIC;
1711 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
1712 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1713 	}
1714 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1715 }
1716 
1717 static int
1718 nvmf_ctrlr_set_features_keep_alive_timer(struct spdk_nvmf_request *req)
1719 {
1720 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1721 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1722 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1723 
1724 	SPDK_DEBUGLOG(nvmf, "Set Features - Keep Alive Timer (%u ms)\n", cmd->cdw11);
1725 
1726 	/*
1727 	 * if attempts to disable keep alive by setting kato to 0h
1728 	 * a status value of keep alive invalid shall be returned
1729 	 */
1730 	if (cmd->cdw11_bits.feat_keep_alive_timer.bits.kato == 0) {
1731 		rsp->status.sc = SPDK_NVME_SC_KEEP_ALIVE_INVALID;
1732 	} else if (cmd->cdw11_bits.feat_keep_alive_timer.bits.kato < MIN_KEEP_ALIVE_TIMEOUT_IN_MS) {
1733 		ctrlr->feat.keep_alive_timer.bits.kato = MIN_KEEP_ALIVE_TIMEOUT_IN_MS;
1734 	} else {
1735 		/* round up to milliseconds */
1736 		ctrlr->feat.keep_alive_timer.bits.kato = spdk_divide_round_up(
1737 					cmd->cdw11_bits.feat_keep_alive_timer.bits.kato,
1738 					KAS_DEFAULT_VALUE * KAS_TIME_UNIT_IN_MS) *
1739 				KAS_DEFAULT_VALUE * KAS_TIME_UNIT_IN_MS;
1740 	}
1741 
1742 	/*
1743 	 * if change the keep alive timeout value successfully
1744 	 * update the keep alive poller.
1745 	 */
1746 	if (cmd->cdw11_bits.feat_keep_alive_timer.bits.kato != 0) {
1747 		if (ctrlr->keep_alive_poller != NULL) {
1748 			spdk_poller_unregister(&ctrlr->keep_alive_poller);
1749 		}
1750 		ctrlr->keep_alive_poller = SPDK_POLLER_REGISTER(nvmf_ctrlr_keep_alive_poll, ctrlr,
1751 					   ctrlr->feat.keep_alive_timer.bits.kato * 1000);
1752 	}
1753 
1754 	SPDK_DEBUGLOG(nvmf, "Set Features - Keep Alive Timer set to %u ms\n",
1755 		      ctrlr->feat.keep_alive_timer.bits.kato);
1756 
1757 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1758 }
1759 
1760 static int
1761 nvmf_ctrlr_set_features_number_of_queues(struct spdk_nvmf_request *req)
1762 {
1763 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1764 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1765 	uint32_t count;
1766 
1767 	SPDK_DEBUGLOG(nvmf, "Set Features - Number of Queues, cdw11 0x%x\n",
1768 		      req->cmd->nvme_cmd.cdw11);
1769 
1770 	count = spdk_bit_array_count_set(ctrlr->qpair_mask);
1771 	/* verify that the controller is ready to process commands */
1772 	if (count > 1) {
1773 		SPDK_DEBUGLOG(nvmf, "Queue pairs already active!\n");
1774 		rsp->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
1775 	} else {
1776 		/*
1777 		 * Ignore the value requested by the host -
1778 		 * always return the pre-configured value based on max_qpairs_allowed.
1779 		 */
1780 		rsp->cdw0 = ctrlr->feat.number_of_queues.raw;
1781 	}
1782 
1783 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1784 }
1785 
1786 static int
1787 nvmf_ctrlr_set_features_async_event_configuration(struct spdk_nvmf_request *req)
1788 {
1789 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1790 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
1791 
1792 	SPDK_DEBUGLOG(nvmf, "Set Features - Async Event Configuration, cdw11 0x%08x\n",
1793 		      cmd->cdw11);
1794 	ctrlr->feat.async_event_configuration.raw = cmd->cdw11;
1795 	ctrlr->feat.async_event_configuration.bits.reserved1 = 0;
1796 	ctrlr->feat.async_event_configuration.bits.reserved2 = 0;
1797 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1798 }
1799 
1800 static int
1801 nvmf_ctrlr_async_event_request(struct spdk_nvmf_request *req)
1802 {
1803 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
1804 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
1805 	struct spdk_nvmf_subsystem_poll_group *sgroup;
1806 	struct spdk_nvmf_async_event_completion *pending_event;
1807 
1808 	SPDK_DEBUGLOG(nvmf, "Async Event Request\n");
1809 
1810 	/* AER cmd is an exception */
1811 	sgroup = &req->qpair->group->sgroups[ctrlr->subsys->id];
1812 	assert(sgroup != NULL);
1813 	sgroup->mgmt_io_outstanding--;
1814 
1815 	/* Four asynchronous events are supported for now */
1816 	if (ctrlr->nr_aer_reqs >= NVMF_MAX_ASYNC_EVENTS) {
1817 		SPDK_DEBUGLOG(nvmf, "AERL exceeded\n");
1818 		rsp->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
1819 		rsp->status.sc = SPDK_NVME_SC_ASYNC_EVENT_REQUEST_LIMIT_EXCEEDED;
1820 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1821 	}
1822 
1823 	if (!STAILQ_EMPTY(&ctrlr->async_events)) {
1824 		pending_event = STAILQ_FIRST(&ctrlr->async_events);
1825 		rsp->cdw0 = pending_event->event.raw;
1826 		STAILQ_REMOVE(&ctrlr->async_events, pending_event, spdk_nvmf_async_event_completion, link);
1827 		free(pending_event);
1828 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
1829 	}
1830 
1831 	ctrlr->aer_req[ctrlr->nr_aer_reqs++] = req;
1832 	return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
1833 }
1834 
1835 struct copy_iovs_ctx {
1836 	struct iovec *iovs;
1837 	int iovcnt;
1838 	int cur_iov_idx;
1839 	size_t cur_iov_offset;
1840 };
1841 
1842 static void
1843 _init_copy_iovs_ctx(struct copy_iovs_ctx *copy_ctx, struct iovec *iovs, int iovcnt)
1844 {
1845 	int iov_idx = 0;
1846 	struct iovec *iov;
1847 
1848 	copy_ctx->iovs = iovs;
1849 	copy_ctx->iovcnt = iovcnt;
1850 	copy_ctx->cur_iov_idx = 0;
1851 	copy_ctx->cur_iov_offset = 0;
1852 
1853 	while (iov_idx < copy_ctx->iovcnt) {
1854 		iov = &copy_ctx->iovs[iov_idx];
1855 		memset(iov->iov_base, 0, iov->iov_len);
1856 		iov_idx++;
1857 	}
1858 }
1859 
1860 static size_t
1861 _copy_buf_to_iovs(struct copy_iovs_ctx *copy_ctx, const void *buf, size_t buf_len)
1862 {
1863 	size_t len, iov_remain_len, copied_len = 0;
1864 	struct iovec *iov;
1865 
1866 	if (buf_len == 0) {
1867 		return 0;
1868 	}
1869 
1870 	while (copy_ctx->cur_iov_idx < copy_ctx->iovcnt) {
1871 		iov = &copy_ctx->iovs[copy_ctx->cur_iov_idx];
1872 		iov_remain_len = iov->iov_len - copy_ctx->cur_iov_offset;
1873 		if (iov_remain_len == 0) {
1874 			copy_ctx->cur_iov_idx++;
1875 			copy_ctx->cur_iov_offset = 0;
1876 			continue;
1877 		}
1878 
1879 		len = spdk_min(iov_remain_len, buf_len - copied_len);
1880 		memcpy((char *)iov->iov_base + copy_ctx->cur_iov_offset,
1881 		       (const char *)buf + copied_len,
1882 		       len);
1883 		copied_len += len;
1884 		copy_ctx->cur_iov_offset += len;
1885 
1886 		if (buf_len == copied_len) {
1887 			return copied_len;
1888 		}
1889 	}
1890 
1891 	return copied_len;
1892 }
1893 
1894 static void
1895 nvmf_get_firmware_slot_log_page(struct iovec *iovs, int iovcnt, uint64_t offset, uint32_t length)
1896 {
1897 	struct spdk_nvme_firmware_page fw_page;
1898 	size_t copy_len;
1899 	struct copy_iovs_ctx copy_ctx;
1900 
1901 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
1902 
1903 	memset(&fw_page, 0, sizeof(fw_page));
1904 	fw_page.afi.active_slot = 1;
1905 	fw_page.afi.next_reset_slot = 0;
1906 	spdk_strcpy_pad(fw_page.revision[0], FW_VERSION, sizeof(fw_page.revision[0]), ' ');
1907 
1908 	if (offset < sizeof(fw_page)) {
1909 		copy_len = spdk_min(sizeof(fw_page) - offset, length);
1910 		if (copy_len > 0) {
1911 			_copy_buf_to_iovs(&copy_ctx, (const char *)&fw_page + offset, copy_len);
1912 		}
1913 	}
1914 }
1915 
1916 /*
1917  * Asynchronous Event Mask Bit
1918  */
1919 enum spdk_nvme_async_event_mask_bit {
1920 	/* Mask Namespace Change Notificaton */
1921 	SPDK_NVME_ASYNC_EVENT_NS_ATTR_CHANGE_MASK_BIT		= 0,
1922 	/* Mask Asymmetric Namespace Access Change Notification */
1923 	SPDK_NVME_ASYNC_EVENT_ANA_CHANGE_MASK_BIT		= 1,
1924 	/* Mask Discovery Log Change Notification */
1925 	SPDK_NVME_ASYNC_EVENT_DISCOVERY_LOG_CHANGE_MASK_BIT	= 2,
1926 	/* Mask Reservation Log Page Available Notification */
1927 	SPDK_NVME_ASYNC_EVENT_RESERVATION_LOG_AVAIL_MASK_BIT	= 3,
1928 	/* Mask Error Event */
1929 	SPDK_NVME_ASYNC_EVENT_ERROR_MASK_BIT			= 4,
1930 	/* 4 - 63 Reserved */
1931 };
1932 
1933 static inline void
1934 nvmf_ctrlr_unmask_aen(struct spdk_nvmf_ctrlr *ctrlr,
1935 		      enum spdk_nvme_async_event_mask_bit mask)
1936 {
1937 	ctrlr->notice_aen_mask &= ~(1 << mask);
1938 }
1939 
1940 static inline bool
1941 nvmf_ctrlr_mask_aen(struct spdk_nvmf_ctrlr *ctrlr,
1942 		    enum spdk_nvme_async_event_mask_bit mask)
1943 {
1944 	if (ctrlr->notice_aen_mask & (1 << mask)) {
1945 		return false;
1946 	} else {
1947 		ctrlr->notice_aen_mask |= (1 << mask);
1948 		return true;
1949 	}
1950 }
1951 
1952 /* we have to use the typedef in the function declaration to appease astyle. */
1953 typedef enum spdk_nvme_ana_state spdk_nvme_ana_state_t;
1954 
1955 static inline spdk_nvme_ana_state_t
1956 nvmf_ctrlr_get_ana_state(struct spdk_nvmf_ctrlr *ctrlr, uint32_t anagrpid)
1957 {
1958 	if (spdk_unlikely(ctrlr->listener == NULL)) {
1959 		return SPDK_NVME_ANA_INACCESSIBLE_STATE;
1960 	}
1961 
1962 	assert(anagrpid - 1 < ctrlr->subsys->max_nsid);
1963 	return ctrlr->listener->ana_state[anagrpid - 1];
1964 }
1965 
1966 static spdk_nvme_ana_state_t
1967 nvmf_ctrlr_get_ana_state_from_nsid(struct spdk_nvmf_ctrlr *ctrlr, uint32_t nsid)
1968 {
1969 	struct spdk_nvmf_ns *ns;
1970 
1971 	/* We do not have NVM subsystem specific ANA state. Hence if NSID is either
1972 	 * SPDK_NVMF_GLOBAL_NS_TAG, invalid, or for inactive namespace, return
1973 	 * the optimized state.
1974 	 */
1975 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
1976 	if (ns == NULL) {
1977 		return SPDK_NVME_ANA_OPTIMIZED_STATE;
1978 	}
1979 
1980 	return nvmf_ctrlr_get_ana_state(ctrlr, ns->anagrpid);
1981 }
1982 
1983 static void
1984 nvmf_get_error_log_page(struct spdk_nvmf_ctrlr *ctrlr, struct iovec *iovs, int iovcnt,
1985 			uint64_t offset, uint32_t length, uint32_t rae)
1986 {
1987 	if (!rae) {
1988 		nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_ERROR_MASK_BIT);
1989 	}
1990 
1991 	/* TODO: actually fill out log page data */
1992 }
1993 
1994 static void
1995 nvmf_get_ana_log_page(struct spdk_nvmf_ctrlr *ctrlr, struct iovec *iovs, int iovcnt,
1996 		      uint64_t offset, uint32_t length, uint32_t rae)
1997 {
1998 	struct spdk_nvme_ana_page ana_hdr;
1999 	struct spdk_nvme_ana_group_descriptor ana_desc;
2000 	size_t copy_len, copied_len;
2001 	uint32_t num_anagrp = 0, anagrpid;
2002 	struct spdk_nvmf_ns *ns;
2003 	struct copy_iovs_ctx copy_ctx;
2004 
2005 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
2006 
2007 	if (length == 0) {
2008 		goto done;
2009 	}
2010 
2011 	if (offset >= sizeof(ana_hdr)) {
2012 		offset -= sizeof(ana_hdr);
2013 	} else {
2014 		for (anagrpid = 1; anagrpid <= ctrlr->subsys->max_nsid; anagrpid++) {
2015 			if (ctrlr->subsys->ana_group[anagrpid - 1] > 0) {
2016 				num_anagrp++;
2017 			}
2018 		}
2019 
2020 		memset(&ana_hdr, 0, sizeof(ana_hdr));
2021 
2022 		ana_hdr.num_ana_group_desc = num_anagrp;
2023 		/* TODO: Support Change Count. */
2024 		ana_hdr.change_count = 0;
2025 
2026 		copy_len = spdk_min(sizeof(ana_hdr) - offset, length);
2027 		copied_len = _copy_buf_to_iovs(&copy_ctx, (const char *)&ana_hdr + offset, copy_len);
2028 		assert(copied_len == copy_len);
2029 		length -= copied_len;
2030 		offset = 0;
2031 	}
2032 
2033 	if (length == 0) {
2034 		goto done;
2035 	}
2036 
2037 	for (anagrpid = 1; anagrpid <= ctrlr->subsys->max_nsid; anagrpid++) {
2038 		if (ctrlr->subsys->ana_group[anagrpid - 1] == 0) {
2039 			continue;
2040 		}
2041 
2042 		if (offset >= sizeof(ana_desc)) {
2043 			offset -= sizeof(ana_desc);
2044 		} else {
2045 			memset(&ana_desc, 0, sizeof(ana_desc));
2046 
2047 			ana_desc.ana_group_id = anagrpid;
2048 			ana_desc.num_of_nsid = ctrlr->subsys->ana_group[anagrpid - 1];
2049 			ana_desc.ana_state = nvmf_ctrlr_get_ana_state(ctrlr, anagrpid);
2050 
2051 			copy_len = spdk_min(sizeof(ana_desc) - offset, length);
2052 			copied_len = _copy_buf_to_iovs(&copy_ctx, (const char *)&ana_desc + offset,
2053 						       copy_len);
2054 			assert(copied_len == copy_len);
2055 			length -= copied_len;
2056 			offset = 0;
2057 
2058 			if (length == 0) {
2059 				goto done;
2060 			}
2061 		}
2062 
2063 		/* TODO: Revisit here about O(n^2) cost if we have subsystem with
2064 		 * many namespaces in the future.
2065 		 */
2066 		for (ns = spdk_nvmf_subsystem_get_first_ns(ctrlr->subsys); ns != NULL;
2067 		     ns = spdk_nvmf_subsystem_get_next_ns(ctrlr->subsys, ns)) {
2068 			if (ns->anagrpid != anagrpid) {
2069 				continue;
2070 			}
2071 
2072 			if (offset >= sizeof(uint32_t)) {
2073 				offset -= sizeof(uint32_t);
2074 				continue;
2075 			}
2076 
2077 			copy_len = spdk_min(sizeof(uint32_t) - offset, length);
2078 			copied_len = _copy_buf_to_iovs(&copy_ctx, (const char *)&ns->nsid + offset,
2079 						       copy_len);
2080 			assert(copied_len == copy_len);
2081 			length -= copied_len;
2082 			offset = 0;
2083 
2084 			if (length == 0) {
2085 				goto done;
2086 			}
2087 		}
2088 	}
2089 
2090 done:
2091 	if (!rae) {
2092 		nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_ANA_CHANGE_MASK_BIT);
2093 	}
2094 }
2095 
2096 void
2097 nvmf_ctrlr_ns_changed(struct spdk_nvmf_ctrlr *ctrlr, uint32_t nsid)
2098 {
2099 	uint16_t max_changes = SPDK_COUNTOF(ctrlr->changed_ns_list.ns_list);
2100 	uint16_t i;
2101 	bool found = false;
2102 
2103 	for (i = 0; i < ctrlr->changed_ns_list_count; i++) {
2104 		if (ctrlr->changed_ns_list.ns_list[i] == nsid) {
2105 			/* nsid is already in the list */
2106 			found = true;
2107 			break;
2108 		}
2109 	}
2110 
2111 	if (!found) {
2112 		if (ctrlr->changed_ns_list_count == max_changes) {
2113 			/* Out of space - set first entry to FFFFFFFFh and zero-fill the rest. */
2114 			ctrlr->changed_ns_list.ns_list[0] = 0xFFFFFFFFu;
2115 			for (i = 1; i < max_changes; i++) {
2116 				ctrlr->changed_ns_list.ns_list[i] = 0;
2117 			}
2118 		} else {
2119 			ctrlr->changed_ns_list.ns_list[ctrlr->changed_ns_list_count++] = nsid;
2120 		}
2121 	}
2122 }
2123 
2124 static void
2125 nvmf_get_changed_ns_list_log_page(struct spdk_nvmf_ctrlr *ctrlr,
2126 				  struct iovec *iovs, int iovcnt, uint64_t offset, uint32_t length, uint32_t rae)
2127 {
2128 	size_t copy_length;
2129 	struct copy_iovs_ctx copy_ctx;
2130 
2131 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
2132 
2133 	if (offset < sizeof(ctrlr->changed_ns_list)) {
2134 		copy_length = spdk_min(length, sizeof(ctrlr->changed_ns_list) - offset);
2135 		if (copy_length) {
2136 			_copy_buf_to_iovs(&copy_ctx, (char *)&ctrlr->changed_ns_list + offset, copy_length);
2137 		}
2138 	}
2139 
2140 	/* Clear log page each time it is read */
2141 	ctrlr->changed_ns_list_count = 0;
2142 	memset(&ctrlr->changed_ns_list, 0, sizeof(ctrlr->changed_ns_list));
2143 
2144 	if (!rae) {
2145 		nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_NS_ATTR_CHANGE_MASK_BIT);
2146 	}
2147 }
2148 
2149 /* The structure can be modified if we provide support for other commands in future */
2150 static const struct spdk_nvme_cmds_and_effect_log_page g_cmds_and_effect_log_page = {
2151 	.admin_cmds_supported = {
2152 		/* CSUPP, LBCC, NCC, NIC, CCC, CSE */
2153 		/* Get Log Page */
2154 		[SPDK_NVME_OPC_GET_LOG_PAGE]		= {1, 0, 0, 0, 0, 0, 0, 0},
2155 		/* Identify */
2156 		[SPDK_NVME_OPC_IDENTIFY]		= {1, 0, 0, 0, 0, 0, 0, 0},
2157 		/* Abort */
2158 		[SPDK_NVME_OPC_ABORT]			= {1, 0, 0, 0, 0, 0, 0, 0},
2159 		/* Set Features */
2160 		[SPDK_NVME_OPC_SET_FEATURES]		= {1, 0, 0, 0, 0, 0, 0, 0},
2161 		/* Get Features */
2162 		[SPDK_NVME_OPC_GET_FEATURES]		= {1, 0, 0, 0, 0, 0, 0, 0},
2163 		/* Async Event Request */
2164 		[SPDK_NVME_OPC_ASYNC_EVENT_REQUEST]	= {1, 0, 0, 0, 0, 0, 0, 0},
2165 		/* Keep Alive */
2166 		[SPDK_NVME_OPC_KEEP_ALIVE]		= {1, 0, 0, 0, 0, 0, 0, 0},
2167 	},
2168 	.io_cmds_supported = {
2169 		/* FLUSH */
2170 		[SPDK_NVME_OPC_FLUSH]			= {1, 1, 0, 0, 0, 0, 0, 0},
2171 		/* WRITE */
2172 		[SPDK_NVME_OPC_WRITE]			= {1, 1, 0, 0, 0, 0, 0, 0},
2173 		/* READ */
2174 		[SPDK_NVME_OPC_READ]			= {1, 0, 0, 0, 0, 0, 0, 0},
2175 		/* WRITE ZEROES */
2176 		[SPDK_NVME_OPC_WRITE_ZEROES]		= {1, 1, 0, 0, 0, 0, 0, 0},
2177 		/* DATASET MANAGEMENT */
2178 		[SPDK_NVME_OPC_DATASET_MANAGEMENT]	= {1, 1, 0, 0, 0, 0, 0, 0},
2179 		/* COMPARE */
2180 		[SPDK_NVME_OPC_COMPARE]			= {1, 0, 0, 0, 0, 0, 0, 0},
2181 	},
2182 };
2183 
2184 static void
2185 nvmf_get_cmds_and_effects_log_page(struct iovec *iovs, int iovcnt,
2186 				   uint64_t offset, uint32_t length)
2187 {
2188 	uint32_t page_size = sizeof(struct spdk_nvme_cmds_and_effect_log_page);
2189 	size_t copy_len = 0;
2190 	struct copy_iovs_ctx copy_ctx;
2191 
2192 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
2193 
2194 	if (offset < page_size) {
2195 		copy_len = spdk_min(page_size - offset, length);
2196 		_copy_buf_to_iovs(&copy_ctx, (char *)(&g_cmds_and_effect_log_page) + offset, copy_len);
2197 	}
2198 }
2199 
2200 static void
2201 nvmf_get_reservation_notification_log_page(struct spdk_nvmf_ctrlr *ctrlr,
2202 		struct iovec *iovs, int iovcnt, uint64_t offset, uint32_t length, uint32_t rae)
2203 {
2204 	uint32_t unit_log_len, avail_log_len, next_pos, copy_len;
2205 	struct spdk_nvmf_reservation_log *log, *log_tmp;
2206 	struct copy_iovs_ctx copy_ctx;
2207 
2208 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
2209 
2210 	unit_log_len = sizeof(struct spdk_nvme_reservation_notification_log);
2211 	/* No available log, return zeroed log pages */
2212 	if (!ctrlr->num_avail_log_pages) {
2213 		return;
2214 	}
2215 
2216 	avail_log_len = ctrlr->num_avail_log_pages * unit_log_len;
2217 	if (offset >= avail_log_len) {
2218 		return;
2219 	}
2220 
2221 	next_pos = 0;
2222 	TAILQ_FOREACH_SAFE(log, &ctrlr->log_head, link, log_tmp) {
2223 		TAILQ_REMOVE(&ctrlr->log_head, log, link);
2224 		ctrlr->num_avail_log_pages--;
2225 
2226 		next_pos += unit_log_len;
2227 		if (next_pos > offset) {
2228 			copy_len = spdk_min(next_pos - offset, length);
2229 			_copy_buf_to_iovs(&copy_ctx, &log->log, copy_len);
2230 			length -= copy_len;
2231 			offset += copy_len;
2232 		}
2233 		free(log);
2234 
2235 		if (length == 0) {
2236 			break;
2237 		}
2238 	}
2239 
2240 	if (!rae) {
2241 		nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_RESERVATION_LOG_AVAIL_MASK_BIT);
2242 	}
2243 	return;
2244 }
2245 
2246 static int
2247 nvmf_ctrlr_get_log_page(struct spdk_nvmf_request *req)
2248 {
2249 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2250 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2251 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2252 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
2253 	uint64_t offset, len;
2254 	uint32_t rae, numdl, numdu;
2255 	uint8_t lid;
2256 
2257 	if (req->data == NULL) {
2258 		SPDK_ERRLOG("get log command with no buffer\n");
2259 		response->status.sct = SPDK_NVME_SCT_GENERIC;
2260 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2261 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2262 	}
2263 
2264 	offset = (uint64_t)cmd->cdw12 | ((uint64_t)cmd->cdw13 << 32);
2265 	if (offset & 3) {
2266 		SPDK_ERRLOG("Invalid log page offset 0x%" PRIx64 "\n", offset);
2267 		response->status.sct = SPDK_NVME_SCT_GENERIC;
2268 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2269 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2270 	}
2271 
2272 	rae = cmd->cdw10_bits.get_log_page.rae;
2273 	numdl = cmd->cdw10_bits.get_log_page.numdl;
2274 	numdu = cmd->cdw11_bits.get_log_page.numdu;
2275 	len = ((numdu << 16) + numdl + (uint64_t)1) * 4;
2276 	if (len > req->length) {
2277 		SPDK_ERRLOG("Get log page: len (%" PRIu64 ") > buf size (%u)\n",
2278 			    len, req->length);
2279 		response->status.sct = SPDK_NVME_SCT_GENERIC;
2280 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2281 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2282 	}
2283 
2284 	lid = cmd->cdw10_bits.get_log_page.lid;
2285 	SPDK_DEBUGLOG(nvmf, "Get log page: LID=0x%02X offset=0x%" PRIx64 " len=0x%" PRIx64 " rae=%u\n",
2286 		      lid, offset, len, rae);
2287 
2288 	if (subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2289 		switch (lid) {
2290 		case SPDK_NVME_LOG_DISCOVERY:
2291 			nvmf_get_discovery_log_page(subsystem->tgt, ctrlr->hostnqn, req->iov, req->iovcnt, offset,
2292 						    len);
2293 			if (!rae) {
2294 				nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_DISCOVERY_LOG_CHANGE_MASK_BIT);
2295 			}
2296 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2297 		default:
2298 			goto invalid_log_page;
2299 		}
2300 	} else {
2301 		switch (lid) {
2302 		case SPDK_NVME_LOG_ERROR:
2303 			nvmf_get_error_log_page(ctrlr, req->iov, req->iovcnt, offset, len, rae);
2304 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2305 		case SPDK_NVME_LOG_HEALTH_INFORMATION:
2306 			/* TODO: actually fill out log page data */
2307 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2308 		case SPDK_NVME_LOG_FIRMWARE_SLOT:
2309 			nvmf_get_firmware_slot_log_page(req->iov, req->iovcnt, offset, len);
2310 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2311 		case SPDK_NVME_LOG_ASYMMETRIC_NAMESPACE_ACCESS:
2312 			if (subsystem->flags.ana_reporting) {
2313 				nvmf_get_ana_log_page(ctrlr, req->iov, req->iovcnt, offset, len, rae);
2314 				return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2315 			} else {
2316 				goto invalid_log_page;
2317 			}
2318 		case SPDK_NVME_LOG_COMMAND_EFFECTS_LOG:
2319 			nvmf_get_cmds_and_effects_log_page(req->iov, req->iovcnt, offset, len);
2320 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2321 		case SPDK_NVME_LOG_CHANGED_NS_LIST:
2322 			nvmf_get_changed_ns_list_log_page(ctrlr, req->iov, req->iovcnt, offset, len, rae);
2323 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2324 		case SPDK_NVME_LOG_RESERVATION_NOTIFICATION:
2325 			nvmf_get_reservation_notification_log_page(ctrlr, req->iov, req->iovcnt, offset, len, rae);
2326 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2327 		default:
2328 			goto invalid_log_page;
2329 		}
2330 	}
2331 
2332 invalid_log_page:
2333 	SPDK_INFOLOG(nvmf, "Unsupported Get Log Page 0x%02X\n", lid);
2334 	response->status.sct = SPDK_NVME_SCT_GENERIC;
2335 	response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2336 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2337 }
2338 
2339 int
2340 spdk_nvmf_ctrlr_identify_ns(struct spdk_nvmf_ctrlr *ctrlr,
2341 			    struct spdk_nvme_cmd *cmd,
2342 			    struct spdk_nvme_cpl *rsp,
2343 			    struct spdk_nvme_ns_data *nsdata)
2344 {
2345 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2346 	struct spdk_nvmf_ns *ns;
2347 	uint32_t max_num_blocks;
2348 	enum spdk_nvme_ana_state ana_state;
2349 
2350 	if (cmd->nsid == 0 || cmd->nsid > subsystem->max_nsid) {
2351 		SPDK_ERRLOG("Identify Namespace for invalid NSID %u\n", cmd->nsid);
2352 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2353 		rsp->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
2354 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2355 	}
2356 
2357 	ns = _nvmf_subsystem_get_ns(subsystem, cmd->nsid);
2358 	if (ns == NULL || ns->bdev == NULL) {
2359 		/*
2360 		 * Inactive namespaces should return a zero filled data structure.
2361 		 * The data buffer is already zeroed by nvmf_ctrlr_process_admin_cmd(),
2362 		 * so we can just return early here.
2363 		 */
2364 		SPDK_DEBUGLOG(nvmf, "Identify Namespace for inactive NSID %u\n", cmd->nsid);
2365 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2366 		rsp->status.sc = SPDK_NVME_SC_SUCCESS;
2367 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2368 	}
2369 
2370 	nvmf_bdev_ctrlr_identify_ns(ns, nsdata, ctrlr->dif_insert_or_strip);
2371 
2372 	/* Due to bug in the Linux kernel NVMe driver we have to set noiob no larger than mdts */
2373 	max_num_blocks = ctrlr->admin_qpair->transport->opts.max_io_size /
2374 			 (1U << nsdata->lbaf[nsdata->flbas.format].lbads);
2375 	if (nsdata->noiob > max_num_blocks) {
2376 		nsdata->noiob = max_num_blocks;
2377 	}
2378 
2379 	if (subsystem->flags.ana_reporting) {
2380 		assert(ns->anagrpid - 1 < subsystem->max_nsid);
2381 		nsdata->anagrpid = ns->anagrpid;
2382 
2383 		ana_state = nvmf_ctrlr_get_ana_state(ctrlr, ns->anagrpid);
2384 		if (ana_state == SPDK_NVME_ANA_INACCESSIBLE_STATE ||
2385 		    ana_state == SPDK_NVME_ANA_PERSISTENT_LOSS_STATE) {
2386 			nsdata->nuse = 0;
2387 		}
2388 	}
2389 
2390 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2391 }
2392 
2393 static void
2394 nvmf_ctrlr_populate_oacs(struct spdk_nvmf_ctrlr *ctrlr,
2395 			 struct spdk_nvme_ctrlr_data *cdata)
2396 {
2397 	cdata->oacs.virtualization_management =
2398 		g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_VIRTUALIZATION_MANAGEMENT].hdlr != NULL;
2399 	cdata->oacs.nvme_mi = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NVME_MI_SEND].hdlr != NULL
2400 			      && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NVME_MI_RECEIVE].hdlr != NULL;
2401 	cdata->oacs.directives = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_DIRECTIVE_SEND].hdlr != NULL
2402 				 && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_DIRECTIVE_RECEIVE].hdlr != NULL;
2403 	cdata->oacs.device_self_test =
2404 		g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_DEVICE_SELF_TEST].hdlr != NULL;
2405 	cdata->oacs.ns_manage = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NS_MANAGEMENT].hdlr != NULL
2406 				&& g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NS_ATTACHMENT].hdlr != NULL;
2407 	cdata->oacs.firmware = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_FIRMWARE_IMAGE_DOWNLOAD].hdlr !=
2408 			       NULL
2409 			       && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_FIRMWARE_COMMIT].hdlr != NULL;
2410 	cdata->oacs.format =
2411 		g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_FORMAT_NVM].hdlr != NULL;
2412 	cdata->oacs.security = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_SECURITY_SEND].hdlr != NULL
2413 			       && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_SECURITY_RECEIVE].hdlr != NULL;
2414 	cdata->oacs.get_lba_status = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_GET_LBA_STATUS].hdlr !=
2415 				     NULL;
2416 }
2417 
2418 int
2419 spdk_nvmf_ctrlr_identify_ctrlr(struct spdk_nvmf_ctrlr *ctrlr, struct spdk_nvme_ctrlr_data *cdata)
2420 {
2421 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2422 	struct spdk_nvmf_transport *transport = ctrlr->admin_qpair->transport;
2423 
2424 	/*
2425 	 * Common fields for discovery and NVM subsystems
2426 	 */
2427 	spdk_strcpy_pad(cdata->fr, FW_VERSION, sizeof(cdata->fr), ' ');
2428 	assert((transport->opts.max_io_size % 4096) == 0);
2429 	cdata->mdts = spdk_u32log2(transport->opts.max_io_size / 4096);
2430 	cdata->cntlid = ctrlr->cntlid;
2431 	cdata->ver = ctrlr->vcprop.vs;
2432 	cdata->aerl = NVMF_MAX_ASYNC_EVENTS - 1;
2433 	cdata->lpa.edlp = 1;
2434 	cdata->elpe = 127;
2435 	cdata->maxcmd = transport->opts.max_queue_depth;
2436 	cdata->sgls = ctrlr->cdata.sgls;
2437 	cdata->fuses.compare_and_write = 1;
2438 	cdata->acwu = 1;
2439 	if (subsystem->flags.ana_reporting) {
2440 		cdata->mnan = subsystem->max_nsid;
2441 	}
2442 	spdk_strcpy_pad(cdata->subnqn, subsystem->subnqn, sizeof(cdata->subnqn), '\0');
2443 
2444 	SPDK_DEBUGLOG(nvmf, "ctrlr data: maxcmd 0x%x\n", cdata->maxcmd);
2445 	SPDK_DEBUGLOG(nvmf, "sgls data: 0x%x\n", from_le32(&cdata->sgls));
2446 
2447 
2448 	if (subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2449 		/*
2450 		 * NVM Discovery subsystem fields
2451 		 */
2452 		cdata->oaes.discovery_log_change_notices = 1;
2453 	} else {
2454 		/*
2455 		 * NVM subsystem fields (reserved for discovery subsystems)
2456 		 */
2457 		spdk_strcpy_pad(cdata->mn, spdk_nvmf_subsystem_get_mn(subsystem), sizeof(cdata->mn), ' ');
2458 		spdk_strcpy_pad(cdata->sn, spdk_nvmf_subsystem_get_sn(subsystem), sizeof(cdata->sn), ' ');
2459 		cdata->kas = ctrlr->cdata.kas;
2460 
2461 		cdata->rab = 6;
2462 		cdata->cmic.multi_port = 1;
2463 		cdata->cmic.multi_ctrlr = 1;
2464 		if (subsystem->flags.ana_reporting) {
2465 			/* Asymmetric Namespace Access Reporting is supported. */
2466 			cdata->cmic.ana_reporting = 1;
2467 		}
2468 		cdata->oaes.ns_attribute_notices = 1;
2469 		if (subsystem->flags.ana_reporting) {
2470 			cdata->oaes.ana_change_notices = 1;
2471 		}
2472 		cdata->ctratt.host_id_exhid_supported = 1;
2473 		/* TODO: Concurrent execution of multiple abort commands. */
2474 		cdata->acl = 0;
2475 		cdata->frmw.slot1_ro = 1;
2476 		cdata->frmw.num_slots = 1;
2477 
2478 		cdata->lpa.celp = 1; /* Command Effects log page supported */
2479 
2480 		cdata->sqes.min = 6;
2481 		cdata->sqes.max = 6;
2482 		cdata->cqes.min = 4;
2483 		cdata->cqes.max = 4;
2484 		cdata->nn = subsystem->max_nsid;
2485 		cdata->vwc.present = 1;
2486 		cdata->vwc.flush_broadcast = SPDK_NVME_FLUSH_BROADCAST_NOT_SUPPORTED;
2487 
2488 		cdata->nvmf_specific = ctrlr->cdata.nvmf_specific;
2489 
2490 		cdata->oncs.dsm = nvmf_ctrlr_dsm_supported(ctrlr);
2491 		cdata->oncs.write_zeroes = nvmf_ctrlr_write_zeroes_supported(ctrlr);
2492 		cdata->oncs.reservations = ctrlr->cdata.oncs.reservations;
2493 		if (subsystem->flags.ana_reporting) {
2494 			cdata->anatt = ANA_TRANSITION_TIME_IN_SEC;
2495 			/* ANA Change state is not used, and ANA Persistent Loss state
2496 			 * is not supported for now.
2497 			 */
2498 			cdata->anacap.ana_optimized_state = 1;
2499 			cdata->anacap.ana_non_optimized_state = 1;
2500 			cdata->anacap.ana_inaccessible_state = 1;
2501 			/* ANAGRPID does not change while namespace is attached to controller */
2502 			cdata->anacap.no_change_anagrpid = 1;
2503 			cdata->anagrpmax = subsystem->max_nsid;
2504 			cdata->nanagrpid = subsystem->max_nsid;
2505 		}
2506 
2507 		nvmf_ctrlr_populate_oacs(ctrlr, cdata);
2508 
2509 		assert(subsystem->tgt != NULL);
2510 		cdata->crdt[0] = subsystem->tgt->crdt[0];
2511 		cdata->crdt[1] = subsystem->tgt->crdt[1];
2512 		cdata->crdt[2] = subsystem->tgt->crdt[2];
2513 
2514 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: ioccsz 0x%x\n",
2515 			      cdata->nvmf_specific.ioccsz);
2516 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: iorcsz 0x%x\n",
2517 			      cdata->nvmf_specific.iorcsz);
2518 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: icdoff 0x%x\n",
2519 			      cdata->nvmf_specific.icdoff);
2520 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: ctrattr 0x%x\n",
2521 			      *(uint8_t *)&cdata->nvmf_specific.ctrattr);
2522 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: msdbd 0x%x\n",
2523 			      cdata->nvmf_specific.msdbd);
2524 	}
2525 
2526 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2527 }
2528 
2529 static int
2530 nvmf_ctrlr_identify_active_ns_list(struct spdk_nvmf_subsystem *subsystem,
2531 				   struct spdk_nvme_cmd *cmd,
2532 				   struct spdk_nvme_cpl *rsp,
2533 				   struct spdk_nvme_ns_list *ns_list)
2534 {
2535 	struct spdk_nvmf_ns *ns;
2536 	uint32_t count = 0;
2537 
2538 	if (cmd->nsid >= 0xfffffffeUL) {
2539 		SPDK_ERRLOG("Identify Active Namespace List with invalid NSID %u\n", cmd->nsid);
2540 		rsp->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
2541 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2542 	}
2543 
2544 	memset(ns_list, 0, sizeof(*ns_list));
2545 
2546 	for (ns = spdk_nvmf_subsystem_get_first_ns(subsystem); ns != NULL;
2547 	     ns = spdk_nvmf_subsystem_get_next_ns(subsystem, ns)) {
2548 		if (ns->opts.nsid <= cmd->nsid) {
2549 			continue;
2550 		}
2551 
2552 		ns_list->ns_list[count++] = ns->opts.nsid;
2553 		if (count == SPDK_COUNTOF(ns_list->ns_list)) {
2554 			break;
2555 		}
2556 	}
2557 
2558 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2559 }
2560 
2561 static void
2562 _add_ns_id_desc(void **buf_ptr, size_t *buf_remain,
2563 		enum spdk_nvme_nidt type,
2564 		const void *data, size_t data_size)
2565 {
2566 	struct spdk_nvme_ns_id_desc *desc;
2567 	size_t desc_size = sizeof(*desc) + data_size;
2568 
2569 	/*
2570 	 * These should never fail in practice, since all valid NS ID descriptors
2571 	 * should be defined so that they fit in the available 4096-byte buffer.
2572 	 */
2573 	assert(data_size > 0);
2574 	assert(data_size <= UINT8_MAX);
2575 	assert(desc_size < *buf_remain);
2576 	if (data_size == 0 || data_size > UINT8_MAX || desc_size > *buf_remain) {
2577 		return;
2578 	}
2579 
2580 	desc = *buf_ptr;
2581 	desc->nidt = type;
2582 	desc->nidl = data_size;
2583 	memcpy(desc->nid, data, data_size);
2584 
2585 	*buf_ptr += desc_size;
2586 	*buf_remain -= desc_size;
2587 }
2588 
2589 static int
2590 nvmf_ctrlr_identify_ns_id_descriptor_list(
2591 	struct spdk_nvmf_subsystem *subsystem,
2592 	struct spdk_nvme_cmd *cmd,
2593 	struct spdk_nvme_cpl *rsp,
2594 	void *id_desc_list, size_t id_desc_list_size)
2595 {
2596 	struct spdk_nvmf_ns *ns;
2597 	size_t buf_remain = id_desc_list_size;
2598 	void *buf_ptr = id_desc_list;
2599 
2600 	ns = _nvmf_subsystem_get_ns(subsystem, cmd->nsid);
2601 	if (ns == NULL || ns->bdev == NULL) {
2602 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2603 		rsp->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
2604 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2605 	}
2606 
2607 #define ADD_ID_DESC(type, data, size) \
2608 	do { \
2609 		if (!spdk_mem_all_zero(data, size)) { \
2610 			_add_ns_id_desc(&buf_ptr, &buf_remain, type, data, size); \
2611 		} \
2612 	} while (0)
2613 
2614 	ADD_ID_DESC(SPDK_NVME_NIDT_EUI64, ns->opts.eui64, sizeof(ns->opts.eui64));
2615 	ADD_ID_DESC(SPDK_NVME_NIDT_NGUID, ns->opts.nguid, sizeof(ns->opts.nguid));
2616 	ADD_ID_DESC(SPDK_NVME_NIDT_UUID, &ns->opts.uuid, sizeof(ns->opts.uuid));
2617 
2618 	/*
2619 	 * The list is automatically 0-terminated because controller to host buffers in
2620 	 * admin commands always get zeroed in nvmf_ctrlr_process_admin_cmd().
2621 	 */
2622 
2623 #undef ADD_ID_DESC
2624 
2625 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2626 }
2627 
2628 static int
2629 nvmf_ctrlr_identify(struct spdk_nvmf_request *req)
2630 {
2631 	uint8_t cns;
2632 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2633 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2634 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
2635 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2636 
2637 	if (req->data == NULL || req->length < 4096) {
2638 		SPDK_ERRLOG("identify command with invalid buffer\n");
2639 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2640 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2641 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2642 	}
2643 
2644 	cns = cmd->cdw10_bits.identify.cns;
2645 
2646 	if (subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY &&
2647 	    cns != SPDK_NVME_IDENTIFY_CTRLR) {
2648 		/* Discovery controllers only support Identify Controller */
2649 		goto invalid_cns;
2650 	}
2651 
2652 	switch (cns) {
2653 	case SPDK_NVME_IDENTIFY_NS:
2654 		return spdk_nvmf_ctrlr_identify_ns(ctrlr, cmd, rsp, req->data);
2655 	case SPDK_NVME_IDENTIFY_CTRLR:
2656 		return spdk_nvmf_ctrlr_identify_ctrlr(ctrlr, req->data);
2657 	case SPDK_NVME_IDENTIFY_ACTIVE_NS_LIST:
2658 		return nvmf_ctrlr_identify_active_ns_list(subsystem, cmd, rsp, req->data);
2659 	case SPDK_NVME_IDENTIFY_NS_ID_DESCRIPTOR_LIST:
2660 		return nvmf_ctrlr_identify_ns_id_descriptor_list(subsystem, cmd, rsp, req->data, req->length);
2661 	default:
2662 		goto invalid_cns;
2663 	}
2664 
2665 invalid_cns:
2666 	SPDK_INFOLOG(nvmf, "Identify command with unsupported CNS 0x%02x\n", cns);
2667 	rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2668 	rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2669 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2670 }
2671 
2672 static bool
2673 nvmf_qpair_abort_aer(struct spdk_nvmf_qpair *qpair, uint16_t cid)
2674 {
2675 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
2676 	struct spdk_nvmf_request *req;
2677 	int i;
2678 
2679 	if (!nvmf_qpair_is_admin_queue(qpair)) {
2680 		return false;
2681 	}
2682 
2683 	for (i = 0; i < ctrlr->nr_aer_reqs; i++) {
2684 		if (ctrlr->aer_req[i]->cmd->nvme_cmd.cid == cid) {
2685 			SPDK_DEBUGLOG(nvmf, "Aborting AER request\n");
2686 			req = ctrlr->aer_req[i];
2687 			ctrlr->aer_req[i] = NULL;
2688 			ctrlr->nr_aer_reqs--;
2689 
2690 			/* Move the last req to the aborting position for making aer_reqs
2691 			 * in continuous
2692 			 */
2693 			if (i < ctrlr->nr_aer_reqs) {
2694 				ctrlr->aer_req[i] = ctrlr->aer_req[ctrlr->nr_aer_reqs];
2695 				ctrlr->aer_req[ctrlr->nr_aer_reqs] = NULL;
2696 			}
2697 
2698 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
2699 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
2700 			_nvmf_request_complete(req);
2701 			return true;
2702 		}
2703 	}
2704 
2705 	return false;
2706 }
2707 
2708 static void
2709 nvmf_qpair_abort_request(struct spdk_nvmf_qpair *qpair, struct spdk_nvmf_request *req)
2710 {
2711 	uint16_t cid = req->cmd->nvme_cmd.cdw10_bits.abort.cid;
2712 
2713 	if (nvmf_qpair_abort_aer(qpair, cid)) {
2714 		SPDK_DEBUGLOG(nvmf, "abort ctrlr=%p sqid=%u cid=%u successful\n",
2715 			      qpair->ctrlr, qpair->qid, cid);
2716 		req->rsp->nvme_cpl.cdw0 &= ~1U; /* Command successfully aborted */
2717 
2718 		spdk_nvmf_request_complete(req);
2719 		return;
2720 	}
2721 
2722 	nvmf_transport_qpair_abort_request(qpair, req);
2723 }
2724 
2725 static void
2726 nvmf_ctrlr_abort_done(struct spdk_io_channel_iter *i, int status)
2727 {
2728 	struct spdk_nvmf_request *req = spdk_io_channel_iter_get_ctx(i);
2729 
2730 	if (status == 0) {
2731 		/* There was no qpair whose ID matches SQID of the abort command.
2732 		 * Hence call _nvmf_request_complete() here.
2733 		 */
2734 		_nvmf_request_complete(req);
2735 	}
2736 }
2737 
2738 static void
2739 nvmf_ctrlr_abort_on_pg(struct spdk_io_channel_iter *i)
2740 {
2741 	struct spdk_nvmf_request *req = spdk_io_channel_iter_get_ctx(i);
2742 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
2743 	struct spdk_nvmf_poll_group *group = spdk_io_channel_get_ctx(ch);
2744 	uint16_t sqid = req->cmd->nvme_cmd.cdw10_bits.abort.sqid;
2745 	struct spdk_nvmf_qpair *qpair;
2746 
2747 	TAILQ_FOREACH(qpair, &group->qpairs, link) {
2748 		if (qpair->ctrlr == req->qpair->ctrlr && qpair->qid == sqid) {
2749 			/* Found the qpair */
2750 
2751 			nvmf_qpair_abort_request(qpair, req);
2752 
2753 			/* Return -1 for the status so the iteration across threads stops. */
2754 			spdk_for_each_channel_continue(i, -1);
2755 			return;
2756 		}
2757 	}
2758 
2759 	spdk_for_each_channel_continue(i, 0);
2760 }
2761 
2762 static int
2763 nvmf_ctrlr_abort(struct spdk_nvmf_request *req)
2764 {
2765 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
2766 
2767 	rsp->cdw0 = 1U; /* Command not aborted */
2768 	rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2769 	rsp->status.sc = SPDK_NVME_SC_SUCCESS;
2770 
2771 	/* Send a message to each poll group, searching for this ctrlr, sqid, and command. */
2772 	spdk_for_each_channel(req->qpair->ctrlr->subsys->tgt,
2773 			      nvmf_ctrlr_abort_on_pg,
2774 			      req,
2775 			      nvmf_ctrlr_abort_done
2776 			     );
2777 
2778 	return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
2779 }
2780 
2781 int
2782 nvmf_ctrlr_abort_request(struct spdk_nvmf_request *req)
2783 {
2784 	struct spdk_nvmf_request *req_to_abort = req->req_to_abort;
2785 	struct spdk_bdev *bdev;
2786 	struct spdk_bdev_desc *desc;
2787 	struct spdk_io_channel *ch;
2788 	int rc;
2789 
2790 	assert(req_to_abort != NULL);
2791 
2792 	if (g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_ABORT].hdlr &&
2793 	    nvmf_qpair_is_admin_queue(req_to_abort->qpair)) {
2794 		return g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_ABORT].hdlr(req);
2795 	}
2796 
2797 	rc = spdk_nvmf_request_get_bdev(req_to_abort->cmd->nvme_cmd.nsid, req_to_abort,
2798 					&bdev, &desc, &ch);
2799 	if (rc != 0) {
2800 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2801 	}
2802 
2803 	return spdk_nvmf_bdev_ctrlr_abort_cmd(bdev, desc, ch, req, req_to_abort);
2804 }
2805 
2806 static int
2807 get_features_generic(struct spdk_nvmf_request *req, uint32_t cdw0)
2808 {
2809 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
2810 
2811 	rsp->cdw0 = cdw0;
2812 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2813 }
2814 
2815 /* we have to use the typedef in the function declaration to appease astyle. */
2816 typedef enum spdk_nvme_path_status_code spdk_nvme_path_status_code_t;
2817 
2818 static spdk_nvme_path_status_code_t
2819 _nvme_ana_state_to_path_status(enum spdk_nvme_ana_state ana_state)
2820 {
2821 	switch (ana_state) {
2822 	case SPDK_NVME_ANA_INACCESSIBLE_STATE:
2823 		return SPDK_NVME_SC_ASYMMETRIC_ACCESS_INACCESSIBLE;
2824 	case SPDK_NVME_ANA_PERSISTENT_LOSS_STATE:
2825 		return SPDK_NVME_SC_ASYMMETRIC_ACCESS_PERSISTENT_LOSS;
2826 	case SPDK_NVME_ANA_CHANGE_STATE:
2827 		return SPDK_NVME_SC_ASYMMETRIC_ACCESS_TRANSITION;
2828 	default:
2829 		return SPDK_NVME_SC_INTERNAL_PATH_ERROR;
2830 	}
2831 }
2832 
2833 static int
2834 nvmf_ctrlr_get_features(struct spdk_nvmf_request *req)
2835 {
2836 	uint8_t feature;
2837 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2838 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2839 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
2840 	enum spdk_nvme_ana_state ana_state;
2841 
2842 	feature = cmd->cdw10_bits.get_features.fid;
2843 
2844 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2845 		/*
2846 		 * Features supported by Discovery controller
2847 		 */
2848 		switch (feature) {
2849 		case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
2850 			return get_features_generic(req, ctrlr->feat.keep_alive_timer.raw);
2851 		case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
2852 			return get_features_generic(req, ctrlr->feat.async_event_configuration.raw);
2853 		default:
2854 			SPDK_INFOLOG(nvmf, "Get Features command with unsupported feature ID 0x%02x\n", feature);
2855 			response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2856 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2857 		}
2858 	}
2859 	/*
2860 	 * Process Get Features command for non-discovery controller
2861 	 */
2862 	ana_state = nvmf_ctrlr_get_ana_state_from_nsid(ctrlr, cmd->nsid);
2863 	switch (ana_state) {
2864 	case SPDK_NVME_ANA_INACCESSIBLE_STATE:
2865 	case SPDK_NVME_ANA_PERSISTENT_LOSS_STATE:
2866 	case SPDK_NVME_ANA_CHANGE_STATE:
2867 		switch (feature) {
2868 		case SPDK_NVME_FEAT_ERROR_RECOVERY:
2869 		case SPDK_NVME_FEAT_WRITE_ATOMICITY:
2870 		case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
2871 		case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
2872 			response->status.sct = SPDK_NVME_SCT_PATH;
2873 			response->status.sc = _nvme_ana_state_to_path_status(ana_state);
2874 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2875 		default:
2876 			break;
2877 		}
2878 		break;
2879 	default:
2880 		break;
2881 	}
2882 
2883 	switch (feature) {
2884 	case SPDK_NVME_FEAT_ARBITRATION:
2885 		return get_features_generic(req, ctrlr->feat.arbitration.raw);
2886 	case SPDK_NVME_FEAT_POWER_MANAGEMENT:
2887 		return get_features_generic(req, ctrlr->feat.power_management.raw);
2888 	case SPDK_NVME_FEAT_TEMPERATURE_THRESHOLD:
2889 		return nvmf_ctrlr_get_features_temperature_threshold(req);
2890 	case SPDK_NVME_FEAT_ERROR_RECOVERY:
2891 		return get_features_generic(req, ctrlr->feat.error_recovery.raw);
2892 	case SPDK_NVME_FEAT_VOLATILE_WRITE_CACHE:
2893 		return get_features_generic(req, ctrlr->feat.volatile_write_cache.raw);
2894 	case SPDK_NVME_FEAT_NUMBER_OF_QUEUES:
2895 		return get_features_generic(req, ctrlr->feat.number_of_queues.raw);
2896 	case SPDK_NVME_FEAT_INTERRUPT_COALESCING:
2897 		return get_features_generic(req, ctrlr->feat.interrupt_coalescing.raw);
2898 	case SPDK_NVME_FEAT_INTERRUPT_VECTOR_CONFIGURATION:
2899 		return nvmf_ctrlr_get_features_interrupt_vector_configuration(req);
2900 	case SPDK_NVME_FEAT_WRITE_ATOMICITY:
2901 		return get_features_generic(req, ctrlr->feat.write_atomicity.raw);
2902 	case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
2903 		return get_features_generic(req, ctrlr->feat.async_event_configuration.raw);
2904 	case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
2905 		return get_features_generic(req, ctrlr->feat.keep_alive_timer.raw);
2906 	case SPDK_NVME_FEAT_HOST_IDENTIFIER:
2907 		return nvmf_ctrlr_get_features_host_identifier(req);
2908 	case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
2909 		return nvmf_ctrlr_get_features_reservation_notification_mask(req);
2910 	case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
2911 		return nvmf_ctrlr_get_features_reservation_persistence(req);
2912 	default:
2913 		SPDK_INFOLOG(nvmf, "Get Features command with unsupported feature ID 0x%02x\n", feature);
2914 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2915 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2916 	}
2917 }
2918 
2919 static int
2920 nvmf_ctrlr_set_features(struct spdk_nvmf_request *req)
2921 {
2922 	uint8_t feature, save;
2923 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2924 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2925 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
2926 	enum spdk_nvme_ana_state ana_state;
2927 	/*
2928 	 * Features are not saveable by the controller as indicated by
2929 	 * ONCS field of the Identify Controller data.
2930 	 * */
2931 	save = cmd->cdw10_bits.set_features.sv;
2932 	if (save) {
2933 		response->status.sc = SPDK_NVME_SC_FEATURE_ID_NOT_SAVEABLE;
2934 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
2935 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2936 	}
2937 
2938 	feature = cmd->cdw10_bits.set_features.fid;
2939 
2940 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2941 		/*
2942 		 * Features supported by Discovery controller
2943 		 */
2944 		switch (feature) {
2945 		case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
2946 			return nvmf_ctrlr_set_features_keep_alive_timer(req);
2947 		case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
2948 			return nvmf_ctrlr_set_features_async_event_configuration(req);
2949 		default:
2950 			SPDK_INFOLOG(nvmf, "Set Features command with unsupported feature ID 0x%02x\n", feature);
2951 			response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2952 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2953 		}
2954 	}
2955 	/*
2956 	 * Process Set Features command for non-discovery controller
2957 	 */
2958 	ana_state = nvmf_ctrlr_get_ana_state_from_nsid(ctrlr, cmd->nsid);
2959 	switch (ana_state) {
2960 	case SPDK_NVME_ANA_INACCESSIBLE_STATE:
2961 	case SPDK_NVME_ANA_CHANGE_STATE:
2962 		if (cmd->nsid == SPDK_NVME_GLOBAL_NS_TAG) {
2963 			response->status.sct = SPDK_NVME_SCT_PATH;
2964 			response->status.sc = _nvme_ana_state_to_path_status(ana_state);
2965 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2966 		} else {
2967 			switch (feature) {
2968 			case SPDK_NVME_FEAT_ERROR_RECOVERY:
2969 			case SPDK_NVME_FEAT_WRITE_ATOMICITY:
2970 			case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
2971 			case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
2972 				response->status.sct = SPDK_NVME_SCT_PATH;
2973 				response->status.sc = _nvme_ana_state_to_path_status(ana_state);
2974 				return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2975 			default:
2976 				break;
2977 			}
2978 		}
2979 		break;
2980 	case SPDK_NVME_ANA_PERSISTENT_LOSS_STATE:
2981 		response->status.sct = SPDK_NVME_SCT_PATH;
2982 		response->status.sc = SPDK_NVME_SC_ASYMMETRIC_ACCESS_PERSISTENT_LOSS;
2983 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2984 	default:
2985 		break;
2986 	}
2987 
2988 	switch (feature) {
2989 	case SPDK_NVME_FEAT_ARBITRATION:
2990 		return nvmf_ctrlr_set_features_arbitration(req);
2991 	case SPDK_NVME_FEAT_POWER_MANAGEMENT:
2992 		return nvmf_ctrlr_set_features_power_management(req);
2993 	case SPDK_NVME_FEAT_TEMPERATURE_THRESHOLD:
2994 		return nvmf_ctrlr_set_features_temperature_threshold(req);
2995 	case SPDK_NVME_FEAT_ERROR_RECOVERY:
2996 		return nvmf_ctrlr_set_features_error_recovery(req);
2997 	case SPDK_NVME_FEAT_VOLATILE_WRITE_CACHE:
2998 		return nvmf_ctrlr_set_features_volatile_write_cache(req);
2999 	case SPDK_NVME_FEAT_NUMBER_OF_QUEUES:
3000 		return nvmf_ctrlr_set_features_number_of_queues(req);
3001 	case SPDK_NVME_FEAT_INTERRUPT_COALESCING:
3002 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
3003 		response->status.sc = SPDK_NVME_SC_FEATURE_NOT_CHANGEABLE;
3004 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3005 	case SPDK_NVME_FEAT_WRITE_ATOMICITY:
3006 		return nvmf_ctrlr_set_features_write_atomicity(req);
3007 	case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
3008 		return nvmf_ctrlr_set_features_async_event_configuration(req);
3009 	case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
3010 		return nvmf_ctrlr_set_features_keep_alive_timer(req);
3011 	case SPDK_NVME_FEAT_HOST_IDENTIFIER:
3012 		return nvmf_ctrlr_set_features_host_identifier(req);
3013 	case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
3014 		return nvmf_ctrlr_set_features_reservation_notification_mask(req);
3015 	case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
3016 		return nvmf_ctrlr_set_features_reservation_persistence(req);
3017 	case SPDK_NVME_FEAT_HOST_BEHAVIOR_SUPPORT:
3018 		return nvmf_ctrlr_set_features_host_behavior_support(req);
3019 	default:
3020 		SPDK_INFOLOG(nvmf, "Set Features command with unsupported feature ID 0x%02x\n", feature);
3021 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
3022 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3023 	}
3024 }
3025 
3026 static int
3027 nvmf_ctrlr_keep_alive(struct spdk_nvmf_request *req)
3028 {
3029 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
3030 
3031 	SPDK_DEBUGLOG(nvmf, "Keep Alive\n");
3032 	/*
3033 	 * To handle keep alive just clear or reset the
3034 	 * ctrlr based keep alive duration counter.
3035 	 * When added, a separate timer based process
3036 	 * will monitor if the time since last recorded
3037 	 * keep alive has exceeded the max duration and
3038 	 * take appropriate action.
3039 	 */
3040 	ctrlr->last_keep_alive_tick = spdk_get_ticks();
3041 
3042 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3043 }
3044 
3045 int
3046 nvmf_ctrlr_process_admin_cmd(struct spdk_nvmf_request *req)
3047 {
3048 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
3049 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3050 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
3051 	int rc;
3052 
3053 	if (ctrlr == NULL) {
3054 		SPDK_ERRLOG("Admin command sent before CONNECT\n");
3055 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3056 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3057 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3058 	}
3059 
3060 	if (cmd->fuse != 0) {
3061 		/* Fused admin commands are not supported. */
3062 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3063 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
3064 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3065 	}
3066 
3067 	if (ctrlr->vcprop.cc.bits.en != 1) {
3068 		SPDK_ERRLOG("Admin command sent to disabled controller\n");
3069 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3070 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3071 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3072 	}
3073 
3074 	if (req->data && spdk_nvme_opc_get_data_transfer(cmd->opc) == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
3075 		memset(req->data, 0, req->length);
3076 	}
3077 
3078 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
3079 		/* Discovery controllers only support these admin OPS. */
3080 		switch (cmd->opc) {
3081 		case SPDK_NVME_OPC_IDENTIFY:
3082 		case SPDK_NVME_OPC_GET_LOG_PAGE:
3083 		case SPDK_NVME_OPC_KEEP_ALIVE:
3084 		case SPDK_NVME_OPC_SET_FEATURES:
3085 		case SPDK_NVME_OPC_GET_FEATURES:
3086 		case SPDK_NVME_OPC_ASYNC_EVENT_REQUEST:
3087 			break;
3088 		default:
3089 			goto invalid_opcode;
3090 		}
3091 	}
3092 
3093 	/* Call a custom adm cmd handler if set. Aborts are handled in a different path (see nvmf_passthru_admin_cmd) */
3094 	if (g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].hdlr && cmd->opc != SPDK_NVME_OPC_ABORT) {
3095 		rc = g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].hdlr(req);
3096 		if (rc >= SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
3097 			/* The handler took care of this commmand */
3098 			return rc;
3099 		}
3100 	}
3101 
3102 	switch (cmd->opc) {
3103 	case SPDK_NVME_OPC_GET_LOG_PAGE:
3104 		return nvmf_ctrlr_get_log_page(req);
3105 	case SPDK_NVME_OPC_IDENTIFY:
3106 		return nvmf_ctrlr_identify(req);
3107 	case SPDK_NVME_OPC_ABORT:
3108 		return nvmf_ctrlr_abort(req);
3109 	case SPDK_NVME_OPC_GET_FEATURES:
3110 		return nvmf_ctrlr_get_features(req);
3111 	case SPDK_NVME_OPC_SET_FEATURES:
3112 		return nvmf_ctrlr_set_features(req);
3113 	case SPDK_NVME_OPC_ASYNC_EVENT_REQUEST:
3114 		return nvmf_ctrlr_async_event_request(req);
3115 	case SPDK_NVME_OPC_KEEP_ALIVE:
3116 		return nvmf_ctrlr_keep_alive(req);
3117 
3118 	case SPDK_NVME_OPC_CREATE_IO_SQ:
3119 	case SPDK_NVME_OPC_CREATE_IO_CQ:
3120 	case SPDK_NVME_OPC_DELETE_IO_SQ:
3121 	case SPDK_NVME_OPC_DELETE_IO_CQ:
3122 		/* Create and Delete I/O CQ/SQ not allowed in NVMe-oF */
3123 		goto invalid_opcode;
3124 
3125 	default:
3126 		goto invalid_opcode;
3127 	}
3128 
3129 invalid_opcode:
3130 	SPDK_INFOLOG(nvmf, "Unsupported admin opcode 0x%x\n", cmd->opc);
3131 	response->status.sct = SPDK_NVME_SCT_GENERIC;
3132 	response->status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3133 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3134 }
3135 
3136 static int
3137 nvmf_ctrlr_process_fabrics_cmd(struct spdk_nvmf_request *req)
3138 {
3139 	struct spdk_nvmf_qpair *qpair = req->qpair;
3140 	struct spdk_nvmf_capsule_cmd *cap_hdr;
3141 
3142 	cap_hdr = &req->cmd->nvmf_cmd;
3143 
3144 	if (qpair->ctrlr == NULL) {
3145 		/* No ctrlr established yet; the only valid command is Connect */
3146 		if (cap_hdr->fctype == SPDK_NVMF_FABRIC_COMMAND_CONNECT) {
3147 			return nvmf_ctrlr_cmd_connect(req);
3148 		} else {
3149 			SPDK_DEBUGLOG(nvmf, "Got fctype 0x%x, expected Connect\n",
3150 				      cap_hdr->fctype);
3151 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3152 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3153 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3154 		}
3155 	} else if (nvmf_qpair_is_admin_queue(qpair)) {
3156 		/*
3157 		 * Controller session is established, and this is an admin queue.
3158 		 * Disallow Connect and allow other fabrics commands.
3159 		 */
3160 		switch (cap_hdr->fctype) {
3161 		case SPDK_NVMF_FABRIC_COMMAND_PROPERTY_SET:
3162 			return nvmf_property_set(req);
3163 		case SPDK_NVMF_FABRIC_COMMAND_PROPERTY_GET:
3164 			return nvmf_property_get(req);
3165 		default:
3166 			SPDK_DEBUGLOG(nvmf, "unknown fctype 0x%02x\n",
3167 				      cap_hdr->fctype);
3168 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3169 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3170 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3171 		}
3172 	} else {
3173 		/* Controller session is established, and this is an I/O queue */
3174 		/* For now, no I/O-specific Fabrics commands are implemented (other than Connect) */
3175 		SPDK_DEBUGLOG(nvmf, "Unexpected I/O fctype 0x%x\n", cap_hdr->fctype);
3176 		req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3177 		req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3178 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3179 	}
3180 }
3181 
3182 static inline void
3183 nvmf_ctrlr_queue_pending_async_event(struct spdk_nvmf_ctrlr *ctrlr,
3184 				     union spdk_nvme_async_event_completion *event)
3185 {
3186 	struct spdk_nvmf_async_event_completion *nvmf_event;
3187 
3188 	nvmf_event = calloc(1, sizeof(*nvmf_event));
3189 	if (!nvmf_event) {
3190 		SPDK_ERRLOG("Alloc nvmf event failed, ignore the event\n");
3191 		return;
3192 	}
3193 	nvmf_event->event.raw = event->raw;
3194 	STAILQ_INSERT_TAIL(&ctrlr->async_events, nvmf_event, link);
3195 }
3196 
3197 static inline int
3198 nvmf_ctrlr_async_event_notification(struct spdk_nvmf_ctrlr *ctrlr,
3199 				    union spdk_nvme_async_event_completion *event)
3200 {
3201 	struct spdk_nvmf_request *req;
3202 	struct spdk_nvme_cpl *rsp;
3203 
3204 	/* If there is no outstanding AER request, queue the event.  Then
3205 	 * if an AER is later submitted, this event can be sent as a
3206 	 * response.
3207 	 */
3208 	if (ctrlr->nr_aer_reqs == 0) {
3209 		nvmf_ctrlr_queue_pending_async_event(ctrlr, event);
3210 		return 0;
3211 	}
3212 
3213 	req = ctrlr->aer_req[--ctrlr->nr_aer_reqs];
3214 	rsp = &req->rsp->nvme_cpl;
3215 
3216 	rsp->cdw0 = event->raw;
3217 
3218 	_nvmf_request_complete(req);
3219 	ctrlr->aer_req[ctrlr->nr_aer_reqs] = NULL;
3220 
3221 	return 0;
3222 }
3223 
3224 int
3225 nvmf_ctrlr_async_event_ns_notice(struct spdk_nvmf_ctrlr *ctrlr)
3226 {
3227 	union spdk_nvme_async_event_completion event = {0};
3228 
3229 	/* Users may disable the event notification */
3230 	if (!ctrlr->feat.async_event_configuration.bits.ns_attr_notice) {
3231 		return 0;
3232 	}
3233 
3234 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_NS_ATTR_CHANGE_MASK_BIT)) {
3235 		return 0;
3236 	}
3237 
3238 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_NOTICE;
3239 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_NS_ATTR_CHANGED;
3240 	event.bits.log_page_identifier = SPDK_NVME_LOG_CHANGED_NS_LIST;
3241 
3242 	return nvmf_ctrlr_async_event_notification(ctrlr, &event);
3243 }
3244 
3245 int
3246 nvmf_ctrlr_async_event_ana_change_notice(struct spdk_nvmf_ctrlr *ctrlr)
3247 {
3248 	union spdk_nvme_async_event_completion event = {0};
3249 
3250 	/* Users may disable the event notification */
3251 	if (!ctrlr->feat.async_event_configuration.bits.ana_change_notice) {
3252 		return 0;
3253 	}
3254 
3255 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_ANA_CHANGE_MASK_BIT)) {
3256 		return 0;
3257 	}
3258 
3259 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_NOTICE;
3260 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_ANA_CHANGE;
3261 	event.bits.log_page_identifier = SPDK_NVME_LOG_ASYMMETRIC_NAMESPACE_ACCESS;
3262 
3263 	return nvmf_ctrlr_async_event_notification(ctrlr, &event);
3264 }
3265 
3266 void
3267 nvmf_ctrlr_async_event_reservation_notification(struct spdk_nvmf_ctrlr *ctrlr)
3268 {
3269 	union spdk_nvme_async_event_completion event = {0};
3270 
3271 	if (!ctrlr->num_avail_log_pages) {
3272 		return;
3273 	}
3274 
3275 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_RESERVATION_LOG_AVAIL_MASK_BIT)) {
3276 		return;
3277 	}
3278 
3279 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_IO;
3280 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_RESERVATION_LOG_AVAIL;
3281 	event.bits.log_page_identifier = SPDK_NVME_LOG_RESERVATION_NOTIFICATION;
3282 
3283 	nvmf_ctrlr_async_event_notification(ctrlr, &event);
3284 }
3285 
3286 int
3287 nvmf_ctrlr_async_event_discovery_log_change_notice(struct spdk_nvmf_ctrlr *ctrlr)
3288 {
3289 	union spdk_nvme_async_event_completion event = {0};
3290 
3291 	/* Users may disable the event notification manually or
3292 	 * it may not be enabled due to keep alive timeout
3293 	 * not being set in connect command to discovery controller.
3294 	 */
3295 	if (!ctrlr->feat.async_event_configuration.bits.discovery_log_change_notice) {
3296 		return 0;
3297 	}
3298 
3299 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_DISCOVERY_LOG_CHANGE_MASK_BIT)) {
3300 		return 0;
3301 	}
3302 
3303 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_NOTICE;
3304 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_DISCOVERY_LOG_CHANGE;
3305 	event.bits.log_page_identifier = SPDK_NVME_LOG_DISCOVERY;
3306 
3307 	return nvmf_ctrlr_async_event_notification(ctrlr, &event);
3308 }
3309 
3310 int
3311 nvmf_ctrlr_async_event_error_event(struct spdk_nvmf_ctrlr *ctrlr,
3312 				   union spdk_nvme_async_event_completion event)
3313 {
3314 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_ERROR_MASK_BIT)) {
3315 		return 0;
3316 	}
3317 
3318 	if (event.bits.async_event_type != SPDK_NVME_ASYNC_EVENT_TYPE_ERROR ||
3319 	    event.bits.async_event_info > SPDK_NVME_ASYNC_EVENT_FW_IMAGE_LOAD) {
3320 		return 0;
3321 	}
3322 
3323 	return nvmf_ctrlr_async_event_notification(ctrlr, &event);
3324 }
3325 
3326 void
3327 nvmf_qpair_free_aer(struct spdk_nvmf_qpair *qpair)
3328 {
3329 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
3330 	int i;
3331 
3332 	if (!nvmf_qpair_is_admin_queue(qpair)) {
3333 		return;
3334 	}
3335 
3336 	for (i = 0; i < ctrlr->nr_aer_reqs; i++) {
3337 		spdk_nvmf_request_free(ctrlr->aer_req[i]);
3338 		ctrlr->aer_req[i] = NULL;
3339 	}
3340 
3341 	ctrlr->nr_aer_reqs = 0;
3342 }
3343 
3344 void
3345 nvmf_ctrlr_abort_aer(struct spdk_nvmf_ctrlr *ctrlr)
3346 {
3347 	struct spdk_nvmf_request *req;
3348 	int i;
3349 
3350 	if (!ctrlr->nr_aer_reqs) {
3351 		return;
3352 	}
3353 
3354 	for (i = 0; i < ctrlr->nr_aer_reqs; i++) {
3355 		req = ctrlr->aer_req[i];
3356 
3357 		req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3358 		req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
3359 		_nvmf_request_complete(req);
3360 
3361 		ctrlr->aer_req[i] = NULL;
3362 	}
3363 
3364 	ctrlr->nr_aer_reqs = 0;
3365 }
3366 
3367 static void
3368 _nvmf_ctrlr_add_reservation_log(void *ctx)
3369 {
3370 	struct spdk_nvmf_reservation_log *log = (struct spdk_nvmf_reservation_log *)ctx;
3371 	struct spdk_nvmf_ctrlr *ctrlr = log->ctrlr;
3372 
3373 	ctrlr->log_page_count++;
3374 
3375 	/* Maximum number of queued log pages is 255 */
3376 	if (ctrlr->num_avail_log_pages == 0xff) {
3377 		struct spdk_nvmf_reservation_log *entry;
3378 		entry = TAILQ_LAST(&ctrlr->log_head, log_page_head);
3379 		entry->log.log_page_count = ctrlr->log_page_count;
3380 		free(log);
3381 		return;
3382 	}
3383 
3384 	log->log.log_page_count = ctrlr->log_page_count;
3385 	log->log.num_avail_log_pages = ctrlr->num_avail_log_pages++;
3386 	TAILQ_INSERT_TAIL(&ctrlr->log_head, log, link);
3387 
3388 	nvmf_ctrlr_async_event_reservation_notification(ctrlr);
3389 }
3390 
3391 void
3392 nvmf_ctrlr_reservation_notice_log(struct spdk_nvmf_ctrlr *ctrlr,
3393 				  struct spdk_nvmf_ns *ns,
3394 				  enum spdk_nvme_reservation_notification_log_page_type type)
3395 {
3396 	struct spdk_nvmf_reservation_log *log;
3397 
3398 	switch (type) {
3399 	case SPDK_NVME_RESERVATION_LOG_PAGE_EMPTY:
3400 		return;
3401 	case SPDK_NVME_REGISTRATION_PREEMPTED:
3402 		if (ns->mask & SPDK_NVME_REGISTRATION_PREEMPTED_MASK) {
3403 			return;
3404 		}
3405 		break;
3406 	case SPDK_NVME_RESERVATION_RELEASED:
3407 		if (ns->mask & SPDK_NVME_RESERVATION_RELEASED_MASK) {
3408 			return;
3409 		}
3410 		break;
3411 	case SPDK_NVME_RESERVATION_PREEMPTED:
3412 		if (ns->mask & SPDK_NVME_RESERVATION_PREEMPTED_MASK) {
3413 			return;
3414 		}
3415 		break;
3416 	default:
3417 		return;
3418 	}
3419 
3420 	log = calloc(1, sizeof(*log));
3421 	if (!log) {
3422 		SPDK_ERRLOG("Alloc log page failed, ignore the log\n");
3423 		return;
3424 	}
3425 	log->ctrlr = ctrlr;
3426 	log->log.type = type;
3427 	log->log.nsid = ns->nsid;
3428 
3429 	spdk_thread_send_msg(ctrlr->thread, _nvmf_ctrlr_add_reservation_log, log);
3430 }
3431 
3432 /* Check from subsystem poll group's namespace information data structure */
3433 static bool
3434 nvmf_ns_info_ctrlr_is_registrant(struct spdk_nvmf_subsystem_pg_ns_info *ns_info,
3435 				 struct spdk_nvmf_ctrlr *ctrlr)
3436 {
3437 	uint32_t i;
3438 
3439 	for (i = 0; i < SPDK_NVMF_MAX_NUM_REGISTRANTS; i++) {
3440 		if (!spdk_uuid_compare(&ns_info->reg_hostid[i], &ctrlr->hostid)) {
3441 			return true;
3442 		}
3443 	}
3444 
3445 	return false;
3446 }
3447 
3448 /*
3449  * Check the NVMe command is permitted or not for current controller(Host).
3450  */
3451 static int
3452 nvmf_ns_reservation_request_check(struct spdk_nvmf_subsystem_pg_ns_info *ns_info,
3453 				  struct spdk_nvmf_ctrlr *ctrlr,
3454 				  struct spdk_nvmf_request *req)
3455 {
3456 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3457 	enum spdk_nvme_reservation_type rtype = ns_info->rtype;
3458 	uint8_t status = SPDK_NVME_SC_SUCCESS;
3459 	uint8_t racqa;
3460 	bool is_registrant;
3461 
3462 	/* No valid reservation */
3463 	if (!rtype) {
3464 		return 0;
3465 	}
3466 
3467 	is_registrant = nvmf_ns_info_ctrlr_is_registrant(ns_info, ctrlr);
3468 	/* All registrants type and current ctrlr is a valid registrant */
3469 	if ((rtype == SPDK_NVME_RESERVE_WRITE_EXCLUSIVE_ALL_REGS ||
3470 	     rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_ALL_REGS) && is_registrant) {
3471 		return 0;
3472 	} else if (!spdk_uuid_compare(&ns_info->holder_id, &ctrlr->hostid)) {
3473 		return 0;
3474 	}
3475 
3476 	/* Non-holder for current controller */
3477 	switch (cmd->opc) {
3478 	case SPDK_NVME_OPC_READ:
3479 	case SPDK_NVME_OPC_COMPARE:
3480 		if (rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS) {
3481 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3482 			goto exit;
3483 		}
3484 		if ((rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_REG_ONLY ||
3485 		     rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_ALL_REGS) && !is_registrant) {
3486 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3487 		}
3488 		break;
3489 	case SPDK_NVME_OPC_FLUSH:
3490 	case SPDK_NVME_OPC_WRITE:
3491 	case SPDK_NVME_OPC_WRITE_UNCORRECTABLE:
3492 	case SPDK_NVME_OPC_WRITE_ZEROES:
3493 	case SPDK_NVME_OPC_DATASET_MANAGEMENT:
3494 		if (rtype == SPDK_NVME_RESERVE_WRITE_EXCLUSIVE ||
3495 		    rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS) {
3496 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3497 			goto exit;
3498 		}
3499 		if (!is_registrant) {
3500 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3501 		}
3502 		break;
3503 	case SPDK_NVME_OPC_RESERVATION_ACQUIRE:
3504 		racqa = cmd->cdw10_bits.resv_acquire.racqa;
3505 		if (racqa == SPDK_NVME_RESERVE_ACQUIRE) {
3506 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3507 			goto exit;
3508 		}
3509 		if (!is_registrant) {
3510 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3511 		}
3512 		break;
3513 	case SPDK_NVME_OPC_RESERVATION_RELEASE:
3514 		if (!is_registrant) {
3515 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3516 		}
3517 		break;
3518 	default:
3519 		break;
3520 	}
3521 
3522 exit:
3523 	req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3524 	req->rsp->nvme_cpl.status.sc = status;
3525 	if (status == SPDK_NVME_SC_RESERVATION_CONFLICT) {
3526 		return -EPERM;
3527 	}
3528 
3529 	return 0;
3530 }
3531 
3532 static int
3533 nvmf_ctrlr_process_io_fused_cmd(struct spdk_nvmf_request *req, struct spdk_bdev *bdev,
3534 				struct spdk_bdev_desc *desc, struct spdk_io_channel *ch)
3535 {
3536 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3537 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
3538 	struct spdk_nvmf_request *first_fused_req = req->qpair->first_fused_req;
3539 	int rc;
3540 
3541 	if (cmd->fuse == SPDK_NVME_CMD_FUSE_FIRST) {
3542 		/* first fused operation (should be compare) */
3543 		if (first_fused_req != NULL) {
3544 			struct spdk_nvme_cpl *fused_response = &first_fused_req->rsp->nvme_cpl;
3545 
3546 			SPDK_ERRLOG("Wrong sequence of fused operations\n");
3547 
3548 			/* abort req->qpair->first_fused_request and continue with new fused command */
3549 			fused_response->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3550 			fused_response->status.sct = SPDK_NVME_SCT_GENERIC;
3551 			_nvmf_request_complete(first_fused_req);
3552 		} else if (cmd->opc != SPDK_NVME_OPC_COMPARE) {
3553 			SPDK_ERRLOG("Wrong op code of fused operations\n");
3554 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3555 			rsp->status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3556 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3557 		}
3558 
3559 		req->qpair->first_fused_req = req;
3560 		return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
3561 	} else if (cmd->fuse == SPDK_NVME_CMD_FUSE_SECOND) {
3562 		/* second fused operation (should be write) */
3563 		if (first_fused_req == NULL) {
3564 			SPDK_ERRLOG("Wrong sequence of fused operations\n");
3565 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3566 			rsp->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3567 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3568 		} else if (cmd->opc != SPDK_NVME_OPC_WRITE) {
3569 			struct spdk_nvme_cpl *fused_response = &first_fused_req->rsp->nvme_cpl;
3570 
3571 			SPDK_ERRLOG("Wrong op code of fused operations\n");
3572 
3573 			/* abort req->qpair->first_fused_request and fail current command */
3574 			fused_response->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3575 			fused_response->status.sct = SPDK_NVME_SCT_GENERIC;
3576 			_nvmf_request_complete(first_fused_req);
3577 
3578 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3579 			rsp->status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3580 			req->qpair->first_fused_req = NULL;
3581 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3582 		}
3583 
3584 		/* save request of first command to generate response later */
3585 		req->first_fused_req = first_fused_req;
3586 		req->qpair->first_fused_req = NULL;
3587 	} else {
3588 		SPDK_ERRLOG("Invalid fused command fuse field.\n");
3589 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3590 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
3591 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3592 	}
3593 
3594 	rc = nvmf_bdev_ctrlr_compare_and_write_cmd(bdev, desc, ch, req->first_fused_req, req);
3595 
3596 	if (rc == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
3597 		if (spdk_nvme_cpl_is_error(rsp)) {
3598 			struct spdk_nvme_cpl *fused_response = &first_fused_req->rsp->nvme_cpl;
3599 
3600 			fused_response->status = rsp->status;
3601 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3602 			rsp->status.sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
3603 			/* Complete first of fused commands. Second will be completed by upper layer */
3604 			_nvmf_request_complete(first_fused_req);
3605 			req->first_fused_req = NULL;
3606 		}
3607 	}
3608 
3609 	return rc;
3610 }
3611 
3612 bool
3613 nvmf_ctrlr_use_zcopy(struct spdk_nvmf_request *req)
3614 {
3615 	struct spdk_nvmf_ns *ns;
3616 
3617 	req->zcopy_phase = NVMF_ZCOPY_PHASE_NONE;
3618 
3619 	if (nvmf_qpair_is_admin_queue(req->qpair)) {
3620 		/* Admin queue */
3621 		return false;
3622 	}
3623 
3624 	if ((req->cmd->nvme_cmd.opc != SPDK_NVME_OPC_WRITE) &&
3625 	    (req->cmd->nvme_cmd.opc != SPDK_NVME_OPC_READ)) {
3626 		/* Not a READ or WRITE command */
3627 		return false;
3628 	}
3629 
3630 	if (req->cmd->nvme_cmd.fuse != SPDK_NVME_CMD_FUSE_NONE) {
3631 		/* Fused commands dont use zcopy buffers */
3632 		return false;
3633 	}
3634 
3635 	ns = _nvmf_subsystem_get_ns(req->qpair->ctrlr->subsys, req->cmd->nvme_cmd.nsid);
3636 	if (ns == NULL || ns->bdev == NULL || !ns->zcopy) {
3637 		return false;
3638 	}
3639 
3640 	req->zcopy_phase = NVMF_ZCOPY_PHASE_INIT;
3641 	return true;
3642 }
3643 
3644 /* If this function returns a non-zero value the request
3645  * reverts to using SPDK buffers
3646  */
3647 int
3648 spdk_nvmf_request_zcopy_start(struct spdk_nvmf_request *req)
3649 {
3650 	struct spdk_nvmf_qpair *qpair = req->qpair;
3651 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
3652 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
3653 	uint32_t nsid;
3654 	struct spdk_bdev *bdev;
3655 	struct spdk_bdev_desc *desc;
3656 	struct spdk_io_channel *ch;
3657 	int rc;
3658 
3659 	if (!qpair->ctrlr) {
3660 		goto end;
3661 	}
3662 
3663 	if (qpair->group->sgroups == NULL) {
3664 		goto end;
3665 	}
3666 
3667 	rc = spdk_nvmf_request_get_bdev(req->cmd->nvme_cmd.nsid, req,
3668 					&bdev, &desc, &ch);
3669 	if (rc != 0) {
3670 		goto end;
3671 	}
3672 
3673 	if (ch == NULL) {
3674 		goto end;
3675 	}
3676 
3677 	nsid = req->cmd->nvme_cmd.nsid;
3678 	sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
3679 	ns_info = &sgroup->ns_info[nsid - 1];
3680 	if (ns_info->state != SPDK_NVMF_SUBSYSTEM_ACTIVE) {
3681 		goto end;
3682 	}
3683 
3684 	if (qpair->state != SPDK_NVMF_QPAIR_ACTIVE) {
3685 		goto end;
3686 	}
3687 
3688 	/* Set iovcnt to be the maximum number of
3689 	 * iovs that the ZCOPY can use
3690 	 */
3691 	req->iovcnt = NVMF_REQ_MAX_BUFFERS;
3692 	TAILQ_INSERT_TAIL(&qpair->outstanding, req, link);
3693 	rc = nvmf_bdev_ctrlr_start_zcopy(bdev, desc, ch, req);
3694 	if (rc == 0) {
3695 		ns_info->io_outstanding++;
3696 		return 0;
3697 	}
3698 	TAILQ_REMOVE(&qpair->outstanding, req, link);
3699 
3700 end:
3701 	/* An error occurred, the subsystem is paused, or the qpair is not active.
3702 	 * Revert to using SPDK buffers
3703 	 */
3704 	req->zcopy_phase = NVMF_ZCOPY_PHASE_NONE;
3705 	return -1;
3706 }
3707 
3708 int
3709 spdk_nvmf_request_zcopy_end(struct spdk_nvmf_request *req, bool commit)
3710 {
3711 	req->zcopy_phase = NVMF_ZCOPY_PHASE_END_PENDING;
3712 	return nvmf_bdev_ctrlr_end_zcopy(req, commit);
3713 }
3714 
3715 int
3716 nvmf_ctrlr_process_io_cmd(struct spdk_nvmf_request *req)
3717 {
3718 	uint32_t nsid;
3719 	struct spdk_nvmf_ns *ns;
3720 	struct spdk_bdev *bdev;
3721 	struct spdk_bdev_desc *desc;
3722 	struct spdk_io_channel *ch;
3723 	struct spdk_nvmf_poll_group *group = req->qpair->group;
3724 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
3725 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3726 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
3727 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
3728 	enum spdk_nvme_ana_state ana_state;
3729 
3730 	/* pre-set response details for this command */
3731 	response->status.sc = SPDK_NVME_SC_SUCCESS;
3732 	nsid = cmd->nsid;
3733 
3734 	if (spdk_unlikely(ctrlr == NULL)) {
3735 		SPDK_ERRLOG("I/O command sent before CONNECT\n");
3736 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3737 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3738 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3739 	}
3740 
3741 	if (spdk_unlikely(ctrlr->vcprop.cc.bits.en != 1)) {
3742 		SPDK_ERRLOG("I/O command sent to disabled controller\n");
3743 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3744 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3745 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3746 	}
3747 
3748 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
3749 	if (ns == NULL || ns->bdev == NULL) {
3750 		SPDK_DEBUGLOG(nvmf, "Unsuccessful query for nsid %u\n", cmd->nsid);
3751 		response->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
3752 		response->status.dnr = 1;
3753 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3754 	}
3755 
3756 	ana_state = nvmf_ctrlr_get_ana_state(ctrlr, ns->anagrpid);
3757 	if (spdk_unlikely(ana_state != SPDK_NVME_ANA_OPTIMIZED_STATE &&
3758 			  ana_state != SPDK_NVME_ANA_NON_OPTIMIZED_STATE)) {
3759 		SPDK_DEBUGLOG(nvmf, "Fail I/O command due to ANA state %d\n",
3760 			      ana_state);
3761 		response->status.sct = SPDK_NVME_SCT_PATH;
3762 		response->status.sc = _nvme_ana_state_to_path_status(ana_state);
3763 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3764 	}
3765 
3766 	/* scan-build falsely reporting dereference of null pointer */
3767 	assert(group != NULL && group->sgroups != NULL);
3768 	ns_info = &group->sgroups[ctrlr->subsys->id].ns_info[nsid - 1];
3769 	if (nvmf_ns_reservation_request_check(ns_info, ctrlr, req)) {
3770 		SPDK_DEBUGLOG(nvmf, "Reservation Conflict for nsid %u, opcode %u\n",
3771 			      cmd->nsid, cmd->opc);
3772 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3773 	}
3774 
3775 	bdev = ns->bdev;
3776 	desc = ns->desc;
3777 	ch = ns_info->channel;
3778 
3779 	if (spdk_unlikely(cmd->fuse & SPDK_NVME_CMD_FUSE_MASK)) {
3780 		return nvmf_ctrlr_process_io_fused_cmd(req, bdev, desc, ch);
3781 	} else if (spdk_unlikely(req->qpair->first_fused_req != NULL)) {
3782 		struct spdk_nvme_cpl *fused_response = &req->qpair->first_fused_req->rsp->nvme_cpl;
3783 
3784 		SPDK_ERRLOG("Expected second of fused commands - failing first of fused commands\n");
3785 
3786 		/* abort req->qpair->first_fused_request and continue with new command */
3787 		fused_response->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3788 		fused_response->status.sct = SPDK_NVME_SCT_GENERIC;
3789 		_nvmf_request_complete(req->qpair->first_fused_req);
3790 		req->qpair->first_fused_req = NULL;
3791 	}
3792 
3793 	switch (cmd->opc) {
3794 	case SPDK_NVME_OPC_READ:
3795 		return nvmf_bdev_ctrlr_read_cmd(bdev, desc, ch, req);
3796 	case SPDK_NVME_OPC_WRITE:
3797 		return nvmf_bdev_ctrlr_write_cmd(bdev, desc, ch, req);
3798 	case SPDK_NVME_OPC_COMPARE:
3799 		return nvmf_bdev_ctrlr_compare_cmd(bdev, desc, ch, req);
3800 	case SPDK_NVME_OPC_WRITE_ZEROES:
3801 		return nvmf_bdev_ctrlr_write_zeroes_cmd(bdev, desc, ch, req);
3802 	case SPDK_NVME_OPC_FLUSH:
3803 		return nvmf_bdev_ctrlr_flush_cmd(bdev, desc, ch, req);
3804 	case SPDK_NVME_OPC_DATASET_MANAGEMENT:
3805 		return nvmf_bdev_ctrlr_dsm_cmd(bdev, desc, ch, req);
3806 	case SPDK_NVME_OPC_RESERVATION_REGISTER:
3807 	case SPDK_NVME_OPC_RESERVATION_ACQUIRE:
3808 	case SPDK_NVME_OPC_RESERVATION_RELEASE:
3809 	case SPDK_NVME_OPC_RESERVATION_REPORT:
3810 		spdk_thread_send_msg(ctrlr->subsys->thread, nvmf_ns_reservation_request, req);
3811 		return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
3812 	default:
3813 		return nvmf_bdev_ctrlr_nvme_passthru_io(bdev, desc, ch, req);
3814 	}
3815 }
3816 
3817 static void
3818 nvmf_qpair_request_cleanup(struct spdk_nvmf_qpair *qpair)
3819 {
3820 	if (qpair->state == SPDK_NVMF_QPAIR_DEACTIVATING) {
3821 		assert(qpair->state_cb != NULL);
3822 
3823 		if (TAILQ_EMPTY(&qpair->outstanding)) {
3824 			qpair->state_cb(qpair->state_cb_arg, 0);
3825 		}
3826 	}
3827 }
3828 
3829 int
3830 spdk_nvmf_request_free(struct spdk_nvmf_request *req)
3831 {
3832 	struct spdk_nvmf_qpair *qpair = req->qpair;
3833 
3834 	TAILQ_REMOVE(&qpair->outstanding, req, link);
3835 	if (nvmf_transport_req_free(req)) {
3836 		SPDK_ERRLOG("Unable to free transport level request resources.\n");
3837 	}
3838 
3839 	nvmf_qpair_request_cleanup(qpair);
3840 
3841 	return 0;
3842 }
3843 
3844 static void
3845 _nvmf_request_complete(void *ctx)
3846 {
3847 	struct spdk_nvmf_request *req = ctx;
3848 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
3849 	struct spdk_nvmf_qpair *qpair;
3850 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
3851 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
3852 	bool is_aer = false;
3853 	uint32_t nsid;
3854 	bool paused;
3855 	uint8_t opcode;
3856 
3857 	rsp->sqid = 0;
3858 	rsp->status.p = 0;
3859 	rsp->cid = req->cmd->nvme_cmd.cid;
3860 	nsid = req->cmd->nvme_cmd.nsid;
3861 	opcode = req->cmd->nvmf_cmd.opcode;
3862 
3863 	qpair = req->qpair;
3864 	if (qpair->ctrlr) {
3865 		sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
3866 		assert(sgroup != NULL);
3867 		is_aer = req->cmd->nvme_cmd.opc == SPDK_NVME_OPC_ASYNC_EVENT_REQUEST;
3868 
3869 		/*
3870 		 * Set the crd value.
3871 		 * If the the IO has any error, and dnr (DoNotRetry) is not 1,
3872 		 * and ACRE is enabled, we will set the crd to 1 to select the first CRDT.
3873 		 */
3874 		if (spdk_nvme_cpl_is_error(rsp) &&
3875 		    rsp->status.dnr == 0 &&
3876 		    qpair->ctrlr->acre_enabled) {
3877 			rsp->status.crd = 1;
3878 		}
3879 	} else if (spdk_unlikely(nvmf_request_is_fabric_connect(req))) {
3880 		sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
3881 	}
3882 
3883 	if (SPDK_DEBUGLOG_FLAG_ENABLED("nvmf")) {
3884 		spdk_nvme_print_completion(qpair->qid, rsp);
3885 	}
3886 
3887 	switch (req->zcopy_phase) {
3888 	case NVMF_ZCOPY_PHASE_NONE:
3889 		TAILQ_REMOVE(&qpair->outstanding, req, link);
3890 		break;
3891 	case NVMF_ZCOPY_PHASE_INIT:
3892 		if (spdk_unlikely(spdk_nvme_cpl_is_error(rsp))) {
3893 			/* The START failed or was aborted so revert to a normal IO */
3894 			req->zcopy_phase = NVMF_ZCOPY_PHASE_INIT_FAILED;
3895 			TAILQ_REMOVE(&qpair->outstanding, req, link);
3896 		} else {
3897 			req->zcopy_phase = NVMF_ZCOPY_PHASE_EXECUTE;
3898 		}
3899 		break;
3900 	case NVMF_ZCOPY_PHASE_EXECUTE:
3901 		break;
3902 	case NVMF_ZCOPY_PHASE_END_PENDING:
3903 		TAILQ_REMOVE(&qpair->outstanding, req, link);
3904 		req->zcopy_phase = NVMF_ZCOPY_PHASE_COMPLETE;
3905 		break;
3906 	default:
3907 		SPDK_ERRLOG("Invalid ZCOPY phase %u\n", req->zcopy_phase);
3908 		break;
3909 	}
3910 
3911 	if (nvmf_transport_req_complete(req)) {
3912 		SPDK_ERRLOG("Transport request completion error!\n");
3913 	}
3914 
3915 	/* AER cmd is an exception */
3916 	if (sgroup && !is_aer) {
3917 		if (spdk_unlikely(opcode == SPDK_NVME_OPC_FABRIC ||
3918 				  nvmf_qpair_is_admin_queue(qpair))) {
3919 			assert(sgroup->mgmt_io_outstanding > 0);
3920 			sgroup->mgmt_io_outstanding--;
3921 		} else {
3922 			if ((req->zcopy_phase == NVMF_ZCOPY_PHASE_NONE) ||
3923 			    (req->zcopy_phase == NVMF_ZCOPY_PHASE_COMPLETE)) {
3924 				/* End of request */
3925 
3926 				/* NOTE: This implicitly also checks for 0, since 0 - 1 wraps around to UINT32_MAX. */
3927 				if (spdk_likely(nsid - 1 < sgroup->num_ns)) {
3928 					sgroup->ns_info[nsid - 1].io_outstanding--;
3929 				}
3930 			}
3931 		}
3932 
3933 		if (spdk_unlikely(sgroup->state == SPDK_NVMF_SUBSYSTEM_PAUSING &&
3934 				  sgroup->mgmt_io_outstanding == 0)) {
3935 			paused = true;
3936 			for (nsid = 0; nsid < sgroup->num_ns; nsid++) {
3937 				ns_info = &sgroup->ns_info[nsid];
3938 
3939 				if (ns_info->state == SPDK_NVMF_SUBSYSTEM_PAUSING &&
3940 				    ns_info->io_outstanding > 0) {
3941 					paused = false;
3942 					break;
3943 				}
3944 			}
3945 
3946 			if (paused) {
3947 				sgroup->state = SPDK_NVMF_SUBSYSTEM_PAUSED;
3948 				sgroup->cb_fn(sgroup->cb_arg, 0);
3949 				sgroup->cb_fn = NULL;
3950 				sgroup->cb_arg = NULL;
3951 			}
3952 		}
3953 
3954 	}
3955 
3956 	nvmf_qpair_request_cleanup(qpair);
3957 }
3958 
3959 int
3960 spdk_nvmf_request_complete(struct spdk_nvmf_request *req)
3961 {
3962 	struct spdk_nvmf_qpair *qpair = req->qpair;
3963 
3964 	if (spdk_likely(qpair->group->thread == spdk_get_thread())) {
3965 		_nvmf_request_complete(req);
3966 	} else {
3967 		spdk_thread_send_msg(qpair->group->thread,
3968 				     _nvmf_request_complete, req);
3969 	}
3970 
3971 	return 0;
3972 }
3973 
3974 void
3975 spdk_nvmf_request_exec_fabrics(struct spdk_nvmf_request *req)
3976 {
3977 	struct spdk_nvmf_qpair *qpair = req->qpair;
3978 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
3979 	enum spdk_nvmf_request_exec_status status;
3980 
3981 	if (qpair->ctrlr) {
3982 		sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
3983 	} else if (spdk_unlikely(nvmf_request_is_fabric_connect(req))) {
3984 		sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
3985 	}
3986 
3987 	assert(sgroup != NULL);
3988 	sgroup->mgmt_io_outstanding++;
3989 
3990 	/* Place the request on the outstanding list so we can keep track of it */
3991 	nvmf_add_to_outstanding_queue(req);
3992 
3993 	assert(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC);
3994 	status = nvmf_ctrlr_process_fabrics_cmd(req);
3995 
3996 	if (status == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
3997 		_nvmf_request_complete(req);
3998 	}
3999 }
4000 
4001 static bool nvmf_check_subsystem_active(struct spdk_nvmf_request *req)
4002 {
4003 	struct spdk_nvmf_qpair *qpair = req->qpair;
4004 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
4005 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
4006 	uint32_t nsid;
4007 
4008 	if (qpair->ctrlr) {
4009 		sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
4010 		assert(sgroup != NULL);
4011 	} else if (spdk_unlikely(nvmf_request_is_fabric_connect(req))) {
4012 		sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
4013 	}
4014 
4015 	/* Check if the subsystem is paused (if there is a subsystem) */
4016 	if (sgroup != NULL) {
4017 		if (spdk_unlikely(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC ||
4018 				  nvmf_qpair_is_admin_queue(qpair))) {
4019 			if (sgroup->state != SPDK_NVMF_SUBSYSTEM_ACTIVE) {
4020 				/* The subsystem is not currently active. Queue this request. */
4021 				TAILQ_INSERT_TAIL(&sgroup->queued, req, link);
4022 				return false;
4023 			}
4024 			sgroup->mgmt_io_outstanding++;
4025 		} else {
4026 			nsid = req->cmd->nvme_cmd.nsid;
4027 
4028 			/* NOTE: This implicitly also checks for 0, since 0 - 1 wraps around to UINT32_MAX. */
4029 			if (spdk_unlikely(nsid - 1 >= sgroup->num_ns)) {
4030 				req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
4031 				req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
4032 				req->rsp->nvme_cpl.status.dnr = 1;
4033 				nvmf_add_to_outstanding_queue(req);
4034 				_nvmf_request_complete(req);
4035 				return false;
4036 			}
4037 
4038 			ns_info = &sgroup->ns_info[nsid - 1];
4039 			if (ns_info->channel == NULL) {
4040 				/* This can can happen if host sends I/O to a namespace that is
4041 				 * in the process of being added, but before the full addition
4042 				 * process is complete.  Report invalid namespace in that case.
4043 				 */
4044 				req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
4045 				req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
4046 				req->rsp->nvme_cpl.status.dnr = 1;
4047 				nvmf_add_to_outstanding_queue(req);
4048 				ns_info->io_outstanding++;
4049 				_nvmf_request_complete(req);
4050 				return false;
4051 			}
4052 
4053 			if (ns_info->state != SPDK_NVMF_SUBSYSTEM_ACTIVE) {
4054 				/* The namespace is not currently active. Queue this request. */
4055 				TAILQ_INSERT_TAIL(&sgroup->queued, req, link);
4056 				return false;
4057 			}
4058 
4059 			ns_info->io_outstanding++;
4060 		}
4061 
4062 		if (qpair->state != SPDK_NVMF_QPAIR_ACTIVE) {
4063 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
4064 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
4065 			nvmf_add_to_outstanding_queue(req);
4066 			_nvmf_request_complete(req);
4067 			return false;
4068 		}
4069 	}
4070 
4071 	return true;
4072 }
4073 
4074 void
4075 spdk_nvmf_request_exec(struct spdk_nvmf_request *req)
4076 {
4077 	struct spdk_nvmf_qpair *qpair = req->qpair;
4078 	enum spdk_nvmf_request_exec_status status;
4079 
4080 	if (!spdk_nvmf_using_zcopy(req->zcopy_phase)) {
4081 		if (!nvmf_check_subsystem_active(req)) {
4082 			return;
4083 		}
4084 	}
4085 
4086 	if (SPDK_DEBUGLOG_FLAG_ENABLED("nvmf")) {
4087 		spdk_nvme_print_command(qpair->qid, &req->cmd->nvme_cmd);
4088 	}
4089 
4090 	/* Place the request on the outstanding list so we can keep track of it */
4091 	nvmf_add_to_outstanding_queue(req);
4092 
4093 	if (spdk_unlikely(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC)) {
4094 		status = nvmf_ctrlr_process_fabrics_cmd(req);
4095 	} else if (spdk_unlikely(nvmf_qpair_is_admin_queue(qpair))) {
4096 		status = nvmf_ctrlr_process_admin_cmd(req);
4097 	} else {
4098 		status = nvmf_ctrlr_process_io_cmd(req);
4099 	}
4100 
4101 	if (status == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
4102 		_nvmf_request_complete(req);
4103 	}
4104 }
4105 
4106 static bool
4107 nvmf_ctrlr_get_dif_ctx(struct spdk_nvmf_ctrlr *ctrlr, struct spdk_nvme_cmd *cmd,
4108 		       struct spdk_dif_ctx *dif_ctx)
4109 {
4110 	struct spdk_nvmf_ns *ns;
4111 	struct spdk_bdev *bdev;
4112 
4113 	if (ctrlr == NULL || cmd == NULL) {
4114 		return false;
4115 	}
4116 
4117 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, cmd->nsid);
4118 	if (ns == NULL || ns->bdev == NULL) {
4119 		return false;
4120 	}
4121 
4122 	bdev = ns->bdev;
4123 
4124 	switch (cmd->opc) {
4125 	case SPDK_NVME_OPC_READ:
4126 	case SPDK_NVME_OPC_WRITE:
4127 	case SPDK_NVME_OPC_COMPARE:
4128 		return nvmf_bdev_ctrlr_get_dif_ctx(bdev, cmd, dif_ctx);
4129 	default:
4130 		break;
4131 	}
4132 
4133 	return false;
4134 }
4135 
4136 bool
4137 spdk_nvmf_request_get_dif_ctx(struct spdk_nvmf_request *req, struct spdk_dif_ctx *dif_ctx)
4138 {
4139 	struct spdk_nvmf_qpair *qpair = req->qpair;
4140 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
4141 
4142 	if (spdk_likely(ctrlr == NULL || !ctrlr->dif_insert_or_strip)) {
4143 		return false;
4144 	}
4145 
4146 	if (spdk_unlikely(qpair->state != SPDK_NVMF_QPAIR_ACTIVE)) {
4147 		return false;
4148 	}
4149 
4150 	if (spdk_unlikely(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC)) {
4151 		return false;
4152 	}
4153 
4154 	if (spdk_unlikely(nvmf_qpair_is_admin_queue(qpair))) {
4155 		return false;
4156 	}
4157 
4158 	return nvmf_ctrlr_get_dif_ctx(ctrlr, &req->cmd->nvme_cmd, dif_ctx);
4159 }
4160 
4161 void
4162 spdk_nvmf_set_custom_admin_cmd_hdlr(uint8_t opc, spdk_nvmf_custom_cmd_hdlr hdlr)
4163 {
4164 	g_nvmf_custom_admin_cmd_hdlrs[opc].hdlr = hdlr;
4165 }
4166 
4167 static int
4168 nvmf_passthru_admin_cmd(struct spdk_nvmf_request *req)
4169 {
4170 	struct spdk_bdev *bdev;
4171 	struct spdk_bdev_desc *desc;
4172 	struct spdk_io_channel *ch;
4173 	struct spdk_nvme_cmd *cmd = spdk_nvmf_request_get_cmd(req);
4174 	struct spdk_nvme_cpl *response = spdk_nvmf_request_get_response(req);
4175 	uint32_t bdev_nsid;
4176 	int rc;
4177 
4178 	if (g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].nsid == 0) {
4179 		bdev_nsid = cmd->nsid;
4180 	} else {
4181 		bdev_nsid = g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].nsid;
4182 	}
4183 
4184 	rc = spdk_nvmf_request_get_bdev(bdev_nsid, req, &bdev, &desc, &ch);
4185 	if (rc) {
4186 		response->status.sct = SPDK_NVME_SCT_GENERIC;
4187 		response->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
4188 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
4189 	}
4190 	return spdk_nvmf_bdev_ctrlr_nvme_passthru_admin(bdev, desc, ch, req, NULL);
4191 }
4192 
4193 void
4194 spdk_nvmf_set_passthru_admin_cmd(uint8_t opc, uint32_t forward_nsid)
4195 {
4196 	g_nvmf_custom_admin_cmd_hdlrs[opc].hdlr = nvmf_passthru_admin_cmd;
4197 	g_nvmf_custom_admin_cmd_hdlrs[opc].nsid = forward_nsid;
4198 }
4199 
4200 int
4201 spdk_nvmf_request_get_bdev(uint32_t nsid, struct spdk_nvmf_request *req,
4202 			   struct spdk_bdev **bdev, struct spdk_bdev_desc **desc, struct spdk_io_channel **ch)
4203 {
4204 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
4205 	struct spdk_nvmf_ns *ns;
4206 	struct spdk_nvmf_poll_group *group = req->qpair->group;
4207 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
4208 
4209 	*bdev = NULL;
4210 	*desc = NULL;
4211 	*ch = NULL;
4212 
4213 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
4214 	if (ns == NULL || ns->bdev == NULL) {
4215 		return -EINVAL;
4216 	}
4217 
4218 	assert(group != NULL && group->sgroups != NULL);
4219 	ns_info = &group->sgroups[ctrlr->subsys->id].ns_info[nsid - 1];
4220 	*bdev = ns->bdev;
4221 	*desc = ns->desc;
4222 	*ch = ns_info->channel;
4223 
4224 	return 0;
4225 }
4226 
4227 struct spdk_nvmf_ctrlr *spdk_nvmf_request_get_ctrlr(struct spdk_nvmf_request *req)
4228 {
4229 	return req->qpair->ctrlr;
4230 }
4231 
4232 struct spdk_nvme_cmd *spdk_nvmf_request_get_cmd(struct spdk_nvmf_request *req)
4233 {
4234 	return &req->cmd->nvme_cmd;
4235 }
4236 
4237 struct spdk_nvme_cpl *spdk_nvmf_request_get_response(struct spdk_nvmf_request *req)
4238 {
4239 	return &req->rsp->nvme_cpl;
4240 }
4241 
4242 struct spdk_nvmf_subsystem *spdk_nvmf_request_get_subsystem(struct spdk_nvmf_request *req)
4243 {
4244 	return req->qpair->ctrlr->subsys;
4245 }
4246 
4247 void spdk_nvmf_request_get_data(struct spdk_nvmf_request *req, void **data, uint32_t *length)
4248 {
4249 	*data = req->data;
4250 	*length = req->length;
4251 }
4252 
4253 struct spdk_nvmf_subsystem *spdk_nvmf_ctrlr_get_subsystem(struct spdk_nvmf_ctrlr *ctrlr)
4254 {
4255 	return ctrlr->subsys;
4256 }
4257 
4258 uint16_t spdk_nvmf_ctrlr_get_id(struct spdk_nvmf_ctrlr *ctrlr)
4259 {
4260 	return ctrlr->cntlid;
4261 }
4262 
4263 struct spdk_nvmf_request *spdk_nvmf_request_get_req_to_abort(struct spdk_nvmf_request *req)
4264 {
4265 	return req->req_to_abort;
4266 }
4267