xref: /spdk/lib/nvmf/ctrlr.c (revision 282b8b70a7e61dd67150fdb49b10a53ded6080a9)
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 
1929 	/* 4 - 63 Reserved */
1930 };
1931 
1932 static inline void
1933 nvmf_ctrlr_unmask_aen(struct spdk_nvmf_ctrlr *ctrlr,
1934 		      enum spdk_nvme_async_event_mask_bit mask)
1935 {
1936 	ctrlr->notice_aen_mask &= ~(1 << mask);
1937 }
1938 
1939 static inline bool
1940 nvmf_ctrlr_mask_aen(struct spdk_nvmf_ctrlr *ctrlr,
1941 		    enum spdk_nvme_async_event_mask_bit mask)
1942 {
1943 	if (ctrlr->notice_aen_mask & (1 << mask)) {
1944 		return false;
1945 	} else {
1946 		ctrlr->notice_aen_mask |= (1 << mask);
1947 		return true;
1948 	}
1949 }
1950 
1951 static void
1952 nvmf_get_ana_log_page(struct spdk_nvmf_ctrlr *ctrlr, struct iovec *iovs, int iovcnt,
1953 		      uint64_t offset, uint32_t length, uint32_t rae)
1954 {
1955 	struct spdk_nvme_ana_page ana_hdr;
1956 	struct spdk_nvme_ana_group_descriptor ana_desc;
1957 	size_t copy_len, copied_len;
1958 	uint32_t num_anagrp = 0, anagrpid;
1959 	struct spdk_nvmf_ns *ns;
1960 	struct copy_iovs_ctx copy_ctx;
1961 
1962 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
1963 
1964 	if (length == 0) {
1965 		goto done;
1966 	}
1967 
1968 	if (offset >= sizeof(ana_hdr)) {
1969 		offset -= sizeof(ana_hdr);
1970 	} else {
1971 		for (anagrpid = 1; anagrpid <= ctrlr->subsys->max_nsid; anagrpid++) {
1972 			if (ctrlr->subsys->ana_group[anagrpid - 1] > 0) {
1973 				num_anagrp++;
1974 			}
1975 		}
1976 
1977 		memset(&ana_hdr, 0, sizeof(ana_hdr));
1978 
1979 		ana_hdr.num_ana_group_desc = num_anagrp;
1980 		/* TODO: Support Change Count. */
1981 		ana_hdr.change_count = 0;
1982 
1983 		copy_len = spdk_min(sizeof(ana_hdr) - offset, length);
1984 		copied_len = _copy_buf_to_iovs(&copy_ctx, (const char *)&ana_hdr + offset, copy_len);
1985 		assert(copied_len == copy_len);
1986 		length -= copied_len;
1987 		offset = 0;
1988 	}
1989 
1990 	if (length == 0) {
1991 		goto done;
1992 	}
1993 
1994 	for (anagrpid = 1; anagrpid <= ctrlr->subsys->max_nsid; anagrpid++) {
1995 		if (ctrlr->subsys->ana_group[anagrpid - 1] == 0) {
1996 			continue;
1997 		}
1998 
1999 		if (offset >= sizeof(ana_desc)) {
2000 			offset -= sizeof(ana_desc);
2001 		} else {
2002 			memset(&ana_desc, 0, sizeof(ana_desc));
2003 
2004 			ana_desc.ana_group_id = anagrpid;
2005 			ana_desc.num_of_nsid = ctrlr->subsys->ana_group[anagrpid - 1];
2006 			ana_desc.ana_state = ctrlr->listener->ana_state[anagrpid - 1];
2007 
2008 			copy_len = spdk_min(sizeof(ana_desc) - offset, length);
2009 			copied_len = _copy_buf_to_iovs(&copy_ctx, (const char *)&ana_desc + offset,
2010 						       copy_len);
2011 			assert(copied_len == copy_len);
2012 			length -= copied_len;
2013 			offset = 0;
2014 
2015 			if (length == 0) {
2016 				goto done;
2017 			}
2018 		}
2019 
2020 		/* TODO: Revisit here about O(n^2) cost if we have subsystem with
2021 		 * many namespaces in the future.
2022 		 */
2023 		for (ns = spdk_nvmf_subsystem_get_first_ns(ctrlr->subsys); ns != NULL;
2024 		     ns = spdk_nvmf_subsystem_get_next_ns(ctrlr->subsys, ns)) {
2025 			if (ns->anagrpid != anagrpid) {
2026 				continue;
2027 			}
2028 
2029 			if (offset >= sizeof(uint32_t)) {
2030 				offset -= sizeof(uint32_t);
2031 				continue;
2032 			}
2033 
2034 			copy_len = spdk_min(sizeof(uint32_t) - offset, length);
2035 			copied_len = _copy_buf_to_iovs(&copy_ctx, (const char *)&ns->nsid + offset,
2036 						       copy_len);
2037 			assert(copied_len == copy_len);
2038 			length -= copied_len;
2039 			offset = 0;
2040 
2041 			if (length == 0) {
2042 				goto done;
2043 			}
2044 		}
2045 	}
2046 
2047 done:
2048 	if (!rae) {
2049 		nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_ANA_CHANGE_MASK_BIT);
2050 	}
2051 }
2052 
2053 void
2054 nvmf_ctrlr_ns_changed(struct spdk_nvmf_ctrlr *ctrlr, uint32_t nsid)
2055 {
2056 	uint16_t max_changes = SPDK_COUNTOF(ctrlr->changed_ns_list.ns_list);
2057 	uint16_t i;
2058 	bool found = false;
2059 
2060 	for (i = 0; i < ctrlr->changed_ns_list_count; i++) {
2061 		if (ctrlr->changed_ns_list.ns_list[i] == nsid) {
2062 			/* nsid is already in the list */
2063 			found = true;
2064 			break;
2065 		}
2066 	}
2067 
2068 	if (!found) {
2069 		if (ctrlr->changed_ns_list_count == max_changes) {
2070 			/* Out of space - set first entry to FFFFFFFFh and zero-fill the rest. */
2071 			ctrlr->changed_ns_list.ns_list[0] = 0xFFFFFFFFu;
2072 			for (i = 1; i < max_changes; i++) {
2073 				ctrlr->changed_ns_list.ns_list[i] = 0;
2074 			}
2075 		} else {
2076 			ctrlr->changed_ns_list.ns_list[ctrlr->changed_ns_list_count++] = nsid;
2077 		}
2078 	}
2079 }
2080 
2081 static void
2082 nvmf_get_changed_ns_list_log_page(struct spdk_nvmf_ctrlr *ctrlr,
2083 				  struct iovec *iovs, int iovcnt, uint64_t offset, uint32_t length, uint32_t rae)
2084 {
2085 	size_t copy_length;
2086 	struct copy_iovs_ctx copy_ctx;
2087 
2088 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
2089 
2090 	if (offset < sizeof(ctrlr->changed_ns_list)) {
2091 		copy_length = spdk_min(length, sizeof(ctrlr->changed_ns_list) - offset);
2092 		if (copy_length) {
2093 			_copy_buf_to_iovs(&copy_ctx, (char *)&ctrlr->changed_ns_list + offset, copy_length);
2094 		}
2095 	}
2096 
2097 	/* Clear log page each time it is read */
2098 	ctrlr->changed_ns_list_count = 0;
2099 	memset(&ctrlr->changed_ns_list, 0, sizeof(ctrlr->changed_ns_list));
2100 
2101 	if (!rae) {
2102 		nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_NS_ATTR_CHANGE_MASK_BIT);
2103 	}
2104 }
2105 
2106 /* The structure can be modified if we provide support for other commands in future */
2107 static const struct spdk_nvme_cmds_and_effect_log_page g_cmds_and_effect_log_page = {
2108 	.admin_cmds_supported = {
2109 		/* CSUPP, LBCC, NCC, NIC, CCC, CSE */
2110 		/* Get Log Page */
2111 		[SPDK_NVME_OPC_GET_LOG_PAGE]		= {1, 0, 0, 0, 0, 0, 0, 0},
2112 		/* Identify */
2113 		[SPDK_NVME_OPC_IDENTIFY]		= {1, 0, 0, 0, 0, 0, 0, 0},
2114 		/* Abort */
2115 		[SPDK_NVME_OPC_ABORT]			= {1, 0, 0, 0, 0, 0, 0, 0},
2116 		/* Set Features */
2117 		[SPDK_NVME_OPC_SET_FEATURES]		= {1, 0, 0, 0, 0, 0, 0, 0},
2118 		/* Get Features */
2119 		[SPDK_NVME_OPC_GET_FEATURES]		= {1, 0, 0, 0, 0, 0, 0, 0},
2120 		/* Async Event Request */
2121 		[SPDK_NVME_OPC_ASYNC_EVENT_REQUEST]	= {1, 0, 0, 0, 0, 0, 0, 0},
2122 		/* Keep Alive */
2123 		[SPDK_NVME_OPC_KEEP_ALIVE]		= {1, 0, 0, 0, 0, 0, 0, 0},
2124 	},
2125 	.io_cmds_supported = {
2126 		/* FLUSH */
2127 		[SPDK_NVME_OPC_FLUSH]			= {1, 1, 0, 0, 0, 0, 0, 0},
2128 		/* WRITE */
2129 		[SPDK_NVME_OPC_WRITE]			= {1, 1, 0, 0, 0, 0, 0, 0},
2130 		/* READ */
2131 		[SPDK_NVME_OPC_READ]			= {1, 0, 0, 0, 0, 0, 0, 0},
2132 		/* WRITE ZEROES */
2133 		[SPDK_NVME_OPC_WRITE_ZEROES]		= {1, 1, 0, 0, 0, 0, 0, 0},
2134 		/* DATASET MANAGEMENT */
2135 		[SPDK_NVME_OPC_DATASET_MANAGEMENT]	= {1, 1, 0, 0, 0, 0, 0, 0},
2136 		/* COMPARE */
2137 		[SPDK_NVME_OPC_COMPARE]			= {1, 0, 0, 0, 0, 0, 0, 0},
2138 	},
2139 };
2140 
2141 static void
2142 nvmf_get_cmds_and_effects_log_page(struct iovec *iovs, int iovcnt,
2143 				   uint64_t offset, uint32_t length)
2144 {
2145 	uint32_t page_size = sizeof(struct spdk_nvme_cmds_and_effect_log_page);
2146 	size_t copy_len = 0;
2147 	struct copy_iovs_ctx copy_ctx;
2148 
2149 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
2150 
2151 	if (offset < page_size) {
2152 		copy_len = spdk_min(page_size - offset, length);
2153 		_copy_buf_to_iovs(&copy_ctx, (char *)(&g_cmds_and_effect_log_page) + offset, copy_len);
2154 	}
2155 }
2156 
2157 static void
2158 nvmf_get_reservation_notification_log_page(struct spdk_nvmf_ctrlr *ctrlr,
2159 		struct iovec *iovs, int iovcnt, uint64_t offset, uint32_t length, uint32_t rae)
2160 {
2161 	uint32_t unit_log_len, avail_log_len, next_pos, copy_len;
2162 	struct spdk_nvmf_reservation_log *log, *log_tmp;
2163 	struct copy_iovs_ctx copy_ctx;
2164 
2165 	_init_copy_iovs_ctx(&copy_ctx, iovs, iovcnt);
2166 
2167 	unit_log_len = sizeof(struct spdk_nvme_reservation_notification_log);
2168 	/* No available log, return zeroed log pages */
2169 	if (!ctrlr->num_avail_log_pages) {
2170 		return;
2171 	}
2172 
2173 	avail_log_len = ctrlr->num_avail_log_pages * unit_log_len;
2174 	if (offset >= avail_log_len) {
2175 		return;
2176 	}
2177 
2178 	next_pos = 0;
2179 	TAILQ_FOREACH_SAFE(log, &ctrlr->log_head, link, log_tmp) {
2180 		TAILQ_REMOVE(&ctrlr->log_head, log, link);
2181 		ctrlr->num_avail_log_pages--;
2182 
2183 		next_pos += unit_log_len;
2184 		if (next_pos > offset) {
2185 			copy_len = spdk_min(next_pos - offset, length);
2186 			_copy_buf_to_iovs(&copy_ctx, &log->log, copy_len);
2187 			length -= copy_len;
2188 			offset += copy_len;
2189 		}
2190 		free(log);
2191 
2192 		if (length == 0) {
2193 			break;
2194 		}
2195 	}
2196 
2197 	if (!rae) {
2198 		nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_RESERVATION_LOG_AVAIL_MASK_BIT);
2199 	}
2200 	return;
2201 }
2202 
2203 static int
2204 nvmf_ctrlr_get_log_page(struct spdk_nvmf_request *req)
2205 {
2206 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2207 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2208 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2209 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
2210 	uint64_t offset, len;
2211 	uint32_t rae, numdl, numdu;
2212 	uint8_t lid;
2213 
2214 	if (req->data == NULL) {
2215 		SPDK_ERRLOG("get log command with no buffer\n");
2216 		response->status.sct = SPDK_NVME_SCT_GENERIC;
2217 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2218 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2219 	}
2220 
2221 	offset = (uint64_t)cmd->cdw12 | ((uint64_t)cmd->cdw13 << 32);
2222 	if (offset & 3) {
2223 		SPDK_ERRLOG("Invalid log page offset 0x%" PRIx64 "\n", offset);
2224 		response->status.sct = SPDK_NVME_SCT_GENERIC;
2225 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2226 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2227 	}
2228 
2229 	rae = cmd->cdw10_bits.get_log_page.rae;
2230 	numdl = cmd->cdw10_bits.get_log_page.numdl;
2231 	numdu = cmd->cdw11_bits.get_log_page.numdu;
2232 	len = ((numdu << 16) + numdl + (uint64_t)1) * 4;
2233 	if (len > req->length) {
2234 		SPDK_ERRLOG("Get log page: len (%" PRIu64 ") > buf size (%u)\n",
2235 			    len, req->length);
2236 		response->status.sct = SPDK_NVME_SCT_GENERIC;
2237 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2238 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2239 	}
2240 
2241 	lid = cmd->cdw10_bits.get_log_page.lid;
2242 	SPDK_DEBUGLOG(nvmf, "Get log page: LID=0x%02X offset=0x%" PRIx64 " len=0x%" PRIx64 " rae=%u\n",
2243 		      lid, offset, len, rae);
2244 
2245 	if (subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2246 		switch (lid) {
2247 		case SPDK_NVME_LOG_DISCOVERY:
2248 			nvmf_get_discovery_log_page(subsystem->tgt, ctrlr->hostnqn, req->iov, req->iovcnt, offset,
2249 						    len);
2250 			if (!rae) {
2251 				nvmf_ctrlr_unmask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_DISCOVERY_LOG_CHANGE_MASK_BIT);
2252 			}
2253 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2254 		default:
2255 			goto invalid_log_page;
2256 		}
2257 	} else {
2258 		switch (lid) {
2259 		case SPDK_NVME_LOG_ERROR:
2260 		case SPDK_NVME_LOG_HEALTH_INFORMATION:
2261 			/* TODO: actually fill out log page data */
2262 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2263 		case SPDK_NVME_LOG_FIRMWARE_SLOT:
2264 			nvmf_get_firmware_slot_log_page(req->iov, req->iovcnt, offset, len);
2265 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2266 		case SPDK_NVME_LOG_ASYMMETRIC_NAMESPACE_ACCESS:
2267 			if (subsystem->flags.ana_reporting) {
2268 				nvmf_get_ana_log_page(ctrlr, req->iov, req->iovcnt, offset, len, rae);
2269 				return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2270 			} else {
2271 				goto invalid_log_page;
2272 			}
2273 		case SPDK_NVME_LOG_COMMAND_EFFECTS_LOG:
2274 			nvmf_get_cmds_and_effects_log_page(req->iov, req->iovcnt, offset, len);
2275 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2276 		case SPDK_NVME_LOG_CHANGED_NS_LIST:
2277 			nvmf_get_changed_ns_list_log_page(ctrlr, req->iov, req->iovcnt, offset, len, rae);
2278 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2279 		case SPDK_NVME_LOG_RESERVATION_NOTIFICATION:
2280 			nvmf_get_reservation_notification_log_page(ctrlr, req->iov, req->iovcnt, offset, len, rae);
2281 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2282 		default:
2283 			goto invalid_log_page;
2284 		}
2285 	}
2286 
2287 invalid_log_page:
2288 	SPDK_INFOLOG(nvmf, "Unsupported Get Log Page 0x%02X\n", lid);
2289 	response->status.sct = SPDK_NVME_SCT_GENERIC;
2290 	response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2291 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2292 }
2293 
2294 int
2295 spdk_nvmf_ctrlr_identify_ns(struct spdk_nvmf_ctrlr *ctrlr,
2296 			    struct spdk_nvme_cmd *cmd,
2297 			    struct spdk_nvme_cpl *rsp,
2298 			    struct spdk_nvme_ns_data *nsdata)
2299 {
2300 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2301 	struct spdk_nvmf_ns *ns;
2302 	uint32_t max_num_blocks;
2303 	enum spdk_nvme_ana_state ana_state;
2304 
2305 	if (cmd->nsid == 0 || cmd->nsid > subsystem->max_nsid) {
2306 		SPDK_ERRLOG("Identify Namespace for invalid NSID %u\n", cmd->nsid);
2307 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2308 		rsp->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
2309 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2310 	}
2311 
2312 	ns = _nvmf_subsystem_get_ns(subsystem, cmd->nsid);
2313 	if (ns == NULL || ns->bdev == NULL) {
2314 		/*
2315 		 * Inactive namespaces should return a zero filled data structure.
2316 		 * The data buffer is already zeroed by nvmf_ctrlr_process_admin_cmd(),
2317 		 * so we can just return early here.
2318 		 */
2319 		SPDK_DEBUGLOG(nvmf, "Identify Namespace for inactive NSID %u\n", cmd->nsid);
2320 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2321 		rsp->status.sc = SPDK_NVME_SC_SUCCESS;
2322 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2323 	}
2324 
2325 	nvmf_bdev_ctrlr_identify_ns(ns, nsdata, ctrlr->dif_insert_or_strip);
2326 
2327 	/* Due to bug in the Linux kernel NVMe driver we have to set noiob no larger than mdts */
2328 	max_num_blocks = ctrlr->admin_qpair->transport->opts.max_io_size /
2329 			 (1U << nsdata->lbaf[nsdata->flbas.format].lbads);
2330 	if (nsdata->noiob > max_num_blocks) {
2331 		nsdata->noiob = max_num_blocks;
2332 	}
2333 
2334 	if (subsystem->flags.ana_reporting) {
2335 		assert(ns->anagrpid - 1 < subsystem->max_nsid);
2336 		nsdata->anagrpid = ns->anagrpid;
2337 
2338 		ana_state = ctrlr->listener->ana_state[ns->anagrpid - 1];
2339 		if (ana_state == SPDK_NVME_ANA_INACCESSIBLE_STATE ||
2340 		    ana_state == SPDK_NVME_ANA_PERSISTENT_LOSS_STATE) {
2341 			nsdata->nuse = 0;
2342 		}
2343 	}
2344 
2345 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2346 }
2347 
2348 static void
2349 nvmf_ctrlr_populate_oacs(struct spdk_nvmf_ctrlr *ctrlr,
2350 			 struct spdk_nvme_ctrlr_data *cdata)
2351 {
2352 	cdata->oacs.virtualization_management =
2353 		g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_VIRTUALIZATION_MANAGEMENT].hdlr != NULL;
2354 	cdata->oacs.nvme_mi = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NVME_MI_SEND].hdlr != NULL
2355 			      && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NVME_MI_RECEIVE].hdlr != NULL;
2356 	cdata->oacs.directives = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_DIRECTIVE_SEND].hdlr != NULL
2357 				 && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_DIRECTIVE_RECEIVE].hdlr != NULL;
2358 	cdata->oacs.device_self_test =
2359 		g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_DEVICE_SELF_TEST].hdlr != NULL;
2360 	cdata->oacs.ns_manage = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NS_MANAGEMENT].hdlr != NULL
2361 				&& g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_NS_ATTACHMENT].hdlr != NULL;
2362 	cdata->oacs.firmware = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_FIRMWARE_IMAGE_DOWNLOAD].hdlr !=
2363 			       NULL
2364 			       && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_FIRMWARE_COMMIT].hdlr != NULL;
2365 	cdata->oacs.format =
2366 		g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_FORMAT_NVM].hdlr != NULL;
2367 	cdata->oacs.security = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_SECURITY_SEND].hdlr != NULL
2368 			       && g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_SECURITY_RECEIVE].hdlr != NULL;
2369 	cdata->oacs.get_lba_status = g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_GET_LBA_STATUS].hdlr !=
2370 				     NULL;
2371 }
2372 
2373 int
2374 spdk_nvmf_ctrlr_identify_ctrlr(struct spdk_nvmf_ctrlr *ctrlr, struct spdk_nvme_ctrlr_data *cdata)
2375 {
2376 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2377 	struct spdk_nvmf_transport *transport = ctrlr->admin_qpair->transport;
2378 
2379 	/*
2380 	 * Common fields for discovery and NVM subsystems
2381 	 */
2382 	spdk_strcpy_pad(cdata->fr, FW_VERSION, sizeof(cdata->fr), ' ');
2383 	assert((transport->opts.max_io_size % 4096) == 0);
2384 	cdata->mdts = spdk_u32log2(transport->opts.max_io_size / 4096);
2385 	cdata->cntlid = ctrlr->cntlid;
2386 	cdata->ver = ctrlr->vcprop.vs;
2387 	cdata->aerl = NVMF_MAX_ASYNC_EVENTS - 1;
2388 	cdata->lpa.edlp = 1;
2389 	cdata->elpe = 127;
2390 	cdata->maxcmd = transport->opts.max_queue_depth;
2391 	cdata->sgls = ctrlr->cdata.sgls;
2392 	cdata->fuses.compare_and_write = 1;
2393 	cdata->acwu = 1;
2394 	if (subsystem->flags.ana_reporting) {
2395 		cdata->mnan = subsystem->max_nsid;
2396 	}
2397 	spdk_strcpy_pad(cdata->subnqn, subsystem->subnqn, sizeof(cdata->subnqn), '\0');
2398 
2399 	SPDK_DEBUGLOG(nvmf, "ctrlr data: maxcmd 0x%x\n", cdata->maxcmd);
2400 	SPDK_DEBUGLOG(nvmf, "sgls data: 0x%x\n", from_le32(&cdata->sgls));
2401 
2402 
2403 	if (subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2404 		/*
2405 		 * NVM Discovery subsystem fields
2406 		 */
2407 		cdata->oaes.discovery_log_change_notices = 1;
2408 	} else {
2409 		/*
2410 		 * NVM subsystem fields (reserved for discovery subsystems)
2411 		 */
2412 		spdk_strcpy_pad(cdata->mn, spdk_nvmf_subsystem_get_mn(subsystem), sizeof(cdata->mn), ' ');
2413 		spdk_strcpy_pad(cdata->sn, spdk_nvmf_subsystem_get_sn(subsystem), sizeof(cdata->sn), ' ');
2414 		cdata->kas = ctrlr->cdata.kas;
2415 
2416 		cdata->rab = 6;
2417 		cdata->cmic.multi_port = 1;
2418 		cdata->cmic.multi_ctrlr = 1;
2419 		if (subsystem->flags.ana_reporting) {
2420 			/* Asymmetric Namespace Access Reporting is supported. */
2421 			cdata->cmic.ana_reporting = 1;
2422 		}
2423 		cdata->oaes.ns_attribute_notices = 1;
2424 		if (subsystem->flags.ana_reporting) {
2425 			cdata->oaes.ana_change_notices = 1;
2426 		}
2427 		cdata->ctratt.host_id_exhid_supported = 1;
2428 		/* TODO: Concurrent execution of multiple abort commands. */
2429 		cdata->acl = 0;
2430 		cdata->frmw.slot1_ro = 1;
2431 		cdata->frmw.num_slots = 1;
2432 
2433 		cdata->lpa.celp = 1; /* Command Effects log page supported */
2434 
2435 		cdata->sqes.min = 6;
2436 		cdata->sqes.max = 6;
2437 		cdata->cqes.min = 4;
2438 		cdata->cqes.max = 4;
2439 		cdata->nn = subsystem->max_nsid;
2440 		cdata->vwc.present = 1;
2441 		cdata->vwc.flush_broadcast = SPDK_NVME_FLUSH_BROADCAST_NOT_SUPPORTED;
2442 
2443 		cdata->nvmf_specific = ctrlr->cdata.nvmf_specific;
2444 
2445 		cdata->oncs.dsm = nvmf_ctrlr_dsm_supported(ctrlr);
2446 		cdata->oncs.write_zeroes = nvmf_ctrlr_write_zeroes_supported(ctrlr);
2447 		cdata->oncs.reservations = ctrlr->cdata.oncs.reservations;
2448 		if (subsystem->flags.ana_reporting) {
2449 			cdata->anatt = ANA_TRANSITION_TIME_IN_SEC;
2450 			/* ANA Change state is not used, and ANA Persistent Loss state
2451 			 * is not supported for now.
2452 			 */
2453 			cdata->anacap.ana_optimized_state = 1;
2454 			cdata->anacap.ana_non_optimized_state = 1;
2455 			cdata->anacap.ana_inaccessible_state = 1;
2456 			/* ANAGRPID does not change while namespace is attached to controller */
2457 			cdata->anacap.no_change_anagrpid = 1;
2458 			cdata->anagrpmax = subsystem->max_nsid;
2459 			cdata->nanagrpid = subsystem->max_nsid;
2460 		}
2461 
2462 		nvmf_ctrlr_populate_oacs(ctrlr, cdata);
2463 
2464 		assert(subsystem->tgt != NULL);
2465 		cdata->crdt[0] = subsystem->tgt->crdt[0];
2466 		cdata->crdt[1] = subsystem->tgt->crdt[1];
2467 		cdata->crdt[2] = subsystem->tgt->crdt[2];
2468 
2469 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: ioccsz 0x%x\n",
2470 			      cdata->nvmf_specific.ioccsz);
2471 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: iorcsz 0x%x\n",
2472 			      cdata->nvmf_specific.iorcsz);
2473 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: icdoff 0x%x\n",
2474 			      cdata->nvmf_specific.icdoff);
2475 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: ctrattr 0x%x\n",
2476 			      *(uint8_t *)&cdata->nvmf_specific.ctrattr);
2477 		SPDK_DEBUGLOG(nvmf, "ext ctrlr data: msdbd 0x%x\n",
2478 			      cdata->nvmf_specific.msdbd);
2479 	}
2480 
2481 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2482 }
2483 
2484 static int
2485 nvmf_ctrlr_identify_active_ns_list(struct spdk_nvmf_subsystem *subsystem,
2486 				   struct spdk_nvme_cmd *cmd,
2487 				   struct spdk_nvme_cpl *rsp,
2488 				   struct spdk_nvme_ns_list *ns_list)
2489 {
2490 	struct spdk_nvmf_ns *ns;
2491 	uint32_t count = 0;
2492 
2493 	if (cmd->nsid >= 0xfffffffeUL) {
2494 		SPDK_ERRLOG("Identify Active Namespace List with invalid NSID %u\n", cmd->nsid);
2495 		rsp->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
2496 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2497 	}
2498 
2499 	memset(ns_list, 0, sizeof(*ns_list));
2500 
2501 	for (ns = spdk_nvmf_subsystem_get_first_ns(subsystem); ns != NULL;
2502 	     ns = spdk_nvmf_subsystem_get_next_ns(subsystem, ns)) {
2503 		if (ns->opts.nsid <= cmd->nsid) {
2504 			continue;
2505 		}
2506 
2507 		ns_list->ns_list[count++] = ns->opts.nsid;
2508 		if (count == SPDK_COUNTOF(ns_list->ns_list)) {
2509 			break;
2510 		}
2511 	}
2512 
2513 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2514 }
2515 
2516 static void
2517 _add_ns_id_desc(void **buf_ptr, size_t *buf_remain,
2518 		enum spdk_nvme_nidt type,
2519 		const void *data, size_t data_size)
2520 {
2521 	struct spdk_nvme_ns_id_desc *desc;
2522 	size_t desc_size = sizeof(*desc) + data_size;
2523 
2524 	/*
2525 	 * These should never fail in practice, since all valid NS ID descriptors
2526 	 * should be defined so that they fit in the available 4096-byte buffer.
2527 	 */
2528 	assert(data_size > 0);
2529 	assert(data_size <= UINT8_MAX);
2530 	assert(desc_size < *buf_remain);
2531 	if (data_size == 0 || data_size > UINT8_MAX || desc_size > *buf_remain) {
2532 		return;
2533 	}
2534 
2535 	desc = *buf_ptr;
2536 	desc->nidt = type;
2537 	desc->nidl = data_size;
2538 	memcpy(desc->nid, data, data_size);
2539 
2540 	*buf_ptr += desc_size;
2541 	*buf_remain -= desc_size;
2542 }
2543 
2544 static int
2545 nvmf_ctrlr_identify_ns_id_descriptor_list(
2546 	struct spdk_nvmf_subsystem *subsystem,
2547 	struct spdk_nvme_cmd *cmd,
2548 	struct spdk_nvme_cpl *rsp,
2549 	void *id_desc_list, size_t id_desc_list_size)
2550 {
2551 	struct spdk_nvmf_ns *ns;
2552 	size_t buf_remain = id_desc_list_size;
2553 	void *buf_ptr = id_desc_list;
2554 
2555 	ns = _nvmf_subsystem_get_ns(subsystem, cmd->nsid);
2556 	if (ns == NULL || ns->bdev == NULL) {
2557 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2558 		rsp->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
2559 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2560 	}
2561 
2562 #define ADD_ID_DESC(type, data, size) \
2563 	do { \
2564 		if (!spdk_mem_all_zero(data, size)) { \
2565 			_add_ns_id_desc(&buf_ptr, &buf_remain, type, data, size); \
2566 		} \
2567 	} while (0)
2568 
2569 	ADD_ID_DESC(SPDK_NVME_NIDT_EUI64, ns->opts.eui64, sizeof(ns->opts.eui64));
2570 	ADD_ID_DESC(SPDK_NVME_NIDT_NGUID, ns->opts.nguid, sizeof(ns->opts.nguid));
2571 	ADD_ID_DESC(SPDK_NVME_NIDT_UUID, &ns->opts.uuid, sizeof(ns->opts.uuid));
2572 
2573 	/*
2574 	 * The list is automatically 0-terminated because controller to host buffers in
2575 	 * admin commands always get zeroed in nvmf_ctrlr_process_admin_cmd().
2576 	 */
2577 
2578 #undef ADD_ID_DESC
2579 
2580 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2581 }
2582 
2583 static int
2584 nvmf_ctrlr_identify(struct spdk_nvmf_request *req)
2585 {
2586 	uint8_t cns;
2587 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2588 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2589 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
2590 	struct spdk_nvmf_subsystem *subsystem = ctrlr->subsys;
2591 
2592 	if (req->data == NULL || req->length < 4096) {
2593 		SPDK_ERRLOG("identify command with invalid buffer\n");
2594 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2595 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2596 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2597 	}
2598 
2599 	cns = cmd->cdw10_bits.identify.cns;
2600 
2601 	if (subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY &&
2602 	    cns != SPDK_NVME_IDENTIFY_CTRLR) {
2603 		/* Discovery controllers only support Identify Controller */
2604 		goto invalid_cns;
2605 	}
2606 
2607 	switch (cns) {
2608 	case SPDK_NVME_IDENTIFY_NS:
2609 		return spdk_nvmf_ctrlr_identify_ns(ctrlr, cmd, rsp, req->data);
2610 	case SPDK_NVME_IDENTIFY_CTRLR:
2611 		return spdk_nvmf_ctrlr_identify_ctrlr(ctrlr, req->data);
2612 	case SPDK_NVME_IDENTIFY_ACTIVE_NS_LIST:
2613 		return nvmf_ctrlr_identify_active_ns_list(subsystem, cmd, rsp, req->data);
2614 	case SPDK_NVME_IDENTIFY_NS_ID_DESCRIPTOR_LIST:
2615 		return nvmf_ctrlr_identify_ns_id_descriptor_list(subsystem, cmd, rsp, req->data, req->length);
2616 	default:
2617 		goto invalid_cns;
2618 	}
2619 
2620 invalid_cns:
2621 	SPDK_INFOLOG(nvmf, "Identify command with unsupported CNS 0x%02x\n", cns);
2622 	rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2623 	rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2624 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2625 }
2626 
2627 static bool
2628 nvmf_qpair_abort_aer(struct spdk_nvmf_qpair *qpair, uint16_t cid)
2629 {
2630 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
2631 	struct spdk_nvmf_request *req;
2632 	int i;
2633 
2634 	if (!nvmf_qpair_is_admin_queue(qpair)) {
2635 		return false;
2636 	}
2637 
2638 	for (i = 0; i < ctrlr->nr_aer_reqs; i++) {
2639 		if (ctrlr->aer_req[i]->cmd->nvme_cmd.cid == cid) {
2640 			SPDK_DEBUGLOG(nvmf, "Aborting AER request\n");
2641 			req = ctrlr->aer_req[i];
2642 			ctrlr->aer_req[i] = NULL;
2643 			ctrlr->nr_aer_reqs--;
2644 
2645 			/* Move the last req to the aborting position for making aer_reqs
2646 			 * in continuous
2647 			 */
2648 			if (i < ctrlr->nr_aer_reqs) {
2649 				ctrlr->aer_req[i] = ctrlr->aer_req[ctrlr->nr_aer_reqs];
2650 				ctrlr->aer_req[ctrlr->nr_aer_reqs] = NULL;
2651 			}
2652 
2653 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
2654 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
2655 			_nvmf_request_complete(req);
2656 			return true;
2657 		}
2658 	}
2659 
2660 	return false;
2661 }
2662 
2663 static void
2664 nvmf_qpair_abort_request(struct spdk_nvmf_qpair *qpair, struct spdk_nvmf_request *req)
2665 {
2666 	uint16_t cid = req->cmd->nvme_cmd.cdw10_bits.abort.cid;
2667 
2668 	if (nvmf_qpair_abort_aer(qpair, cid)) {
2669 		SPDK_DEBUGLOG(nvmf, "abort ctrlr=%p sqid=%u cid=%u successful\n",
2670 			      qpair->ctrlr, qpair->qid, cid);
2671 		req->rsp->nvme_cpl.cdw0 &= ~1U; /* Command successfully aborted */
2672 
2673 		spdk_nvmf_request_complete(req);
2674 		return;
2675 	}
2676 
2677 	nvmf_transport_qpair_abort_request(qpair, req);
2678 }
2679 
2680 static void
2681 nvmf_ctrlr_abort_done(struct spdk_io_channel_iter *i, int status)
2682 {
2683 	struct spdk_nvmf_request *req = spdk_io_channel_iter_get_ctx(i);
2684 
2685 	if (status == 0) {
2686 		/* There was no qpair whose ID matches SQID of the abort command.
2687 		 * Hence call _nvmf_request_complete() here.
2688 		 */
2689 		_nvmf_request_complete(req);
2690 	}
2691 }
2692 
2693 static void
2694 nvmf_ctrlr_abort_on_pg(struct spdk_io_channel_iter *i)
2695 {
2696 	struct spdk_nvmf_request *req = spdk_io_channel_iter_get_ctx(i);
2697 	struct spdk_io_channel *ch = spdk_io_channel_iter_get_channel(i);
2698 	struct spdk_nvmf_poll_group *group = spdk_io_channel_get_ctx(ch);
2699 	uint16_t sqid = req->cmd->nvme_cmd.cdw10_bits.abort.sqid;
2700 	struct spdk_nvmf_qpair *qpair;
2701 
2702 	TAILQ_FOREACH(qpair, &group->qpairs, link) {
2703 		if (qpair->ctrlr == req->qpair->ctrlr && qpair->qid == sqid) {
2704 			/* Found the qpair */
2705 
2706 			nvmf_qpair_abort_request(qpair, req);
2707 
2708 			/* Return -1 for the status so the iteration across threads stops. */
2709 			spdk_for_each_channel_continue(i, -1);
2710 			return;
2711 		}
2712 	}
2713 
2714 	spdk_for_each_channel_continue(i, 0);
2715 }
2716 
2717 static int
2718 nvmf_ctrlr_abort(struct spdk_nvmf_request *req)
2719 {
2720 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
2721 
2722 	rsp->cdw0 = 1U; /* Command not aborted */
2723 	rsp->status.sct = SPDK_NVME_SCT_GENERIC;
2724 	rsp->status.sc = SPDK_NVME_SC_SUCCESS;
2725 
2726 	/* Send a message to each poll group, searching for this ctrlr, sqid, and command. */
2727 	spdk_for_each_channel(req->qpair->ctrlr->subsys->tgt,
2728 			      nvmf_ctrlr_abort_on_pg,
2729 			      req,
2730 			      nvmf_ctrlr_abort_done
2731 			     );
2732 
2733 	return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
2734 }
2735 
2736 int
2737 nvmf_ctrlr_abort_request(struct spdk_nvmf_request *req)
2738 {
2739 	struct spdk_nvmf_request *req_to_abort = req->req_to_abort;
2740 	struct spdk_bdev *bdev;
2741 	struct spdk_bdev_desc *desc;
2742 	struct spdk_io_channel *ch;
2743 	int rc;
2744 
2745 	assert(req_to_abort != NULL);
2746 
2747 	if (g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_ABORT].hdlr &&
2748 	    nvmf_qpair_is_admin_queue(req_to_abort->qpair)) {
2749 		return g_nvmf_custom_admin_cmd_hdlrs[SPDK_NVME_OPC_ABORT].hdlr(req);
2750 	}
2751 
2752 	rc = spdk_nvmf_request_get_bdev(req_to_abort->cmd->nvme_cmd.nsid, req_to_abort,
2753 					&bdev, &desc, &ch);
2754 	if (rc != 0) {
2755 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2756 	}
2757 
2758 	return spdk_nvmf_bdev_ctrlr_abort_cmd(bdev, desc, ch, req, req_to_abort);
2759 }
2760 
2761 static int
2762 get_features_generic(struct spdk_nvmf_request *req, uint32_t cdw0)
2763 {
2764 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
2765 
2766 	rsp->cdw0 = cdw0;
2767 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2768 }
2769 
2770 /* we have to use the typedef in the function declaration to appease astyle. */
2771 typedef enum spdk_nvme_path_status_code spdk_nvme_path_status_code_t;
2772 
2773 static spdk_nvme_path_status_code_t
2774 _nvme_ana_state_to_path_status(enum spdk_nvme_ana_state ana_state)
2775 {
2776 	switch (ana_state) {
2777 	case SPDK_NVME_ANA_INACCESSIBLE_STATE:
2778 		return SPDK_NVME_SC_ASYMMETRIC_ACCESS_INACCESSIBLE;
2779 	case SPDK_NVME_ANA_PERSISTENT_LOSS_STATE:
2780 		return SPDK_NVME_SC_ASYMMETRIC_ACCESS_PERSISTENT_LOSS;
2781 	case SPDK_NVME_ANA_CHANGE_STATE:
2782 		return SPDK_NVME_SC_ASYMMETRIC_ACCESS_TRANSITION;
2783 	default:
2784 		return SPDK_NVME_SC_INTERNAL_PATH_ERROR;
2785 	}
2786 }
2787 
2788 /* we have to use the typedef in the function declaration to appease astyle. */
2789 typedef enum spdk_nvme_ana_state spdk_nvme_ana_state_t;
2790 
2791 static spdk_nvme_ana_state_t
2792 nvmf_ctrlr_get_ana_state(struct spdk_nvmf_ctrlr *ctrlr, uint32_t nsid)
2793 {
2794 	struct spdk_nvmf_ns *ns;
2795 
2796 	/* We do not have NVM subsystem specific ANA state. Hence if NSID is either
2797 	 * SPDK_NVMF_GLOBAL_NS_TAG, invalid, or for inactive namespace, return
2798 	 * the optimized state.
2799 	 */
2800 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
2801 	if (ns == NULL) {
2802 		return SPDK_NVME_ANA_OPTIMIZED_STATE;
2803 	}
2804 
2805 	assert(ns->anagrpid - 1 < ctrlr->subsys->max_nsid);
2806 
2807 	return ctrlr->listener->ana_state[ns->anagrpid];
2808 }
2809 
2810 static int
2811 nvmf_ctrlr_get_features(struct spdk_nvmf_request *req)
2812 {
2813 	uint8_t feature;
2814 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2815 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2816 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
2817 	enum spdk_nvme_ana_state ana_state;
2818 
2819 	feature = cmd->cdw10_bits.get_features.fid;
2820 
2821 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2822 		/*
2823 		 * Features supported by Discovery controller
2824 		 */
2825 		switch (feature) {
2826 		case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
2827 			return get_features_generic(req, ctrlr->feat.keep_alive_timer.raw);
2828 		case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
2829 			return get_features_generic(req, ctrlr->feat.async_event_configuration.raw);
2830 		default:
2831 			SPDK_INFOLOG(nvmf, "Get Features command with unsupported feature ID 0x%02x\n", feature);
2832 			response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2833 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2834 		}
2835 	}
2836 	/*
2837 	 * Process Get Features command for non-discovery controller
2838 	 */
2839 	ana_state = nvmf_ctrlr_get_ana_state(ctrlr, cmd->nsid);
2840 	switch (ana_state) {
2841 	case SPDK_NVME_ANA_INACCESSIBLE_STATE:
2842 	case SPDK_NVME_ANA_PERSISTENT_LOSS_STATE:
2843 	case SPDK_NVME_ANA_CHANGE_STATE:
2844 		switch (feature) {
2845 		case SPDK_NVME_FEAT_ERROR_RECOVERY:
2846 		case SPDK_NVME_FEAT_WRITE_ATOMICITY:
2847 		case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
2848 		case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
2849 			response->status.sct = SPDK_NVME_SCT_PATH;
2850 			response->status.sc = _nvme_ana_state_to_path_status(ana_state);
2851 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2852 		default:
2853 			break;
2854 		}
2855 		break;
2856 	default:
2857 		break;
2858 	}
2859 
2860 	switch (feature) {
2861 	case SPDK_NVME_FEAT_ARBITRATION:
2862 		return get_features_generic(req, ctrlr->feat.arbitration.raw);
2863 	case SPDK_NVME_FEAT_POWER_MANAGEMENT:
2864 		return get_features_generic(req, ctrlr->feat.power_management.raw);
2865 	case SPDK_NVME_FEAT_TEMPERATURE_THRESHOLD:
2866 		return nvmf_ctrlr_get_features_temperature_threshold(req);
2867 	case SPDK_NVME_FEAT_ERROR_RECOVERY:
2868 		return get_features_generic(req, ctrlr->feat.error_recovery.raw);
2869 	case SPDK_NVME_FEAT_VOLATILE_WRITE_CACHE:
2870 		return get_features_generic(req, ctrlr->feat.volatile_write_cache.raw);
2871 	case SPDK_NVME_FEAT_NUMBER_OF_QUEUES:
2872 		return get_features_generic(req, ctrlr->feat.number_of_queues.raw);
2873 	case SPDK_NVME_FEAT_INTERRUPT_COALESCING:
2874 		return get_features_generic(req, ctrlr->feat.interrupt_coalescing.raw);
2875 	case SPDK_NVME_FEAT_INTERRUPT_VECTOR_CONFIGURATION:
2876 		return nvmf_ctrlr_get_features_interrupt_vector_configuration(req);
2877 	case SPDK_NVME_FEAT_WRITE_ATOMICITY:
2878 		return get_features_generic(req, ctrlr->feat.write_atomicity.raw);
2879 	case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
2880 		return get_features_generic(req, ctrlr->feat.async_event_configuration.raw);
2881 	case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
2882 		return get_features_generic(req, ctrlr->feat.keep_alive_timer.raw);
2883 	case SPDK_NVME_FEAT_HOST_IDENTIFIER:
2884 		return nvmf_ctrlr_get_features_host_identifier(req);
2885 	case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
2886 		return nvmf_ctrlr_get_features_reservation_notification_mask(req);
2887 	case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
2888 		return nvmf_ctrlr_get_features_reservation_persistence(req);
2889 	default:
2890 		SPDK_INFOLOG(nvmf, "Get Features command with unsupported feature ID 0x%02x\n", feature);
2891 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2892 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2893 	}
2894 }
2895 
2896 static int
2897 nvmf_ctrlr_set_features(struct spdk_nvmf_request *req)
2898 {
2899 	uint8_t feature, save;
2900 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
2901 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
2902 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
2903 	enum spdk_nvme_ana_state ana_state;
2904 	/*
2905 	 * Features are not saveable by the controller as indicated by
2906 	 * ONCS field of the Identify Controller data.
2907 	 * */
2908 	save = cmd->cdw10_bits.set_features.sv;
2909 	if (save) {
2910 		response->status.sc = SPDK_NVME_SC_FEATURE_ID_NOT_SAVEABLE;
2911 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
2912 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2913 	}
2914 
2915 	feature = cmd->cdw10_bits.set_features.fid;
2916 
2917 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
2918 		/*
2919 		 * Features supported by Discovery controller
2920 		 */
2921 		switch (feature) {
2922 		case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
2923 			return nvmf_ctrlr_set_features_keep_alive_timer(req);
2924 		case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
2925 			return nvmf_ctrlr_set_features_async_event_configuration(req);
2926 		default:
2927 			SPDK_INFOLOG(nvmf, "Set Features command with unsupported feature ID 0x%02x\n", feature);
2928 			response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2929 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2930 		}
2931 	}
2932 	/*
2933 	 * Process Set Features command for non-discovery controller
2934 	 */
2935 	ana_state = nvmf_ctrlr_get_ana_state(ctrlr, cmd->nsid);
2936 	switch (ana_state) {
2937 	case SPDK_NVME_ANA_INACCESSIBLE_STATE:
2938 	case SPDK_NVME_ANA_CHANGE_STATE:
2939 		if (cmd->nsid == SPDK_NVME_GLOBAL_NS_TAG) {
2940 			response->status.sct = SPDK_NVME_SCT_PATH;
2941 			response->status.sc = _nvme_ana_state_to_path_status(ana_state);
2942 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2943 		} else {
2944 			switch (feature) {
2945 			case SPDK_NVME_FEAT_ERROR_RECOVERY:
2946 			case SPDK_NVME_FEAT_WRITE_ATOMICITY:
2947 			case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
2948 			case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
2949 				response->status.sct = SPDK_NVME_SCT_PATH;
2950 				response->status.sc = _nvme_ana_state_to_path_status(ana_state);
2951 				return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2952 			default:
2953 				break;
2954 			}
2955 		}
2956 		break;
2957 	case SPDK_NVME_ANA_PERSISTENT_LOSS_STATE:
2958 		response->status.sct = SPDK_NVME_SCT_PATH;
2959 		response->status.sc = SPDK_NVME_SC_ASYMMETRIC_ACCESS_PERSISTENT_LOSS;
2960 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2961 	default:
2962 		break;
2963 	}
2964 
2965 	switch (feature) {
2966 	case SPDK_NVME_FEAT_ARBITRATION:
2967 		return nvmf_ctrlr_set_features_arbitration(req);
2968 	case SPDK_NVME_FEAT_POWER_MANAGEMENT:
2969 		return nvmf_ctrlr_set_features_power_management(req);
2970 	case SPDK_NVME_FEAT_TEMPERATURE_THRESHOLD:
2971 		return nvmf_ctrlr_set_features_temperature_threshold(req);
2972 	case SPDK_NVME_FEAT_ERROR_RECOVERY:
2973 		return nvmf_ctrlr_set_features_error_recovery(req);
2974 	case SPDK_NVME_FEAT_VOLATILE_WRITE_CACHE:
2975 		return nvmf_ctrlr_set_features_volatile_write_cache(req);
2976 	case SPDK_NVME_FEAT_NUMBER_OF_QUEUES:
2977 		return nvmf_ctrlr_set_features_number_of_queues(req);
2978 	case SPDK_NVME_FEAT_INTERRUPT_COALESCING:
2979 		response->status.sct = SPDK_NVME_SCT_COMMAND_SPECIFIC;
2980 		response->status.sc = SPDK_NVME_SC_FEATURE_NOT_CHANGEABLE;
2981 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
2982 	case SPDK_NVME_FEAT_WRITE_ATOMICITY:
2983 		return nvmf_ctrlr_set_features_write_atomicity(req);
2984 	case SPDK_NVME_FEAT_ASYNC_EVENT_CONFIGURATION:
2985 		return nvmf_ctrlr_set_features_async_event_configuration(req);
2986 	case SPDK_NVME_FEAT_KEEP_ALIVE_TIMER:
2987 		return nvmf_ctrlr_set_features_keep_alive_timer(req);
2988 	case SPDK_NVME_FEAT_HOST_IDENTIFIER:
2989 		return nvmf_ctrlr_set_features_host_identifier(req);
2990 	case SPDK_NVME_FEAT_HOST_RESERVE_MASK:
2991 		return nvmf_ctrlr_set_features_reservation_notification_mask(req);
2992 	case SPDK_NVME_FEAT_HOST_RESERVE_PERSIST:
2993 		return nvmf_ctrlr_set_features_reservation_persistence(req);
2994 	case SPDK_NVME_FEAT_HOST_BEHAVIOR_SUPPORT:
2995 		return nvmf_ctrlr_set_features_host_behavior_support(req);
2996 	default:
2997 		SPDK_INFOLOG(nvmf, "Set Features command with unsupported feature ID 0x%02x\n", feature);
2998 		response->status.sc = SPDK_NVME_SC_INVALID_FIELD;
2999 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3000 	}
3001 }
3002 
3003 static int
3004 nvmf_ctrlr_keep_alive(struct spdk_nvmf_request *req)
3005 {
3006 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
3007 
3008 	SPDK_DEBUGLOG(nvmf, "Keep Alive\n");
3009 	/*
3010 	 * To handle keep alive just clear or reset the
3011 	 * ctrlr based keep alive duration counter.
3012 	 * When added, a separate timer based process
3013 	 * will monitor if the time since last recorded
3014 	 * keep alive has exceeded the max duration and
3015 	 * take appropriate action.
3016 	 */
3017 	ctrlr->last_keep_alive_tick = spdk_get_ticks();
3018 
3019 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3020 }
3021 
3022 int
3023 nvmf_ctrlr_process_admin_cmd(struct spdk_nvmf_request *req)
3024 {
3025 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
3026 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3027 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
3028 	int rc;
3029 
3030 	if (ctrlr == NULL) {
3031 		SPDK_ERRLOG("Admin command sent before CONNECT\n");
3032 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3033 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3034 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3035 	}
3036 
3037 	if (ctrlr->vcprop.cc.bits.en != 1) {
3038 		SPDK_ERRLOG("Admin command sent to disabled controller\n");
3039 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3040 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3041 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3042 	}
3043 
3044 	if (req->data && spdk_nvme_opc_get_data_transfer(cmd->opc) == SPDK_NVME_DATA_CONTROLLER_TO_HOST) {
3045 		memset(req->data, 0, req->length);
3046 	}
3047 
3048 	if (ctrlr->subsys->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY) {
3049 		/* Discovery controllers only support these admin OPS. */
3050 		switch (cmd->opc) {
3051 		case SPDK_NVME_OPC_IDENTIFY:
3052 		case SPDK_NVME_OPC_GET_LOG_PAGE:
3053 		case SPDK_NVME_OPC_KEEP_ALIVE:
3054 		case SPDK_NVME_OPC_SET_FEATURES:
3055 		case SPDK_NVME_OPC_GET_FEATURES:
3056 		case SPDK_NVME_OPC_ASYNC_EVENT_REQUEST:
3057 			break;
3058 		default:
3059 			goto invalid_opcode;
3060 		}
3061 	}
3062 
3063 	/* Call a custom adm cmd handler if set. Aborts are handled in a different path (see nvmf_passthru_admin_cmd) */
3064 	if (g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].hdlr && cmd->opc != SPDK_NVME_OPC_ABORT) {
3065 		rc = g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].hdlr(req);
3066 		if (rc >= SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
3067 			/* The handler took care of this commmand */
3068 			return rc;
3069 		}
3070 	}
3071 
3072 	switch (cmd->opc) {
3073 	case SPDK_NVME_OPC_GET_LOG_PAGE:
3074 		return nvmf_ctrlr_get_log_page(req);
3075 	case SPDK_NVME_OPC_IDENTIFY:
3076 		return nvmf_ctrlr_identify(req);
3077 	case SPDK_NVME_OPC_ABORT:
3078 		return nvmf_ctrlr_abort(req);
3079 	case SPDK_NVME_OPC_GET_FEATURES:
3080 		return nvmf_ctrlr_get_features(req);
3081 	case SPDK_NVME_OPC_SET_FEATURES:
3082 		return nvmf_ctrlr_set_features(req);
3083 	case SPDK_NVME_OPC_ASYNC_EVENT_REQUEST:
3084 		return nvmf_ctrlr_async_event_request(req);
3085 	case SPDK_NVME_OPC_KEEP_ALIVE:
3086 		return nvmf_ctrlr_keep_alive(req);
3087 
3088 	case SPDK_NVME_OPC_CREATE_IO_SQ:
3089 	case SPDK_NVME_OPC_CREATE_IO_CQ:
3090 	case SPDK_NVME_OPC_DELETE_IO_SQ:
3091 	case SPDK_NVME_OPC_DELETE_IO_CQ:
3092 		/* Create and Delete I/O CQ/SQ not allowed in NVMe-oF */
3093 		goto invalid_opcode;
3094 
3095 	default:
3096 		goto invalid_opcode;
3097 	}
3098 
3099 invalid_opcode:
3100 	SPDK_INFOLOG(nvmf, "Unsupported admin opcode 0x%x\n", cmd->opc);
3101 	response->status.sct = SPDK_NVME_SCT_GENERIC;
3102 	response->status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3103 	return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3104 }
3105 
3106 static int
3107 nvmf_ctrlr_process_fabrics_cmd(struct spdk_nvmf_request *req)
3108 {
3109 	struct spdk_nvmf_qpair *qpair = req->qpair;
3110 	struct spdk_nvmf_capsule_cmd *cap_hdr;
3111 
3112 	cap_hdr = &req->cmd->nvmf_cmd;
3113 
3114 	if (qpair->ctrlr == NULL) {
3115 		/* No ctrlr established yet; the only valid command is Connect */
3116 		if (cap_hdr->fctype == SPDK_NVMF_FABRIC_COMMAND_CONNECT) {
3117 			return nvmf_ctrlr_cmd_connect(req);
3118 		} else {
3119 			SPDK_DEBUGLOG(nvmf, "Got fctype 0x%x, expected Connect\n",
3120 				      cap_hdr->fctype);
3121 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3122 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3123 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3124 		}
3125 	} else if (nvmf_qpair_is_admin_queue(qpair)) {
3126 		/*
3127 		 * Controller session is established, and this is an admin queue.
3128 		 * Disallow Connect and allow other fabrics commands.
3129 		 */
3130 		switch (cap_hdr->fctype) {
3131 		case SPDK_NVMF_FABRIC_COMMAND_PROPERTY_SET:
3132 			return nvmf_property_set(req);
3133 		case SPDK_NVMF_FABRIC_COMMAND_PROPERTY_GET:
3134 			return nvmf_property_get(req);
3135 		default:
3136 			SPDK_DEBUGLOG(nvmf, "unknown fctype 0x%02x\n",
3137 				      cap_hdr->fctype);
3138 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3139 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3140 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3141 		}
3142 	} else {
3143 		/* Controller session is established, and this is an I/O queue */
3144 		/* For now, no I/O-specific Fabrics commands are implemented (other than Connect) */
3145 		SPDK_DEBUGLOG(nvmf, "Unexpected I/O fctype 0x%x\n", cap_hdr->fctype);
3146 		req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3147 		req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3148 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3149 	}
3150 }
3151 
3152 static inline int
3153 nvmf_ctrlr_async_event_notification(struct spdk_nvmf_ctrlr *ctrlr,
3154 				    union spdk_nvme_async_event_completion *event)
3155 {
3156 	struct spdk_nvmf_request *req;
3157 	struct spdk_nvme_cpl *rsp;
3158 
3159 	assert(ctrlr->nr_aer_reqs > 0);
3160 
3161 	req = ctrlr->aer_req[--ctrlr->nr_aer_reqs];
3162 	rsp = &req->rsp->nvme_cpl;
3163 
3164 	rsp->cdw0 = event->raw;
3165 
3166 	_nvmf_request_complete(req);
3167 	ctrlr->aer_req[ctrlr->nr_aer_reqs] = NULL;
3168 
3169 	return 0;
3170 }
3171 
3172 static inline void
3173 nvmf_ctrlr_queue_pending_async_event(struct spdk_nvmf_ctrlr *ctrlr,
3174 				     union spdk_nvme_async_event_completion *event)
3175 {
3176 	struct spdk_nvmf_async_event_completion *nvmf_event;
3177 
3178 	nvmf_event = calloc(1, sizeof(*nvmf_event));
3179 	if (!nvmf_event) {
3180 		SPDK_ERRLOG("Alloc nvmf event failed, ignore the event\n");
3181 		return;
3182 	}
3183 	nvmf_event->event.raw = event->raw;
3184 	STAILQ_INSERT_TAIL(&ctrlr->async_events, nvmf_event, link);
3185 }
3186 
3187 int
3188 nvmf_ctrlr_async_event_ns_notice(struct spdk_nvmf_ctrlr *ctrlr)
3189 {
3190 	union spdk_nvme_async_event_completion event = {0};
3191 
3192 	/* Users may disable the event notification */
3193 	if (!ctrlr->feat.async_event_configuration.bits.ns_attr_notice) {
3194 		return 0;
3195 	}
3196 
3197 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_NS_ATTR_CHANGE_MASK_BIT)) {
3198 		return 0;
3199 	}
3200 
3201 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_NOTICE;
3202 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_NS_ATTR_CHANGED;
3203 	event.bits.log_page_identifier = SPDK_NVME_LOG_CHANGED_NS_LIST;
3204 
3205 	/* If there is no outstanding AER request, queue the event.  Then
3206 	 * if an AER is later submitted, this event can be sent as a
3207 	 * response.
3208 	 */
3209 	if (ctrlr->nr_aer_reqs == 0) {
3210 		nvmf_ctrlr_queue_pending_async_event(ctrlr, &event);
3211 		return 0;
3212 	}
3213 
3214 	return nvmf_ctrlr_async_event_notification(ctrlr, &event);
3215 }
3216 
3217 int
3218 nvmf_ctrlr_async_event_ana_change_notice(struct spdk_nvmf_ctrlr *ctrlr)
3219 {
3220 	union spdk_nvme_async_event_completion event = {0};
3221 
3222 	/* Users may disable the event notification */
3223 	if (!ctrlr->feat.async_event_configuration.bits.ana_change_notice) {
3224 		return 0;
3225 	}
3226 
3227 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_ANA_CHANGE_MASK_BIT)) {
3228 		return 0;
3229 	}
3230 
3231 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_NOTICE;
3232 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_ANA_CHANGE;
3233 	event.bits.log_page_identifier = SPDK_NVME_LOG_ASYMMETRIC_NAMESPACE_ACCESS;
3234 
3235 	/* If there is no outstanding AER request, queue the event.  Then
3236 	 * if an AER is later submitted, this event can be sent as a
3237 	 * response.
3238 	 */
3239 	if (ctrlr->nr_aer_reqs == 0) {
3240 		nvmf_ctrlr_queue_pending_async_event(ctrlr, &event);
3241 		return 0;
3242 	}
3243 
3244 	return nvmf_ctrlr_async_event_notification(ctrlr, &event);
3245 }
3246 
3247 void
3248 nvmf_ctrlr_async_event_reservation_notification(struct spdk_nvmf_ctrlr *ctrlr)
3249 {
3250 	union spdk_nvme_async_event_completion event = {0};
3251 
3252 	if (!ctrlr->num_avail_log_pages) {
3253 		return;
3254 	}
3255 
3256 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_RESERVATION_LOG_AVAIL_MASK_BIT)) {
3257 		return;
3258 	}
3259 
3260 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_IO;
3261 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_RESERVATION_LOG_AVAIL;
3262 	event.bits.log_page_identifier = SPDK_NVME_LOG_RESERVATION_NOTIFICATION;
3263 
3264 	/* If there is no outstanding AER request, queue the event.  Then
3265 	 * if an AER is later submitted, this event can be sent as a
3266 	 * response.
3267 	 */
3268 	if (ctrlr->nr_aer_reqs == 0) {
3269 		nvmf_ctrlr_queue_pending_async_event(ctrlr, &event);
3270 		return;
3271 	}
3272 
3273 	nvmf_ctrlr_async_event_notification(ctrlr, &event);
3274 }
3275 
3276 int
3277 nvmf_ctrlr_async_event_discovery_log_change_notice(struct spdk_nvmf_ctrlr *ctrlr)
3278 {
3279 	union spdk_nvme_async_event_completion event = {0};
3280 
3281 	/* Users may disable the event notification manually or
3282 	 * it may not be enabled due to keep alive timeout
3283 	 * not being set in connect command to discovery controller.
3284 	 */
3285 	if (!ctrlr->feat.async_event_configuration.bits.discovery_log_change_notice) {
3286 		return 0;
3287 	}
3288 
3289 	if (!nvmf_ctrlr_mask_aen(ctrlr, SPDK_NVME_ASYNC_EVENT_DISCOVERY_LOG_CHANGE_MASK_BIT)) {
3290 		return 0;
3291 	}
3292 
3293 	event.bits.async_event_type = SPDK_NVME_ASYNC_EVENT_TYPE_NOTICE;
3294 	event.bits.async_event_info = SPDK_NVME_ASYNC_EVENT_DISCOVERY_LOG_CHANGE;
3295 	event.bits.log_page_identifier = SPDK_NVME_LOG_DISCOVERY;
3296 
3297 	/* If there is no outstanding AER request, queue the event.  Then
3298 	 * if an AER is later submitted, this event can be sent as a
3299 	 * response.
3300 	 */
3301 	if (ctrlr->nr_aer_reqs == 0) {
3302 		nvmf_ctrlr_queue_pending_async_event(ctrlr, &event);
3303 		return 0;
3304 	}
3305 
3306 	return nvmf_ctrlr_async_event_notification(ctrlr, &event);
3307 }
3308 
3309 void
3310 nvmf_qpair_free_aer(struct spdk_nvmf_qpair *qpair)
3311 {
3312 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
3313 	int i;
3314 
3315 	if (!nvmf_qpair_is_admin_queue(qpair)) {
3316 		return;
3317 	}
3318 
3319 	for (i = 0; i < ctrlr->nr_aer_reqs; i++) {
3320 		spdk_nvmf_request_free(ctrlr->aer_req[i]);
3321 		ctrlr->aer_req[i] = NULL;
3322 	}
3323 
3324 	ctrlr->nr_aer_reqs = 0;
3325 }
3326 
3327 void
3328 nvmf_ctrlr_abort_aer(struct spdk_nvmf_ctrlr *ctrlr)
3329 {
3330 	struct spdk_nvmf_request *req;
3331 	int i;
3332 
3333 	if (!ctrlr->nr_aer_reqs) {
3334 		return;
3335 	}
3336 
3337 	for (i = 0; i < ctrlr->nr_aer_reqs; i++) {
3338 		req = ctrlr->aer_req[i];
3339 
3340 		req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3341 		req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_ABORTED_BY_REQUEST;
3342 		_nvmf_request_complete(req);
3343 
3344 		ctrlr->aer_req[i] = NULL;
3345 	}
3346 
3347 	ctrlr->nr_aer_reqs = 0;
3348 }
3349 
3350 static void
3351 _nvmf_ctrlr_add_reservation_log(void *ctx)
3352 {
3353 	struct spdk_nvmf_reservation_log *log = (struct spdk_nvmf_reservation_log *)ctx;
3354 	struct spdk_nvmf_ctrlr *ctrlr = log->ctrlr;
3355 
3356 	ctrlr->log_page_count++;
3357 
3358 	/* Maximum number of queued log pages is 255 */
3359 	if (ctrlr->num_avail_log_pages == 0xff) {
3360 		struct spdk_nvmf_reservation_log *entry;
3361 		entry = TAILQ_LAST(&ctrlr->log_head, log_page_head);
3362 		entry->log.log_page_count = ctrlr->log_page_count;
3363 		free(log);
3364 		return;
3365 	}
3366 
3367 	log->log.log_page_count = ctrlr->log_page_count;
3368 	log->log.num_avail_log_pages = ctrlr->num_avail_log_pages++;
3369 	TAILQ_INSERT_TAIL(&ctrlr->log_head, log, link);
3370 
3371 	nvmf_ctrlr_async_event_reservation_notification(ctrlr);
3372 }
3373 
3374 void
3375 nvmf_ctrlr_reservation_notice_log(struct spdk_nvmf_ctrlr *ctrlr,
3376 				  struct spdk_nvmf_ns *ns,
3377 				  enum spdk_nvme_reservation_notification_log_page_type type)
3378 {
3379 	struct spdk_nvmf_reservation_log *log;
3380 
3381 	switch (type) {
3382 	case SPDK_NVME_RESERVATION_LOG_PAGE_EMPTY:
3383 		return;
3384 	case SPDK_NVME_REGISTRATION_PREEMPTED:
3385 		if (ns->mask & SPDK_NVME_REGISTRATION_PREEMPTED_MASK) {
3386 			return;
3387 		}
3388 		break;
3389 	case SPDK_NVME_RESERVATION_RELEASED:
3390 		if (ns->mask & SPDK_NVME_RESERVATION_RELEASED_MASK) {
3391 			return;
3392 		}
3393 		break;
3394 	case SPDK_NVME_RESERVATION_PREEMPTED:
3395 		if (ns->mask & SPDK_NVME_RESERVATION_PREEMPTED_MASK) {
3396 			return;
3397 		}
3398 		break;
3399 	default:
3400 		return;
3401 	}
3402 
3403 	log = calloc(1, sizeof(*log));
3404 	if (!log) {
3405 		SPDK_ERRLOG("Alloc log page failed, ignore the log\n");
3406 		return;
3407 	}
3408 	log->ctrlr = ctrlr;
3409 	log->log.type = type;
3410 	log->log.nsid = ns->nsid;
3411 
3412 	spdk_thread_send_msg(ctrlr->thread, _nvmf_ctrlr_add_reservation_log, log);
3413 }
3414 
3415 /* Check from subsystem poll group's namespace information data structure */
3416 static bool
3417 nvmf_ns_info_ctrlr_is_registrant(struct spdk_nvmf_subsystem_pg_ns_info *ns_info,
3418 				 struct spdk_nvmf_ctrlr *ctrlr)
3419 {
3420 	uint32_t i;
3421 
3422 	for (i = 0; i < SPDK_NVMF_MAX_NUM_REGISTRANTS; i++) {
3423 		if (!spdk_uuid_compare(&ns_info->reg_hostid[i], &ctrlr->hostid)) {
3424 			return true;
3425 		}
3426 	}
3427 
3428 	return false;
3429 }
3430 
3431 /*
3432  * Check the NVMe command is permitted or not for current controller(Host).
3433  */
3434 static int
3435 nvmf_ns_reservation_request_check(struct spdk_nvmf_subsystem_pg_ns_info *ns_info,
3436 				  struct spdk_nvmf_ctrlr *ctrlr,
3437 				  struct spdk_nvmf_request *req)
3438 {
3439 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3440 	enum spdk_nvme_reservation_type rtype = ns_info->rtype;
3441 	uint8_t status = SPDK_NVME_SC_SUCCESS;
3442 	uint8_t racqa;
3443 	bool is_registrant;
3444 
3445 	/* No valid reservation */
3446 	if (!rtype) {
3447 		return 0;
3448 	}
3449 
3450 	is_registrant = nvmf_ns_info_ctrlr_is_registrant(ns_info, ctrlr);
3451 	/* All registrants type and current ctrlr is a valid registrant */
3452 	if ((rtype == SPDK_NVME_RESERVE_WRITE_EXCLUSIVE_ALL_REGS ||
3453 	     rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_ALL_REGS) && is_registrant) {
3454 		return 0;
3455 	} else if (!spdk_uuid_compare(&ns_info->holder_id, &ctrlr->hostid)) {
3456 		return 0;
3457 	}
3458 
3459 	/* Non-holder for current controller */
3460 	switch (cmd->opc) {
3461 	case SPDK_NVME_OPC_READ:
3462 	case SPDK_NVME_OPC_COMPARE:
3463 		if (rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS) {
3464 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3465 			goto exit;
3466 		}
3467 		if ((rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_REG_ONLY ||
3468 		     rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_ALL_REGS) && !is_registrant) {
3469 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3470 		}
3471 		break;
3472 	case SPDK_NVME_OPC_FLUSH:
3473 	case SPDK_NVME_OPC_WRITE:
3474 	case SPDK_NVME_OPC_WRITE_UNCORRECTABLE:
3475 	case SPDK_NVME_OPC_WRITE_ZEROES:
3476 	case SPDK_NVME_OPC_DATASET_MANAGEMENT:
3477 		if (rtype == SPDK_NVME_RESERVE_WRITE_EXCLUSIVE ||
3478 		    rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS) {
3479 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3480 			goto exit;
3481 		}
3482 		if (!is_registrant) {
3483 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3484 		}
3485 		break;
3486 	case SPDK_NVME_OPC_RESERVATION_ACQUIRE:
3487 		racqa = cmd->cdw10_bits.resv_acquire.racqa;
3488 		if (racqa == SPDK_NVME_RESERVE_ACQUIRE) {
3489 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3490 			goto exit;
3491 		}
3492 		if (!is_registrant) {
3493 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3494 		}
3495 		break;
3496 	case SPDK_NVME_OPC_RESERVATION_RELEASE:
3497 		if (!is_registrant) {
3498 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3499 		}
3500 		break;
3501 	default:
3502 		break;
3503 	}
3504 
3505 exit:
3506 	req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3507 	req->rsp->nvme_cpl.status.sc = status;
3508 	if (status == SPDK_NVME_SC_RESERVATION_CONFLICT) {
3509 		return -EPERM;
3510 	}
3511 
3512 	return 0;
3513 }
3514 
3515 static int
3516 nvmf_ctrlr_process_io_fused_cmd(struct spdk_nvmf_request *req, struct spdk_bdev *bdev,
3517 				struct spdk_bdev_desc *desc, struct spdk_io_channel *ch)
3518 {
3519 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3520 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
3521 	struct spdk_nvmf_request *first_fused_req = req->qpair->first_fused_req;
3522 	int rc;
3523 
3524 	if (cmd->fuse == SPDK_NVME_CMD_FUSE_FIRST) {
3525 		/* first fused operation (should be compare) */
3526 		if (first_fused_req != NULL) {
3527 			struct spdk_nvme_cpl *fused_response = &first_fused_req->rsp->nvme_cpl;
3528 
3529 			SPDK_ERRLOG("Wrong sequence of fused operations\n");
3530 
3531 			/* abort req->qpair->first_fused_request and continue with new fused command */
3532 			fused_response->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3533 			fused_response->status.sct = SPDK_NVME_SCT_GENERIC;
3534 			_nvmf_request_complete(first_fused_req);
3535 		} else if (cmd->opc != SPDK_NVME_OPC_COMPARE) {
3536 			SPDK_ERRLOG("Wrong op code of fused operations\n");
3537 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3538 			rsp->status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3539 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3540 		}
3541 
3542 		req->qpair->first_fused_req = req;
3543 		return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
3544 	} else if (cmd->fuse == SPDK_NVME_CMD_FUSE_SECOND) {
3545 		/* second fused operation (should be write) */
3546 		if (first_fused_req == NULL) {
3547 			SPDK_ERRLOG("Wrong sequence of fused operations\n");
3548 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3549 			rsp->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3550 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3551 		} else if (cmd->opc != SPDK_NVME_OPC_WRITE) {
3552 			struct spdk_nvme_cpl *fused_response = &first_fused_req->rsp->nvme_cpl;
3553 
3554 			SPDK_ERRLOG("Wrong op code of fused operations\n");
3555 
3556 			/* abort req->qpair->first_fused_request and fail current command */
3557 			fused_response->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3558 			fused_response->status.sct = SPDK_NVME_SCT_GENERIC;
3559 			_nvmf_request_complete(first_fused_req);
3560 
3561 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3562 			rsp->status.sc = SPDK_NVME_SC_INVALID_OPCODE;
3563 			req->qpair->first_fused_req = NULL;
3564 			return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3565 		}
3566 
3567 		/* save request of first command to generate response later */
3568 		req->first_fused_req = first_fused_req;
3569 		req->qpair->first_fused_req = NULL;
3570 	} else {
3571 		SPDK_ERRLOG("Invalid fused command fuse field.\n");
3572 		rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3573 		rsp->status.sc = SPDK_NVME_SC_INVALID_FIELD;
3574 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3575 	}
3576 
3577 	rc = nvmf_bdev_ctrlr_compare_and_write_cmd(bdev, desc, ch, req->first_fused_req, req);
3578 
3579 	if (rc == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
3580 		if (spdk_nvme_cpl_is_error(rsp)) {
3581 			struct spdk_nvme_cpl *fused_response = &first_fused_req->rsp->nvme_cpl;
3582 
3583 			fused_response->status = rsp->status;
3584 			rsp->status.sct = SPDK_NVME_SCT_GENERIC;
3585 			rsp->status.sc = SPDK_NVME_SC_ABORTED_FAILED_FUSED;
3586 			/* Complete first of fused commands. Second will be completed by upper layer */
3587 			_nvmf_request_complete(first_fused_req);
3588 			req->first_fused_req = NULL;
3589 		}
3590 	}
3591 
3592 	return rc;
3593 }
3594 
3595 bool
3596 nvmf_ctrlr_use_zcopy(struct spdk_nvmf_request *req)
3597 {
3598 	struct spdk_nvmf_ns *ns;
3599 
3600 	req->zcopy_phase = NVMF_ZCOPY_PHASE_NONE;
3601 
3602 	if (nvmf_qpair_is_admin_queue(req->qpair)) {
3603 		/* Admin queue */
3604 		return false;
3605 	}
3606 
3607 	if ((req->cmd->nvme_cmd.opc != SPDK_NVME_OPC_WRITE) &&
3608 	    (req->cmd->nvme_cmd.opc != SPDK_NVME_OPC_READ)) {
3609 		/* Not a READ or WRITE command */
3610 		return false;
3611 	}
3612 
3613 	if (req->cmd->nvme_cmd.fuse != SPDK_NVME_CMD_FUSE_NONE) {
3614 		/* Fused commands dont use zcopy buffers */
3615 		return false;
3616 	}
3617 
3618 	ns = _nvmf_subsystem_get_ns(req->qpair->ctrlr->subsys, req->cmd->nvme_cmd.nsid);
3619 	if (ns == NULL || ns->bdev == NULL || !ns->zcopy) {
3620 		return false;
3621 	}
3622 
3623 	req->zcopy_phase = NVMF_ZCOPY_PHASE_INIT;
3624 	return true;
3625 }
3626 
3627 /* If this function returns a non-zero value the request
3628  * reverts to using SPDK buffers
3629  */
3630 int
3631 spdk_nvmf_request_zcopy_start(struct spdk_nvmf_request *req)
3632 {
3633 	struct spdk_nvmf_qpair *qpair = req->qpair;
3634 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
3635 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
3636 	uint32_t nsid;
3637 	struct spdk_bdev *bdev;
3638 	struct spdk_bdev_desc *desc;
3639 	struct spdk_io_channel *ch;
3640 	int rc;
3641 
3642 	if (!qpair->ctrlr) {
3643 		goto end;
3644 	}
3645 
3646 	if (qpair->group->sgroups == NULL) {
3647 		goto end;
3648 	}
3649 
3650 	rc = spdk_nvmf_request_get_bdev(req->cmd->nvme_cmd.nsid, req,
3651 					&bdev, &desc, &ch);
3652 	if (rc != 0) {
3653 		goto end;
3654 	}
3655 
3656 	if (ch == NULL) {
3657 		goto end;
3658 	}
3659 
3660 	nsid = req->cmd->nvme_cmd.nsid;
3661 	sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
3662 	ns_info = &sgroup->ns_info[nsid - 1];
3663 	if (ns_info->state != SPDK_NVMF_SUBSYSTEM_ACTIVE) {
3664 		goto end;
3665 	}
3666 
3667 	if (qpair->state != SPDK_NVMF_QPAIR_ACTIVE) {
3668 		goto end;
3669 	}
3670 
3671 	/* Set iovcnt to be the maximum number of
3672 	 * iovs that the ZCOPY can use
3673 	 */
3674 	req->iovcnt = NVMF_REQ_MAX_BUFFERS;
3675 	TAILQ_INSERT_TAIL(&qpair->outstanding, req, link);
3676 	rc = nvmf_bdev_ctrlr_start_zcopy(bdev, desc, ch, req);
3677 	if (rc == 0) {
3678 		ns_info->io_outstanding++;
3679 		return 0;
3680 	}
3681 	TAILQ_REMOVE(&qpair->outstanding, req, link);
3682 
3683 end:
3684 	/* An error occurred, the subsystem is paused, or the qpair is not active.
3685 	 * Revert to using SPDK buffers
3686 	 */
3687 	req->zcopy_phase = NVMF_ZCOPY_PHASE_NONE;
3688 	return -1;
3689 }
3690 
3691 int
3692 spdk_nvmf_request_zcopy_end(struct spdk_nvmf_request *req, bool commit)
3693 {
3694 	req->zcopy_phase = NVMF_ZCOPY_PHASE_END_PENDING;
3695 	return nvmf_bdev_ctrlr_end_zcopy(req, commit);
3696 }
3697 
3698 int
3699 nvmf_ctrlr_process_io_cmd(struct spdk_nvmf_request *req)
3700 {
3701 	uint32_t nsid;
3702 	struct spdk_nvmf_ns *ns;
3703 	struct spdk_bdev *bdev;
3704 	struct spdk_bdev_desc *desc;
3705 	struct spdk_io_channel *ch;
3706 	struct spdk_nvmf_poll_group *group = req->qpair->group;
3707 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
3708 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3709 	struct spdk_nvme_cpl *response = &req->rsp->nvme_cpl;
3710 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
3711 	enum spdk_nvme_ana_state ana_state;
3712 
3713 	/* pre-set response details for this command */
3714 	response->status.sc = SPDK_NVME_SC_SUCCESS;
3715 	nsid = cmd->nsid;
3716 
3717 	if (spdk_unlikely(ctrlr == NULL)) {
3718 		SPDK_ERRLOG("I/O command sent before CONNECT\n");
3719 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3720 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3721 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3722 	}
3723 
3724 	if (spdk_unlikely(ctrlr->vcprop.cc.bits.en != 1)) {
3725 		SPDK_ERRLOG("I/O command sent to disabled controller\n");
3726 		response->status.sct = SPDK_NVME_SCT_GENERIC;
3727 		response->status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
3728 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3729 	}
3730 
3731 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
3732 	if (ns == NULL || ns->bdev == NULL) {
3733 		SPDK_DEBUGLOG(nvmf, "Unsuccessful query for nsid %u\n", cmd->nsid);
3734 		response->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
3735 		response->status.dnr = 1;
3736 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3737 	}
3738 
3739 	assert(ns->anagrpid - 1 < ctrlr->subsys->max_nsid);
3740 
3741 	ana_state = ctrlr->listener->ana_state[ns->anagrpid - 1];
3742 	if (spdk_unlikely(ana_state != SPDK_NVME_ANA_OPTIMIZED_STATE &&
3743 			  ana_state != SPDK_NVME_ANA_NON_OPTIMIZED_STATE)) {
3744 		SPDK_DEBUGLOG(nvmf, "Fail I/O command due to ANA state %d\n",
3745 			      ana_state);
3746 		response->status.sct = SPDK_NVME_SCT_PATH;
3747 		response->status.sc = _nvme_ana_state_to_path_status(ana_state);
3748 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3749 	}
3750 
3751 	/* scan-build falsely reporting dereference of null pointer */
3752 	assert(group != NULL && group->sgroups != NULL);
3753 	ns_info = &group->sgroups[ctrlr->subsys->id].ns_info[nsid - 1];
3754 	if (nvmf_ns_reservation_request_check(ns_info, ctrlr, req)) {
3755 		SPDK_DEBUGLOG(nvmf, "Reservation Conflict for nsid %u, opcode %u\n",
3756 			      cmd->nsid, cmd->opc);
3757 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
3758 	}
3759 
3760 	bdev = ns->bdev;
3761 	desc = ns->desc;
3762 	ch = ns_info->channel;
3763 
3764 	if (spdk_unlikely(cmd->fuse & SPDK_NVME_CMD_FUSE_MASK)) {
3765 		return nvmf_ctrlr_process_io_fused_cmd(req, bdev, desc, ch);
3766 	} else if (spdk_unlikely(req->qpair->first_fused_req != NULL)) {
3767 		struct spdk_nvme_cpl *fused_response = &req->qpair->first_fused_req->rsp->nvme_cpl;
3768 
3769 		SPDK_ERRLOG("Expected second of fused commands - failing first of fused commands\n");
3770 
3771 		/* abort req->qpair->first_fused_request and continue with new command */
3772 		fused_response->status.sc = SPDK_NVME_SC_ABORTED_MISSING_FUSED;
3773 		fused_response->status.sct = SPDK_NVME_SCT_GENERIC;
3774 		_nvmf_request_complete(req->qpair->first_fused_req);
3775 		req->qpair->first_fused_req = NULL;
3776 	}
3777 
3778 	switch (cmd->opc) {
3779 	case SPDK_NVME_OPC_READ:
3780 		return nvmf_bdev_ctrlr_read_cmd(bdev, desc, ch, req);
3781 	case SPDK_NVME_OPC_WRITE:
3782 		return nvmf_bdev_ctrlr_write_cmd(bdev, desc, ch, req);
3783 	case SPDK_NVME_OPC_COMPARE:
3784 		return nvmf_bdev_ctrlr_compare_cmd(bdev, desc, ch, req);
3785 	case SPDK_NVME_OPC_WRITE_ZEROES:
3786 		return nvmf_bdev_ctrlr_write_zeroes_cmd(bdev, desc, ch, req);
3787 	case SPDK_NVME_OPC_FLUSH:
3788 		return nvmf_bdev_ctrlr_flush_cmd(bdev, desc, ch, req);
3789 	case SPDK_NVME_OPC_DATASET_MANAGEMENT:
3790 		return nvmf_bdev_ctrlr_dsm_cmd(bdev, desc, ch, req);
3791 	case SPDK_NVME_OPC_RESERVATION_REGISTER:
3792 	case SPDK_NVME_OPC_RESERVATION_ACQUIRE:
3793 	case SPDK_NVME_OPC_RESERVATION_RELEASE:
3794 	case SPDK_NVME_OPC_RESERVATION_REPORT:
3795 		spdk_thread_send_msg(ctrlr->subsys->thread, nvmf_ns_reservation_request, req);
3796 		return SPDK_NVMF_REQUEST_EXEC_STATUS_ASYNCHRONOUS;
3797 	default:
3798 		return nvmf_bdev_ctrlr_nvme_passthru_io(bdev, desc, ch, req);
3799 	}
3800 }
3801 
3802 static void
3803 nvmf_qpair_request_cleanup(struct spdk_nvmf_qpair *qpair)
3804 {
3805 	if (qpair->state == SPDK_NVMF_QPAIR_DEACTIVATING) {
3806 		assert(qpair->state_cb != NULL);
3807 
3808 		if (TAILQ_EMPTY(&qpair->outstanding)) {
3809 			qpair->state_cb(qpair->state_cb_arg, 0);
3810 		}
3811 	}
3812 }
3813 
3814 int
3815 spdk_nvmf_request_free(struct spdk_nvmf_request *req)
3816 {
3817 	struct spdk_nvmf_qpair *qpair = req->qpair;
3818 
3819 	TAILQ_REMOVE(&qpair->outstanding, req, link);
3820 	if (nvmf_transport_req_free(req)) {
3821 		SPDK_ERRLOG("Unable to free transport level request resources.\n");
3822 	}
3823 
3824 	nvmf_qpair_request_cleanup(qpair);
3825 
3826 	return 0;
3827 }
3828 
3829 static void
3830 _nvmf_request_complete(void *ctx)
3831 {
3832 	struct spdk_nvmf_request *req = ctx;
3833 	struct spdk_nvme_cpl *rsp = &req->rsp->nvme_cpl;
3834 	struct spdk_nvmf_qpair *qpair;
3835 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
3836 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
3837 	bool is_aer = false;
3838 	uint32_t nsid;
3839 	bool paused;
3840 	uint8_t opcode;
3841 
3842 	rsp->sqid = 0;
3843 	rsp->status.p = 0;
3844 	rsp->cid = req->cmd->nvme_cmd.cid;
3845 	nsid = req->cmd->nvme_cmd.nsid;
3846 	opcode = req->cmd->nvmf_cmd.opcode;
3847 
3848 	qpair = req->qpair;
3849 	if (qpair->ctrlr) {
3850 		sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
3851 		assert(sgroup != NULL);
3852 		is_aer = req->cmd->nvme_cmd.opc == SPDK_NVME_OPC_ASYNC_EVENT_REQUEST;
3853 
3854 		/*
3855 		 * Set the crd value.
3856 		 * If the the IO has any error, and dnr (DoNotRetry) is not 1,
3857 		 * and ACRE is enabled, we will set the crd to 1 to select the first CRDT.
3858 		 */
3859 		if (spdk_nvme_cpl_is_error(rsp) &&
3860 		    rsp->status.dnr == 0 &&
3861 		    qpair->ctrlr->acre_enabled) {
3862 			rsp->status.crd = 1;
3863 		}
3864 	} else if (spdk_unlikely(nvmf_request_is_fabric_connect(req))) {
3865 		sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
3866 	}
3867 
3868 	if (SPDK_DEBUGLOG_FLAG_ENABLED("nvmf")) {
3869 		spdk_nvme_print_completion(qpair->qid, rsp);
3870 	}
3871 
3872 	switch (req->zcopy_phase) {
3873 	case NVMF_ZCOPY_PHASE_NONE:
3874 		TAILQ_REMOVE(&qpair->outstanding, req, link);
3875 		break;
3876 	case NVMF_ZCOPY_PHASE_INIT:
3877 		if (spdk_unlikely(spdk_nvme_cpl_is_error(rsp))) {
3878 			/* The START failed or was aborted so revert to a normal IO */
3879 			req->zcopy_phase = NVMF_ZCOPY_PHASE_INIT_FAILED;
3880 			TAILQ_REMOVE(&qpair->outstanding, req, link);
3881 		} else {
3882 			req->zcopy_phase = NVMF_ZCOPY_PHASE_EXECUTE;
3883 		}
3884 		break;
3885 	case NVMF_ZCOPY_PHASE_EXECUTE:
3886 		break;
3887 	case NVMF_ZCOPY_PHASE_END_PENDING:
3888 		TAILQ_REMOVE(&qpair->outstanding, req, link);
3889 		req->zcopy_phase = NVMF_ZCOPY_PHASE_COMPLETE;
3890 		break;
3891 	default:
3892 		SPDK_ERRLOG("Invalid ZCOPY phase %u\n", req->zcopy_phase);
3893 		break;
3894 	}
3895 
3896 	if (nvmf_transport_req_complete(req)) {
3897 		SPDK_ERRLOG("Transport request completion error!\n");
3898 	}
3899 
3900 	/* AER cmd is an exception */
3901 	if (sgroup && !is_aer) {
3902 		if (spdk_unlikely(opcode == SPDK_NVME_OPC_FABRIC ||
3903 				  nvmf_qpair_is_admin_queue(qpair))) {
3904 			assert(sgroup->mgmt_io_outstanding > 0);
3905 			sgroup->mgmt_io_outstanding--;
3906 		} else {
3907 			if ((req->zcopy_phase == NVMF_ZCOPY_PHASE_NONE) ||
3908 			    (req->zcopy_phase == NVMF_ZCOPY_PHASE_COMPLETE)) {
3909 				/* End of request */
3910 
3911 				/* NOTE: This implicitly also checks for 0, since 0 - 1 wraps around to UINT32_MAX. */
3912 				if (spdk_likely(nsid - 1 < sgroup->num_ns)) {
3913 					sgroup->ns_info[nsid - 1].io_outstanding--;
3914 				}
3915 			}
3916 		}
3917 
3918 		if (spdk_unlikely(sgroup->state == SPDK_NVMF_SUBSYSTEM_PAUSING &&
3919 				  sgroup->mgmt_io_outstanding == 0)) {
3920 			paused = true;
3921 			for (nsid = 0; nsid < sgroup->num_ns; nsid++) {
3922 				ns_info = &sgroup->ns_info[nsid];
3923 
3924 				if (ns_info->state == SPDK_NVMF_SUBSYSTEM_PAUSING &&
3925 				    ns_info->io_outstanding > 0) {
3926 					paused = false;
3927 					break;
3928 				}
3929 			}
3930 
3931 			if (paused) {
3932 				sgroup->state = SPDK_NVMF_SUBSYSTEM_PAUSED;
3933 				sgroup->cb_fn(sgroup->cb_arg, 0);
3934 				sgroup->cb_fn = NULL;
3935 				sgroup->cb_arg = NULL;
3936 			}
3937 		}
3938 
3939 	}
3940 
3941 	nvmf_qpair_request_cleanup(qpair);
3942 }
3943 
3944 int
3945 spdk_nvmf_request_complete(struct spdk_nvmf_request *req)
3946 {
3947 	struct spdk_nvmf_qpair *qpair = req->qpair;
3948 
3949 	if (spdk_likely(qpair->group->thread == spdk_get_thread())) {
3950 		_nvmf_request_complete(req);
3951 	} else {
3952 		spdk_thread_send_msg(qpair->group->thread,
3953 				     _nvmf_request_complete, req);
3954 	}
3955 
3956 	return 0;
3957 }
3958 
3959 void
3960 spdk_nvmf_request_exec_fabrics(struct spdk_nvmf_request *req)
3961 {
3962 	struct spdk_nvmf_qpair *qpair = req->qpair;
3963 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
3964 	enum spdk_nvmf_request_exec_status status;
3965 
3966 	if (qpair->ctrlr) {
3967 		sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
3968 	} else if (spdk_unlikely(nvmf_request_is_fabric_connect(req))) {
3969 		sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
3970 	}
3971 
3972 	assert(sgroup != NULL);
3973 	sgroup->mgmt_io_outstanding++;
3974 
3975 	/* Place the request on the outstanding list so we can keep track of it */
3976 	nvmf_add_to_outstanding_queue(req);
3977 
3978 	assert(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC);
3979 	status = nvmf_ctrlr_process_fabrics_cmd(req);
3980 
3981 	if (status == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
3982 		_nvmf_request_complete(req);
3983 	}
3984 }
3985 
3986 static bool nvmf_check_subsystem_active(struct spdk_nvmf_request *req)
3987 {
3988 	struct spdk_nvmf_qpair *qpair = req->qpair;
3989 	struct spdk_nvmf_subsystem_poll_group *sgroup = NULL;
3990 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
3991 	uint32_t nsid;
3992 
3993 	if (qpair->ctrlr) {
3994 		sgroup = &qpair->group->sgroups[qpair->ctrlr->subsys->id];
3995 		assert(sgroup != NULL);
3996 	} else if (spdk_unlikely(nvmf_request_is_fabric_connect(req))) {
3997 		sgroup = nvmf_subsystem_pg_from_connect_cmd(req);
3998 	}
3999 
4000 	/* Check if the subsystem is paused (if there is a subsystem) */
4001 	if (sgroup != NULL) {
4002 		if (spdk_unlikely(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC ||
4003 				  nvmf_qpair_is_admin_queue(qpair))) {
4004 			if (sgroup->state != SPDK_NVMF_SUBSYSTEM_ACTIVE) {
4005 				/* The subsystem is not currently active. Queue this request. */
4006 				TAILQ_INSERT_TAIL(&sgroup->queued, req, link);
4007 				return false;
4008 			}
4009 			sgroup->mgmt_io_outstanding++;
4010 		} else {
4011 			nsid = req->cmd->nvme_cmd.nsid;
4012 
4013 			/* NOTE: This implicitly also checks for 0, since 0 - 1 wraps around to UINT32_MAX. */
4014 			if (spdk_unlikely(nsid - 1 >= sgroup->num_ns)) {
4015 				req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
4016 				req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
4017 				req->rsp->nvme_cpl.status.dnr = 1;
4018 				nvmf_add_to_outstanding_queue(req);
4019 				_nvmf_request_complete(req);
4020 				return false;
4021 			}
4022 
4023 			ns_info = &sgroup->ns_info[nsid - 1];
4024 			if (ns_info->channel == NULL) {
4025 				/* This can can happen if host sends I/O to a namespace that is
4026 				 * in the process of being added, but before the full addition
4027 				 * process is complete.  Report invalid namespace in that case.
4028 				 */
4029 				req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
4030 				req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
4031 				req->rsp->nvme_cpl.status.dnr = 1;
4032 				nvmf_add_to_outstanding_queue(req);
4033 				ns_info->io_outstanding++;
4034 				_nvmf_request_complete(req);
4035 				return false;
4036 			}
4037 
4038 			if (ns_info->state != SPDK_NVMF_SUBSYSTEM_ACTIVE) {
4039 				/* The namespace is not currently active. Queue this request. */
4040 				TAILQ_INSERT_TAIL(&sgroup->queued, req, link);
4041 				return false;
4042 			}
4043 
4044 			ns_info->io_outstanding++;
4045 		}
4046 
4047 		if (qpair->state != SPDK_NVMF_QPAIR_ACTIVE) {
4048 			req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
4049 			req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_COMMAND_SEQUENCE_ERROR;
4050 			nvmf_add_to_outstanding_queue(req);
4051 			_nvmf_request_complete(req);
4052 			return false;
4053 		}
4054 	}
4055 
4056 	return true;
4057 }
4058 
4059 void
4060 spdk_nvmf_request_exec(struct spdk_nvmf_request *req)
4061 {
4062 	struct spdk_nvmf_qpair *qpair = req->qpair;
4063 	enum spdk_nvmf_request_exec_status status;
4064 
4065 	if (!spdk_nvmf_using_zcopy(req->zcopy_phase)) {
4066 		if (!nvmf_check_subsystem_active(req)) {
4067 			return;
4068 		}
4069 	}
4070 
4071 	if (SPDK_DEBUGLOG_FLAG_ENABLED("nvmf")) {
4072 		spdk_nvme_print_command(qpair->qid, &req->cmd->nvme_cmd);
4073 	}
4074 
4075 	/* Place the request on the outstanding list so we can keep track of it */
4076 	nvmf_add_to_outstanding_queue(req);
4077 
4078 	if (spdk_unlikely(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC)) {
4079 		status = nvmf_ctrlr_process_fabrics_cmd(req);
4080 	} else if (spdk_unlikely(nvmf_qpair_is_admin_queue(qpair))) {
4081 		status = nvmf_ctrlr_process_admin_cmd(req);
4082 	} else {
4083 		status = nvmf_ctrlr_process_io_cmd(req);
4084 	}
4085 
4086 	if (status == SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE) {
4087 		_nvmf_request_complete(req);
4088 	}
4089 }
4090 
4091 static bool
4092 nvmf_ctrlr_get_dif_ctx(struct spdk_nvmf_ctrlr *ctrlr, struct spdk_nvme_cmd *cmd,
4093 		       struct spdk_dif_ctx *dif_ctx)
4094 {
4095 	struct spdk_nvmf_ns *ns;
4096 	struct spdk_bdev *bdev;
4097 
4098 	if (ctrlr == NULL || cmd == NULL) {
4099 		return false;
4100 	}
4101 
4102 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, cmd->nsid);
4103 	if (ns == NULL || ns->bdev == NULL) {
4104 		return false;
4105 	}
4106 
4107 	bdev = ns->bdev;
4108 
4109 	switch (cmd->opc) {
4110 	case SPDK_NVME_OPC_READ:
4111 	case SPDK_NVME_OPC_WRITE:
4112 	case SPDK_NVME_OPC_COMPARE:
4113 		return nvmf_bdev_ctrlr_get_dif_ctx(bdev, cmd, dif_ctx);
4114 	default:
4115 		break;
4116 	}
4117 
4118 	return false;
4119 }
4120 
4121 bool
4122 spdk_nvmf_request_get_dif_ctx(struct spdk_nvmf_request *req, struct spdk_dif_ctx *dif_ctx)
4123 {
4124 	struct spdk_nvmf_qpair *qpair = req->qpair;
4125 	struct spdk_nvmf_ctrlr *ctrlr = qpair->ctrlr;
4126 
4127 	if (spdk_likely(ctrlr == NULL || !ctrlr->dif_insert_or_strip)) {
4128 		return false;
4129 	}
4130 
4131 	if (spdk_unlikely(qpair->state != SPDK_NVMF_QPAIR_ACTIVE)) {
4132 		return false;
4133 	}
4134 
4135 	if (spdk_unlikely(req->cmd->nvmf_cmd.opcode == SPDK_NVME_OPC_FABRIC)) {
4136 		return false;
4137 	}
4138 
4139 	if (spdk_unlikely(nvmf_qpair_is_admin_queue(qpair))) {
4140 		return false;
4141 	}
4142 
4143 	return nvmf_ctrlr_get_dif_ctx(ctrlr, &req->cmd->nvme_cmd, dif_ctx);
4144 }
4145 
4146 void
4147 spdk_nvmf_set_custom_admin_cmd_hdlr(uint8_t opc, spdk_nvmf_custom_cmd_hdlr hdlr)
4148 {
4149 	g_nvmf_custom_admin_cmd_hdlrs[opc].hdlr = hdlr;
4150 }
4151 
4152 static int
4153 nvmf_passthru_admin_cmd(struct spdk_nvmf_request *req)
4154 {
4155 	struct spdk_bdev *bdev;
4156 	struct spdk_bdev_desc *desc;
4157 	struct spdk_io_channel *ch;
4158 	struct spdk_nvme_cmd *cmd = spdk_nvmf_request_get_cmd(req);
4159 	struct spdk_nvme_cpl *response = spdk_nvmf_request_get_response(req);
4160 	uint32_t bdev_nsid;
4161 	int rc;
4162 
4163 	if (g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].nsid == 0) {
4164 		bdev_nsid = cmd->nsid;
4165 	} else {
4166 		bdev_nsid = g_nvmf_custom_admin_cmd_hdlrs[cmd->opc].nsid;
4167 	}
4168 
4169 	rc = spdk_nvmf_request_get_bdev(bdev_nsid, req, &bdev, &desc, &ch);
4170 	if (rc) {
4171 		response->status.sct = SPDK_NVME_SCT_GENERIC;
4172 		response->status.sc = SPDK_NVME_SC_INVALID_NAMESPACE_OR_FORMAT;
4173 		return SPDK_NVMF_REQUEST_EXEC_STATUS_COMPLETE;
4174 	}
4175 	return spdk_nvmf_bdev_ctrlr_nvme_passthru_admin(bdev, desc, ch, req, NULL);
4176 }
4177 
4178 void
4179 spdk_nvmf_set_passthru_admin_cmd(uint8_t opc, uint32_t forward_nsid)
4180 {
4181 	g_nvmf_custom_admin_cmd_hdlrs[opc].hdlr = nvmf_passthru_admin_cmd;
4182 	g_nvmf_custom_admin_cmd_hdlrs[opc].nsid = forward_nsid;
4183 }
4184 
4185 int
4186 spdk_nvmf_request_get_bdev(uint32_t nsid, struct spdk_nvmf_request *req,
4187 			   struct spdk_bdev **bdev, struct spdk_bdev_desc **desc, struct spdk_io_channel **ch)
4188 {
4189 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
4190 	struct spdk_nvmf_ns *ns;
4191 	struct spdk_nvmf_poll_group *group = req->qpair->group;
4192 	struct spdk_nvmf_subsystem_pg_ns_info *ns_info;
4193 
4194 	*bdev = NULL;
4195 	*desc = NULL;
4196 	*ch = NULL;
4197 
4198 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
4199 	if (ns == NULL || ns->bdev == NULL) {
4200 		return -EINVAL;
4201 	}
4202 
4203 	assert(group != NULL && group->sgroups != NULL);
4204 	ns_info = &group->sgroups[ctrlr->subsys->id].ns_info[nsid - 1];
4205 	*bdev = ns->bdev;
4206 	*desc = ns->desc;
4207 	*ch = ns_info->channel;
4208 
4209 	return 0;
4210 }
4211 
4212 struct spdk_nvmf_ctrlr *spdk_nvmf_request_get_ctrlr(struct spdk_nvmf_request *req)
4213 {
4214 	return req->qpair->ctrlr;
4215 }
4216 
4217 struct spdk_nvme_cmd *spdk_nvmf_request_get_cmd(struct spdk_nvmf_request *req)
4218 {
4219 	return &req->cmd->nvme_cmd;
4220 }
4221 
4222 struct spdk_nvme_cpl *spdk_nvmf_request_get_response(struct spdk_nvmf_request *req)
4223 {
4224 	return &req->rsp->nvme_cpl;
4225 }
4226 
4227 struct spdk_nvmf_subsystem *spdk_nvmf_request_get_subsystem(struct spdk_nvmf_request *req)
4228 {
4229 	return req->qpair->ctrlr->subsys;
4230 }
4231 
4232 void spdk_nvmf_request_get_data(struct spdk_nvmf_request *req, void **data, uint32_t *length)
4233 {
4234 	*data = req->data;
4235 	*length = req->length;
4236 }
4237 
4238 struct spdk_nvmf_subsystem *spdk_nvmf_ctrlr_get_subsystem(struct spdk_nvmf_ctrlr *ctrlr)
4239 {
4240 	return ctrlr->subsys;
4241 }
4242 
4243 uint16_t spdk_nvmf_ctrlr_get_id(struct spdk_nvmf_ctrlr *ctrlr)
4244 {
4245 	return ctrlr->cntlid;
4246 }
4247 
4248 struct spdk_nvmf_request *spdk_nvmf_request_get_req_to_abort(struct spdk_nvmf_request *req)
4249 {
4250 	return req->req_to_abort;
4251 }
4252