xref: /spdk/lib/nvmf/subsystem.c (revision c65983c9f2000473107a4a5e01f98c1563e7334a)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (C) 2016 Intel Corporation. All rights reserved.
3  *   Copyright (c) 2019 Mellanox Technologies LTD. All rights reserved.
4  *   Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "nvmf_internal.h"
10 #include "transport.h"
11 
12 #include "spdk/assert.h"
13 #include "spdk/likely.h"
14 #include "spdk/string.h"
15 #include "spdk/trace.h"
16 #include "spdk/nvmf_spec.h"
17 #include "spdk/uuid.h"
18 #include "spdk/json.h"
19 #include "spdk/file.h"
20 #include "spdk/bit_array.h"
21 #include "spdk/bdev.h"
22 
23 #define __SPDK_BDEV_MODULE_ONLY
24 #include "spdk/bdev_module.h"
25 #include "spdk/log.h"
26 #include "spdk_internal/utf.h"
27 #include "spdk_internal/usdt.h"
28 
29 #define MODEL_NUMBER_DEFAULT "SPDK bdev Controller"
30 #define NVMF_SUBSYSTEM_DEFAULT_NAMESPACES 32
31 
32 /*
33  * States for parsing valid domains in NQNs according to RFC 1034
34  */
35 enum spdk_nvmf_nqn_domain_states {
36 	/* First character of a domain must be a letter */
37 	SPDK_NVMF_DOMAIN_ACCEPT_LETTER = 0,
38 
39 	/* Subsequent characters can be any of letter, digit, or hyphen */
40 	SPDK_NVMF_DOMAIN_ACCEPT_LDH = 1,
41 
42 	/* A domain label must end with either a letter or digit */
43 	SPDK_NVMF_DOMAIN_ACCEPT_ANY = 2
44 };
45 
46 static int _nvmf_subsystem_destroy(struct spdk_nvmf_subsystem *subsystem);
47 
48 /* Returns true if is a valid ASCII string as defined by the NVMe spec */
49 static bool
50 nvmf_valid_ascii_string(const void *buf, size_t size)
51 {
52 	const uint8_t *str = buf;
53 	size_t i;
54 
55 	for (i = 0; i < size; i++) {
56 		if (str[i] < 0x20 || str[i] > 0x7E) {
57 			return false;
58 		}
59 	}
60 
61 	return true;
62 }
63 
64 bool
65 nvmf_nqn_is_valid(const char *nqn)
66 {
67 	size_t len;
68 	struct spdk_uuid uuid_value;
69 	uint32_t i;
70 	int bytes_consumed;
71 	uint32_t domain_label_length;
72 	char *reverse_domain_end;
73 	uint32_t reverse_domain_end_index;
74 	enum spdk_nvmf_nqn_domain_states domain_state = SPDK_NVMF_DOMAIN_ACCEPT_LETTER;
75 
76 	/* Check for length requirements */
77 	len = strlen(nqn);
78 	if (len > SPDK_NVMF_NQN_MAX_LEN) {
79 		SPDK_ERRLOG("Invalid NQN \"%s\": length %zu > max %d\n", nqn, len, SPDK_NVMF_NQN_MAX_LEN);
80 		return false;
81 	}
82 
83 	/* The nqn must be at least as long as SPDK_NVMF_NQN_MIN_LEN to contain the necessary prefix. */
84 	if (len < SPDK_NVMF_NQN_MIN_LEN) {
85 		SPDK_ERRLOG("Invalid NQN \"%s\": length %zu < min %d\n", nqn, len, SPDK_NVMF_NQN_MIN_LEN);
86 		return false;
87 	}
88 
89 	/* Check for discovery controller nqn */
90 	if (!strcmp(nqn, SPDK_NVMF_DISCOVERY_NQN)) {
91 		return true;
92 	}
93 
94 	/* Check for equality with the generic nqn structure of the form "nqn.2014-08.org.nvmexpress:uuid:11111111-2222-3333-4444-555555555555" */
95 	if (!strncmp(nqn, SPDK_NVMF_NQN_UUID_PRE, SPDK_NVMF_NQN_UUID_PRE_LEN)) {
96 		if (len != SPDK_NVMF_NQN_UUID_PRE_LEN + SPDK_NVMF_UUID_STRING_LEN) {
97 			SPDK_ERRLOG("Invalid NQN \"%s\": uuid is not the correct length\n", nqn);
98 			return false;
99 		}
100 
101 		if (spdk_uuid_parse(&uuid_value, &nqn[SPDK_NVMF_NQN_UUID_PRE_LEN])) {
102 			SPDK_ERRLOG("Invalid NQN \"%s\": uuid is not formatted correctly\n", nqn);
103 			return false;
104 		}
105 		return true;
106 	}
107 
108 	/* If the nqn does not match the uuid structure, the next several checks validate the form "nqn.yyyy-mm.reverse.domain:user-string" */
109 
110 	if (strncmp(nqn, "nqn.", 4) != 0) {
111 		SPDK_ERRLOG("Invalid NQN \"%s\": NQN must begin with \"nqn.\".\n", nqn);
112 		return false;
113 	}
114 
115 	/* Check for yyyy-mm. */
116 	if (!(isdigit(nqn[4]) && isdigit(nqn[5]) && isdigit(nqn[6]) && isdigit(nqn[7]) &&
117 	      nqn[8] == '-' && isdigit(nqn[9]) && isdigit(nqn[10]) && nqn[11] == '.')) {
118 		SPDK_ERRLOG("Invalid date code in NQN \"%s\"\n", nqn);
119 		return false;
120 	}
121 
122 	reverse_domain_end = strchr(nqn, ':');
123 	if (reverse_domain_end != NULL && (reverse_domain_end_index = reverse_domain_end - nqn) < len - 1) {
124 	} else {
125 		SPDK_ERRLOG("Invalid NQN \"%s\". NQN must contain user specified name with a ':' as a prefix.\n",
126 			    nqn);
127 		return false;
128 	}
129 
130 	/* Check for valid reverse domain */
131 	domain_label_length = 0;
132 	for (i = 12; i < reverse_domain_end_index; i++) {
133 		if (domain_label_length > SPDK_DOMAIN_LABEL_MAX_LEN) {
134 			SPDK_ERRLOG("Invalid domain name in NQN \"%s\". At least one Label is too long.\n", nqn);
135 			return false;
136 		}
137 
138 		switch (domain_state) {
139 
140 		case SPDK_NVMF_DOMAIN_ACCEPT_LETTER: {
141 			if (isalpha(nqn[i])) {
142 				domain_state = SPDK_NVMF_DOMAIN_ACCEPT_ANY;
143 				domain_label_length++;
144 				break;
145 			} else {
146 				SPDK_ERRLOG("Invalid domain name in NQN \"%s\". Label names must start with a letter.\n", nqn);
147 				return false;
148 			}
149 		}
150 
151 		case SPDK_NVMF_DOMAIN_ACCEPT_LDH: {
152 			if (isalpha(nqn[i]) || isdigit(nqn[i])) {
153 				domain_state = SPDK_NVMF_DOMAIN_ACCEPT_ANY;
154 				domain_label_length++;
155 				break;
156 			} else if (nqn[i] == '-') {
157 				if (i == reverse_domain_end_index - 1) {
158 					SPDK_ERRLOG("Invalid domain name in NQN \"%s\". Label names must end with an alphanumeric symbol.\n",
159 						    nqn);
160 					return false;
161 				}
162 				domain_state = SPDK_NVMF_DOMAIN_ACCEPT_LDH;
163 				domain_label_length++;
164 				break;
165 			} else if (nqn[i] == '.') {
166 				SPDK_ERRLOG("Invalid domain name in NQN \"%s\". Label names must end with an alphanumeric symbol.\n",
167 					    nqn);
168 				return false;
169 			} else {
170 				SPDK_ERRLOG("Invalid domain name in NQN \"%s\". Label names must contain only [a-z,A-Z,0-9,'-','.'].\n",
171 					    nqn);
172 				return false;
173 			}
174 		}
175 
176 		case SPDK_NVMF_DOMAIN_ACCEPT_ANY: {
177 			if (isalpha(nqn[i]) || isdigit(nqn[i])) {
178 				domain_state = SPDK_NVMF_DOMAIN_ACCEPT_ANY;
179 				domain_label_length++;
180 				break;
181 			} else if (nqn[i] == '-') {
182 				if (i == reverse_domain_end_index - 1) {
183 					SPDK_ERRLOG("Invalid domain name in NQN \"%s\". Label names must end with an alphanumeric symbol.\n",
184 						    nqn);
185 					return false;
186 				}
187 				domain_state = SPDK_NVMF_DOMAIN_ACCEPT_LDH;
188 				domain_label_length++;
189 				break;
190 			} else if (nqn[i] == '.') {
191 				domain_state = SPDK_NVMF_DOMAIN_ACCEPT_LETTER;
192 				domain_label_length = 0;
193 				break;
194 			} else {
195 				SPDK_ERRLOG("Invalid domain name in NQN \"%s\". Label names must contain only [a-z,A-Z,0-9,'-','.'].\n",
196 					    nqn);
197 				return false;
198 			}
199 		}
200 		}
201 	}
202 
203 	i = reverse_domain_end_index + 1;
204 	while (i < len) {
205 		bytes_consumed = utf8_valid(&nqn[i], &nqn[len]);
206 		if (bytes_consumed <= 0) {
207 			SPDK_ERRLOG("Invalid domain name in NQN \"%s\". Label names must contain only valid utf-8.\n", nqn);
208 			return false;
209 		}
210 
211 		i += bytes_consumed;
212 	}
213 	return true;
214 }
215 
216 static void subsystem_state_change_on_pg(struct spdk_io_channel_iter *i);
217 
218 struct spdk_nvmf_subsystem *
219 spdk_nvmf_subsystem_create(struct spdk_nvmf_tgt *tgt,
220 			   const char *nqn,
221 			   enum spdk_nvmf_subtype type,
222 			   uint32_t num_ns)
223 {
224 	struct spdk_nvmf_subsystem	*subsystem;
225 	uint32_t			sid;
226 
227 	if (spdk_nvmf_tgt_find_subsystem(tgt, nqn)) {
228 		SPDK_ERRLOG("Subsystem NQN '%s' already exists\n", nqn);
229 		return NULL;
230 	}
231 
232 	if (!nvmf_nqn_is_valid(nqn)) {
233 		SPDK_ERRLOG("Subsystem NQN '%s' is invalid\n", nqn);
234 		return NULL;
235 	}
236 
237 	if (type == SPDK_NVMF_SUBTYPE_DISCOVERY_CURRENT ||
238 	    type == SPDK_NVMF_SUBTYPE_DISCOVERY) {
239 		if (num_ns != 0) {
240 			SPDK_ERRLOG("Discovery subsystem cannot have namespaces.\n");
241 			return NULL;
242 		}
243 	} else if (num_ns == 0) {
244 		num_ns = NVMF_SUBSYSTEM_DEFAULT_NAMESPACES;
245 	}
246 
247 	/* Find a free subsystem id (sid) */
248 	sid = spdk_bit_array_find_first_clear(tgt->subsystem_ids, 0);
249 	if (sid == UINT32_MAX) {
250 		SPDK_ERRLOG("No free subsystem IDs are available for subsystem creation\n");
251 		return NULL;
252 	}
253 	subsystem = calloc(1, sizeof(struct spdk_nvmf_subsystem));
254 	if (subsystem == NULL) {
255 		SPDK_ERRLOG("Subsystem memory allocation failed\n");
256 		return NULL;
257 	}
258 
259 	subsystem->thread = spdk_get_thread();
260 	subsystem->state = SPDK_NVMF_SUBSYSTEM_INACTIVE;
261 	subsystem->tgt = tgt;
262 	subsystem->id = sid;
263 	subsystem->subtype = type;
264 	subsystem->max_nsid = num_ns;
265 	subsystem->next_cntlid = 0;
266 	subsystem->min_cntlid = NVMF_MIN_CNTLID;
267 	subsystem->max_cntlid = NVMF_MAX_CNTLID;
268 	snprintf(subsystem->subnqn, sizeof(subsystem->subnqn), "%s", nqn);
269 	pthread_mutex_init(&subsystem->mutex, NULL);
270 	TAILQ_INIT(&subsystem->listeners);
271 	TAILQ_INIT(&subsystem->hosts);
272 	TAILQ_INIT(&subsystem->ctrlrs);
273 	TAILQ_INIT(&subsystem->state_changes);
274 	subsystem->used_listener_ids = spdk_bit_array_create(NVMF_MAX_LISTENERS_PER_SUBSYSTEM);
275 	if (subsystem->used_listener_ids == NULL) {
276 		pthread_mutex_destroy(&subsystem->mutex);
277 		free(subsystem);
278 		SPDK_ERRLOG("Listener id array memory allocation failed\n");
279 		return NULL;
280 	}
281 
282 	if (num_ns != 0) {
283 		subsystem->ns = calloc(num_ns, sizeof(struct spdk_nvmf_ns *));
284 		if (subsystem->ns == NULL) {
285 			SPDK_ERRLOG("Namespace memory allocation failed\n");
286 			pthread_mutex_destroy(&subsystem->mutex);
287 			spdk_bit_array_free(&subsystem->used_listener_ids);
288 			free(subsystem);
289 			return NULL;
290 		}
291 		subsystem->ana_group = calloc(num_ns, sizeof(uint32_t));
292 		if (subsystem->ana_group == NULL) {
293 			SPDK_ERRLOG("ANA group memory allocation failed\n");
294 			pthread_mutex_destroy(&subsystem->mutex);
295 			free(subsystem->ns);
296 			spdk_bit_array_free(&subsystem->used_listener_ids);
297 			free(subsystem);
298 			return NULL;
299 		}
300 	}
301 
302 	memset(subsystem->sn, '0', sizeof(subsystem->sn) - 1);
303 	subsystem->sn[sizeof(subsystem->sn) - 1] = '\0';
304 
305 	snprintf(subsystem->mn, sizeof(subsystem->mn), "%s",
306 		 MODEL_NUMBER_DEFAULT);
307 
308 	spdk_bit_array_set(tgt->subsystem_ids, sid);
309 	RB_INSERT(subsystem_tree, &tgt->subsystems, subsystem);
310 
311 	SPDK_DTRACE_PROBE1(nvmf_subsystem_create, subsystem->subnqn);
312 
313 	return subsystem;
314 }
315 
316 static void
317 nvmf_host_free(struct spdk_nvmf_host *host)
318 {
319 	spdk_keyring_put_key(host->dhchap_key);
320 	spdk_keyring_put_key(host->dhchap_ctrlr_key);
321 	free(host);
322 }
323 
324 /* Must hold subsystem->mutex while calling this function */
325 static void
326 nvmf_subsystem_remove_host(struct spdk_nvmf_subsystem *subsystem, struct spdk_nvmf_host *host)
327 {
328 	TAILQ_REMOVE(&subsystem->hosts, host, link);
329 	nvmf_host_free(host);
330 }
331 
332 static void
333 _nvmf_subsystem_remove_listener(struct spdk_nvmf_subsystem *subsystem,
334 				struct spdk_nvmf_subsystem_listener *listener,
335 				bool stop)
336 {
337 	struct spdk_nvmf_transport *transport;
338 	struct spdk_nvmf_ctrlr *ctrlr;
339 
340 	if (stop) {
341 		transport = spdk_nvmf_tgt_get_transport(subsystem->tgt, listener->trid->trstring);
342 		if (transport != NULL) {
343 			spdk_nvmf_transport_stop_listen(transport, listener->trid);
344 		}
345 	}
346 
347 	TAILQ_FOREACH(ctrlr, &subsystem->ctrlrs, link) {
348 		if (ctrlr->listener == listener) {
349 			ctrlr->listener = NULL;
350 		}
351 	}
352 
353 	TAILQ_REMOVE(&subsystem->listeners, listener, link);
354 	nvmf_update_discovery_log(listener->subsystem->tgt, NULL);
355 	free(listener->ana_state);
356 	spdk_bit_array_clear(subsystem->used_listener_ids, listener->id);
357 	free(listener->opts.sock_impl);
358 	free(listener);
359 }
360 
361 static void
362 _nvmf_subsystem_destroy_msg(void *cb_arg)
363 {
364 	struct spdk_nvmf_subsystem *subsystem = cb_arg;
365 
366 	_nvmf_subsystem_destroy(subsystem);
367 }
368 
369 static int
370 _nvmf_subsystem_destroy(struct spdk_nvmf_subsystem *subsystem)
371 {
372 	struct nvmf_subsystem_state_change_ctx *ctx;
373 	struct spdk_nvmf_ns		*ns;
374 	nvmf_subsystem_destroy_cb	async_destroy_cb = NULL;
375 	void				*async_destroy_cb_arg = NULL;
376 	int				rc;
377 
378 	if (!TAILQ_EMPTY(&subsystem->ctrlrs)) {
379 		SPDK_DEBUGLOG(nvmf, "subsystem %p %s has active controllers\n", subsystem, subsystem->subnqn);
380 		subsystem->async_destroy = true;
381 		rc = spdk_thread_send_msg(subsystem->thread, _nvmf_subsystem_destroy_msg, subsystem);
382 		if (rc) {
383 			SPDK_ERRLOG("Failed to send thread msg, rc %d\n", rc);
384 			assert(0);
385 			return rc;
386 		}
387 		return -EINPROGRESS;
388 	}
389 
390 	ns = spdk_nvmf_subsystem_get_first_ns(subsystem);
391 	while (ns != NULL) {
392 		struct spdk_nvmf_ns *next_ns = spdk_nvmf_subsystem_get_next_ns(subsystem, ns);
393 
394 		spdk_nvmf_subsystem_remove_ns(subsystem, ns->opts.nsid);
395 		ns = next_ns;
396 	}
397 
398 	while ((ctx = TAILQ_FIRST(&subsystem->state_changes))) {
399 		SPDK_WARNLOG("subsystem %s has pending state change requests\n", subsystem->subnqn);
400 		TAILQ_REMOVE(&subsystem->state_changes, ctx, link);
401 		if (ctx->cb_fn != NULL) {
402 			ctx->cb_fn(subsystem, ctx->cb_arg, -ECANCELED);
403 		}
404 		free(ctx);
405 	}
406 
407 	free(subsystem->ns);
408 	free(subsystem->ana_group);
409 
410 	RB_REMOVE(subsystem_tree, &subsystem->tgt->subsystems, subsystem);
411 	assert(spdk_bit_array_get(subsystem->tgt->subsystem_ids, subsystem->id) == true);
412 	spdk_bit_array_clear(subsystem->tgt->subsystem_ids, subsystem->id);
413 
414 	pthread_mutex_destroy(&subsystem->mutex);
415 
416 	spdk_bit_array_free(&subsystem->used_listener_ids);
417 
418 	if (subsystem->async_destroy) {
419 		async_destroy_cb = subsystem->async_destroy_cb;
420 		async_destroy_cb_arg = subsystem->async_destroy_cb_arg;
421 	}
422 
423 	free(subsystem);
424 
425 	if (async_destroy_cb) {
426 		async_destroy_cb(async_destroy_cb_arg);
427 	}
428 
429 	return 0;
430 }
431 
432 static struct spdk_nvmf_ns *
433 _nvmf_subsystem_get_first_zoned_ns(struct spdk_nvmf_subsystem *subsystem)
434 {
435 	struct spdk_nvmf_ns *ns = spdk_nvmf_subsystem_get_first_ns(subsystem);
436 	while (ns != NULL) {
437 		if (ns->csi == SPDK_NVME_CSI_ZNS) {
438 			return ns;
439 		}
440 		ns = spdk_nvmf_subsystem_get_next_ns(subsystem, ns);
441 	}
442 	return NULL;
443 }
444 
445 int
446 spdk_nvmf_subsystem_destroy(struct spdk_nvmf_subsystem *subsystem, nvmf_subsystem_destroy_cb cpl_cb,
447 			    void *cpl_cb_arg)
448 {
449 	struct spdk_nvmf_host *host, *host_tmp;
450 	struct spdk_nvmf_transport *transport;
451 
452 	if (!subsystem) {
453 		return -EINVAL;
454 	}
455 
456 	SPDK_DTRACE_PROBE1(nvmf_subsystem_destroy, subsystem->subnqn);
457 
458 	assert(spdk_get_thread() == subsystem->thread);
459 
460 	if (subsystem->state != SPDK_NVMF_SUBSYSTEM_INACTIVE) {
461 		SPDK_ERRLOG("Subsystem can only be destroyed in inactive state, %s state %d\n",
462 			    subsystem->subnqn, subsystem->state);
463 		return -EAGAIN;
464 	}
465 	if (subsystem->destroying) {
466 		SPDK_ERRLOG("Subsystem destruction is already started\n");
467 		assert(0);
468 		return -EALREADY;
469 	}
470 
471 	subsystem->destroying = true;
472 
473 	SPDK_DEBUGLOG(nvmf, "subsystem is %p %s\n", subsystem, subsystem->subnqn);
474 
475 	nvmf_subsystem_remove_all_listeners(subsystem, false);
476 
477 	pthread_mutex_lock(&subsystem->mutex);
478 
479 	TAILQ_FOREACH_SAFE(host, &subsystem->hosts, link, host_tmp) {
480 		for (transport = spdk_nvmf_transport_get_first(subsystem->tgt); transport;
481 		     transport = spdk_nvmf_transport_get_next(transport)) {
482 			if (transport->ops->subsystem_remove_host) {
483 				transport->ops->subsystem_remove_host(transport, subsystem, host->nqn);
484 			}
485 		}
486 		nvmf_subsystem_remove_host(subsystem, host);
487 	}
488 
489 	pthread_mutex_unlock(&subsystem->mutex);
490 
491 	subsystem->async_destroy_cb = cpl_cb;
492 	subsystem->async_destroy_cb_arg = cpl_cb_arg;
493 
494 	return _nvmf_subsystem_destroy(subsystem);
495 }
496 
497 /* we have to use the typedef in the function declaration to appease astyle. */
498 typedef enum spdk_nvmf_subsystem_state spdk_nvmf_subsystem_state_t;
499 
500 static spdk_nvmf_subsystem_state_t
501 nvmf_subsystem_get_intermediate_state(enum spdk_nvmf_subsystem_state current_state,
502 				      enum spdk_nvmf_subsystem_state requested_state)
503 {
504 	switch (requested_state) {
505 	case SPDK_NVMF_SUBSYSTEM_INACTIVE:
506 		return SPDK_NVMF_SUBSYSTEM_DEACTIVATING;
507 	case SPDK_NVMF_SUBSYSTEM_ACTIVE:
508 		if (current_state == SPDK_NVMF_SUBSYSTEM_PAUSED) {
509 			return SPDK_NVMF_SUBSYSTEM_RESUMING;
510 		} else {
511 			return SPDK_NVMF_SUBSYSTEM_ACTIVATING;
512 		}
513 	case SPDK_NVMF_SUBSYSTEM_PAUSED:
514 		return SPDK_NVMF_SUBSYSTEM_PAUSING;
515 	default:
516 		assert(false);
517 		return SPDK_NVMF_SUBSYSTEM_NUM_STATES;
518 	}
519 }
520 
521 static int
522 nvmf_subsystem_set_state(struct spdk_nvmf_subsystem *subsystem,
523 			 enum spdk_nvmf_subsystem_state state)
524 {
525 	enum spdk_nvmf_subsystem_state actual_old_state, expected_old_state;
526 	bool exchanged;
527 
528 	switch (state) {
529 	case SPDK_NVMF_SUBSYSTEM_INACTIVE:
530 		expected_old_state = SPDK_NVMF_SUBSYSTEM_DEACTIVATING;
531 		break;
532 	case SPDK_NVMF_SUBSYSTEM_ACTIVATING:
533 		expected_old_state = SPDK_NVMF_SUBSYSTEM_INACTIVE;
534 		break;
535 	case SPDK_NVMF_SUBSYSTEM_ACTIVE:
536 		expected_old_state = SPDK_NVMF_SUBSYSTEM_ACTIVATING;
537 		break;
538 	case SPDK_NVMF_SUBSYSTEM_PAUSING:
539 		expected_old_state = SPDK_NVMF_SUBSYSTEM_ACTIVE;
540 		break;
541 	case SPDK_NVMF_SUBSYSTEM_PAUSED:
542 		expected_old_state = SPDK_NVMF_SUBSYSTEM_PAUSING;
543 		break;
544 	case SPDK_NVMF_SUBSYSTEM_RESUMING:
545 		expected_old_state = SPDK_NVMF_SUBSYSTEM_PAUSED;
546 		break;
547 	case SPDK_NVMF_SUBSYSTEM_DEACTIVATING:
548 		expected_old_state = SPDK_NVMF_SUBSYSTEM_ACTIVE;
549 		break;
550 	default:
551 		assert(false);
552 		return -1;
553 	}
554 
555 	actual_old_state = expected_old_state;
556 	exchanged = __atomic_compare_exchange_n(&subsystem->state, &actual_old_state, state, false,
557 						__ATOMIC_RELAXED, __ATOMIC_RELAXED);
558 	if (spdk_unlikely(exchanged == false)) {
559 		if (actual_old_state == SPDK_NVMF_SUBSYSTEM_RESUMING &&
560 		    state == SPDK_NVMF_SUBSYSTEM_ACTIVE) {
561 			expected_old_state = SPDK_NVMF_SUBSYSTEM_RESUMING;
562 		}
563 		/* This is for the case when activating the subsystem fails. */
564 		if (actual_old_state == SPDK_NVMF_SUBSYSTEM_ACTIVATING &&
565 		    state == SPDK_NVMF_SUBSYSTEM_DEACTIVATING) {
566 			expected_old_state = SPDK_NVMF_SUBSYSTEM_ACTIVATING;
567 		}
568 		/* This is for the case when resuming the subsystem fails. */
569 		if (actual_old_state == SPDK_NVMF_SUBSYSTEM_RESUMING &&
570 		    state == SPDK_NVMF_SUBSYSTEM_PAUSING) {
571 			expected_old_state = SPDK_NVMF_SUBSYSTEM_RESUMING;
572 		}
573 		/* This is for the case when stopping paused subsystem */
574 		if (actual_old_state == SPDK_NVMF_SUBSYSTEM_PAUSED &&
575 		    state == SPDK_NVMF_SUBSYSTEM_DEACTIVATING) {
576 			expected_old_state = SPDK_NVMF_SUBSYSTEM_PAUSED;
577 		}
578 		actual_old_state = expected_old_state;
579 		__atomic_compare_exchange_n(&subsystem->state, &actual_old_state, state, false,
580 					    __ATOMIC_RELAXED, __ATOMIC_RELAXED);
581 	}
582 	assert(actual_old_state == expected_old_state);
583 	return actual_old_state - expected_old_state;
584 }
585 
586 static void nvmf_subsystem_do_state_change(struct nvmf_subsystem_state_change_ctx *ctx);
587 
588 static void
589 _nvmf_subsystem_state_change_complete(void *_ctx)
590 {
591 	struct nvmf_subsystem_state_change_ctx *next, *ctx = _ctx;
592 	struct spdk_nvmf_subsystem *subsystem = ctx->subsystem;
593 
594 	pthread_mutex_lock(&subsystem->mutex);
595 	assert(TAILQ_FIRST(&subsystem->state_changes) == ctx);
596 	TAILQ_REMOVE(&subsystem->state_changes, ctx, link);
597 	next = TAILQ_FIRST(&subsystem->state_changes);
598 	pthread_mutex_unlock(&subsystem->mutex);
599 
600 	if (ctx->cb_fn != NULL) {
601 		ctx->cb_fn(subsystem, ctx->cb_arg, ctx->status);
602 	}
603 	free(ctx);
604 
605 	if (next != NULL) {
606 		nvmf_subsystem_do_state_change(next);
607 	}
608 }
609 
610 static void
611 nvmf_subsystem_state_change_complete(struct nvmf_subsystem_state_change_ctx *ctx, int status)
612 {
613 	ctx->status = status;
614 	spdk_thread_exec_msg(ctx->thread, _nvmf_subsystem_state_change_complete, ctx);
615 }
616 
617 static void
618 subsystem_state_change_revert_done(struct spdk_io_channel_iter *i, int status)
619 {
620 	struct nvmf_subsystem_state_change_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
621 
622 	/* Nothing to be done here if the state setting fails, we are just screwed. */
623 	if (nvmf_subsystem_set_state(ctx->subsystem, ctx->requested_state)) {
624 		SPDK_ERRLOG("Unable to revert the subsystem state after operation failure.\n");
625 	}
626 
627 	/* return a failure here. This function only exists in an error path. */
628 	nvmf_subsystem_state_change_complete(ctx, -1);
629 }
630 
631 static void
632 subsystem_state_change_done(struct spdk_io_channel_iter *i, int status)
633 {
634 	struct nvmf_subsystem_state_change_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
635 	enum spdk_nvmf_subsystem_state intermediate_state;
636 
637 	SPDK_DTRACE_PROBE4(nvmf_subsystem_change_state_done, ctx->subsystem->subnqn,
638 			   ctx->requested_state, ctx->original_state, status);
639 
640 	if (status == 0) {
641 		status = nvmf_subsystem_set_state(ctx->subsystem, ctx->requested_state);
642 		if (status) {
643 			status = -1;
644 		}
645 	}
646 
647 	if (status) {
648 		intermediate_state = nvmf_subsystem_get_intermediate_state(ctx->requested_state,
649 				     ctx->original_state);
650 		assert(intermediate_state != SPDK_NVMF_SUBSYSTEM_NUM_STATES);
651 
652 		if (nvmf_subsystem_set_state(ctx->subsystem, intermediate_state)) {
653 			goto out;
654 		}
655 		ctx->requested_state = ctx->original_state;
656 		spdk_for_each_channel(ctx->subsystem->tgt,
657 				      subsystem_state_change_on_pg,
658 				      ctx,
659 				      subsystem_state_change_revert_done);
660 		return;
661 	}
662 
663 out:
664 	nvmf_subsystem_state_change_complete(ctx, status);
665 }
666 
667 static void
668 subsystem_state_change_continue(void *ctx, int status)
669 {
670 	struct spdk_io_channel_iter *i = ctx;
671 	struct nvmf_subsystem_state_change_ctx *_ctx __attribute__((unused));
672 
673 	_ctx = spdk_io_channel_iter_get_ctx(i);
674 	SPDK_DTRACE_PROBE3(nvmf_pg_change_state_done, _ctx->subsystem->subnqn,
675 			   _ctx->requested_state, spdk_thread_get_id(spdk_get_thread()));
676 
677 	spdk_for_each_channel_continue(i, status);
678 }
679 
680 static void
681 subsystem_state_change_on_pg(struct spdk_io_channel_iter *i)
682 {
683 	struct nvmf_subsystem_state_change_ctx *ctx;
684 	struct spdk_io_channel *ch;
685 	struct spdk_nvmf_poll_group *group;
686 
687 	ctx = spdk_io_channel_iter_get_ctx(i);
688 	ch = spdk_io_channel_iter_get_channel(i);
689 	group = spdk_io_channel_get_ctx(ch);
690 
691 	SPDK_DTRACE_PROBE3(nvmf_pg_change_state, ctx->subsystem->subnqn,
692 			   ctx->requested_state, spdk_thread_get_id(spdk_get_thread()));
693 	switch (ctx->requested_state) {
694 	case SPDK_NVMF_SUBSYSTEM_INACTIVE:
695 		nvmf_poll_group_remove_subsystem(group, ctx->subsystem, subsystem_state_change_continue, i);
696 		break;
697 	case SPDK_NVMF_SUBSYSTEM_ACTIVE:
698 		if (ctx->subsystem->state == SPDK_NVMF_SUBSYSTEM_ACTIVATING) {
699 			nvmf_poll_group_add_subsystem(group, ctx->subsystem, subsystem_state_change_continue, i);
700 		} else if (ctx->subsystem->state == SPDK_NVMF_SUBSYSTEM_RESUMING) {
701 			nvmf_poll_group_resume_subsystem(group, ctx->subsystem, subsystem_state_change_continue, i);
702 		}
703 		break;
704 	case SPDK_NVMF_SUBSYSTEM_PAUSED:
705 		nvmf_poll_group_pause_subsystem(group, ctx->subsystem, ctx->nsid, subsystem_state_change_continue,
706 						i);
707 		break;
708 	default:
709 		assert(false);
710 		break;
711 	}
712 }
713 
714 static void
715 nvmf_subsystem_do_state_change(struct nvmf_subsystem_state_change_ctx *ctx)
716 {
717 	struct spdk_nvmf_subsystem *subsystem = ctx->subsystem;
718 	enum spdk_nvmf_subsystem_state intermediate_state;
719 	int rc;
720 
721 	SPDK_DTRACE_PROBE3(nvmf_subsystem_change_state, subsystem->subnqn,
722 			   ctx->requested_state, subsystem->state);
723 
724 	/* If we are already in the requested state, just call the callback immediately. */
725 	if (subsystem->state == ctx->requested_state) {
726 		nvmf_subsystem_state_change_complete(ctx, 0);
727 		return;
728 	}
729 
730 	intermediate_state = nvmf_subsystem_get_intermediate_state(subsystem->state,
731 			     ctx->requested_state);
732 	assert(intermediate_state != SPDK_NVMF_SUBSYSTEM_NUM_STATES);
733 
734 	ctx->original_state = subsystem->state;
735 	rc = nvmf_subsystem_set_state(subsystem, intermediate_state);
736 	if (rc) {
737 		nvmf_subsystem_state_change_complete(ctx, -1);
738 		return;
739 	}
740 
741 	spdk_for_each_channel(subsystem->tgt,
742 			      subsystem_state_change_on_pg,
743 			      ctx,
744 			      subsystem_state_change_done);
745 }
746 
747 
748 static int
749 nvmf_subsystem_state_change(struct spdk_nvmf_subsystem *subsystem,
750 			    uint32_t nsid,
751 			    enum spdk_nvmf_subsystem_state requested_state,
752 			    spdk_nvmf_subsystem_state_change_done cb_fn,
753 			    void *cb_arg)
754 {
755 	struct nvmf_subsystem_state_change_ctx *ctx;
756 	struct spdk_thread *thread;
757 
758 	thread = spdk_get_thread();
759 	if (thread == NULL) {
760 		return -EINVAL;
761 	}
762 
763 	ctx = calloc(1, sizeof(*ctx));
764 	if (!ctx) {
765 		return -ENOMEM;
766 	}
767 
768 	ctx->subsystem = subsystem;
769 	ctx->nsid = nsid;
770 	ctx->requested_state = requested_state;
771 	ctx->cb_fn = cb_fn;
772 	ctx->cb_arg = cb_arg;
773 	ctx->thread = thread;
774 
775 	pthread_mutex_lock(&subsystem->mutex);
776 	TAILQ_INSERT_TAIL(&subsystem->state_changes, ctx, link);
777 	if (ctx != TAILQ_FIRST(&subsystem->state_changes)) {
778 		pthread_mutex_unlock(&subsystem->mutex);
779 		return 0;
780 	}
781 	pthread_mutex_unlock(&subsystem->mutex);
782 
783 	nvmf_subsystem_do_state_change(ctx);
784 
785 	return 0;
786 }
787 
788 int
789 spdk_nvmf_subsystem_start(struct spdk_nvmf_subsystem *subsystem,
790 			  spdk_nvmf_subsystem_state_change_done cb_fn,
791 			  void *cb_arg)
792 {
793 	return nvmf_subsystem_state_change(subsystem, 0, SPDK_NVMF_SUBSYSTEM_ACTIVE, cb_fn, cb_arg);
794 }
795 
796 int
797 spdk_nvmf_subsystem_stop(struct spdk_nvmf_subsystem *subsystem,
798 			 spdk_nvmf_subsystem_state_change_done cb_fn,
799 			 void *cb_arg)
800 {
801 	return nvmf_subsystem_state_change(subsystem, 0, SPDK_NVMF_SUBSYSTEM_INACTIVE, cb_fn, cb_arg);
802 }
803 
804 int
805 spdk_nvmf_subsystem_pause(struct spdk_nvmf_subsystem *subsystem,
806 			  uint32_t nsid,
807 			  spdk_nvmf_subsystem_state_change_done cb_fn,
808 			  void *cb_arg)
809 {
810 	return nvmf_subsystem_state_change(subsystem, nsid, SPDK_NVMF_SUBSYSTEM_PAUSED, cb_fn, cb_arg);
811 }
812 
813 int
814 spdk_nvmf_subsystem_resume(struct spdk_nvmf_subsystem *subsystem,
815 			   spdk_nvmf_subsystem_state_change_done cb_fn,
816 			   void *cb_arg)
817 {
818 	return nvmf_subsystem_state_change(subsystem, 0, SPDK_NVMF_SUBSYSTEM_ACTIVE, cb_fn, cb_arg);
819 }
820 
821 struct spdk_nvmf_subsystem *
822 spdk_nvmf_subsystem_get_first(struct spdk_nvmf_tgt *tgt)
823 {
824 	return RB_MIN(subsystem_tree, &tgt->subsystems);
825 }
826 
827 struct spdk_nvmf_subsystem *
828 spdk_nvmf_subsystem_get_next(struct spdk_nvmf_subsystem *subsystem)
829 {
830 	if (!subsystem) {
831 		return NULL;
832 	}
833 
834 	return RB_NEXT(subsystem_tree, &tgt->subsystems, subsystem);
835 }
836 
837 static int
838 nvmf_ns_add_host(struct spdk_nvmf_ns *ns, const char *hostnqn)
839 {
840 	struct spdk_nvmf_host *host;
841 
842 	host = calloc(1, sizeof(*host));
843 	if (!host) {
844 		return -ENOMEM;
845 	}
846 	snprintf(host->nqn, sizeof(host->nqn), "%s", hostnqn);
847 	TAILQ_INSERT_HEAD(&ns->hosts, host, link);
848 	return 0;
849 }
850 
851 static void
852 nvmf_ns_remove_host(struct spdk_nvmf_ns *ns, struct spdk_nvmf_host *host)
853 {
854 	TAILQ_REMOVE(&ns->hosts, host, link);
855 	free(host);
856 }
857 
858 static void
859 _async_event_ns_notice(void *_ctrlr)
860 {
861 	struct spdk_nvmf_ctrlr *ctrlr = _ctrlr;
862 
863 	nvmf_ctrlr_async_event_ns_notice(ctrlr);
864 }
865 
866 static void
867 send_async_event_ns_notice(struct spdk_nvmf_ctrlr *ctrlr)
868 {
869 	spdk_thread_send_msg(ctrlr->thread, _async_event_ns_notice, ctrlr);
870 }
871 
872 static int
873 nvmf_ns_visible(struct spdk_nvmf_subsystem *subsystem,
874 		uint32_t nsid,
875 		const char *hostnqn,
876 		bool visible)
877 {
878 	struct spdk_nvmf_ns *ns;
879 	struct spdk_nvmf_ctrlr *ctrlr;
880 	struct spdk_nvmf_host *host;
881 	int rc;
882 
883 	if (!(subsystem->state == SPDK_NVMF_SUBSYSTEM_INACTIVE ||
884 	      subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSED)) {
885 		assert(false);
886 		return -1;
887 	}
888 
889 	if (hostnqn == NULL || !nvmf_nqn_is_valid(hostnqn)) {
890 		return -EINVAL;
891 	}
892 
893 	if (nsid == 0 || nsid > subsystem->max_nsid) {
894 		return -EINVAL;
895 	}
896 
897 	ns = subsystem->ns[nsid - 1];
898 	if (!ns) {
899 		return -ENOENT;
900 	}
901 
902 	if (ns->always_visible) {
903 		/* No individual host control */
904 		return -EPERM;
905 	}
906 
907 	/* Save host info to use for any future controllers. */
908 	host = nvmf_ns_find_host(ns, hostnqn);
909 	if (visible && host == NULL) {
910 		rc = nvmf_ns_add_host(ns, hostnqn);
911 		if (rc) {
912 			return rc;
913 		}
914 	} else if (!visible && host != NULL) {
915 		nvmf_ns_remove_host(ns, host);
916 	}
917 
918 	/* Also apply to existing controllers. */
919 	TAILQ_FOREACH(ctrlr, &subsystem->ctrlrs, link) {
920 		if (strcmp(hostnqn, ctrlr->hostnqn) ||
921 		    spdk_bit_array_get(ctrlr->visible_ns, nsid - 1) == visible) {
922 			continue;
923 		}
924 		if (visible) {
925 			spdk_bit_array_set(ctrlr->visible_ns, nsid - 1);
926 		} else {
927 			spdk_bit_array_clear(ctrlr->visible_ns, nsid - 1);
928 		}
929 		send_async_event_ns_notice(ctrlr);
930 		nvmf_ctrlr_ns_changed(ctrlr, nsid);
931 	}
932 
933 	return 0;
934 }
935 
936 int
937 spdk_nvmf_ns_add_host(struct spdk_nvmf_subsystem *subsystem,
938 		      uint32_t nsid,
939 		      const char *hostnqn,
940 		      uint32_t flags)
941 {
942 	SPDK_DTRACE_PROBE4(spdk_nvmf_ns_add_host,
943 			   subsystem->subnqn,
944 			   nsid,
945 			   hostnqn,
946 			   flags);
947 	return nvmf_ns_visible(subsystem, nsid, hostnqn, true);
948 }
949 
950 int
951 spdk_nvmf_ns_remove_host(struct spdk_nvmf_subsystem *subsystem,
952 			 uint32_t nsid,
953 			 const char *hostnqn,
954 			 uint32_t flags)
955 {
956 	SPDK_DTRACE_PROBE4(spdk_nvmf_ns_remove_host,
957 			   subsystem->subnqn,
958 			   nsid,
959 			   hostnqn,
960 			   flags);
961 	return nvmf_ns_visible(subsystem, nsid, hostnqn, false);
962 }
963 
964 /* Must hold subsystem->mutex while calling this function */
965 static struct spdk_nvmf_host *
966 nvmf_subsystem_find_host(struct spdk_nvmf_subsystem *subsystem, const char *hostnqn)
967 {
968 	struct spdk_nvmf_host *host = NULL;
969 
970 	TAILQ_FOREACH(host, &subsystem->hosts, link) {
971 		if (strcmp(hostnqn, host->nqn) == 0) {
972 			return host;
973 		}
974 	}
975 
976 	return NULL;
977 }
978 
979 int
980 spdk_nvmf_subsystem_add_host_ext(struct spdk_nvmf_subsystem *subsystem,
981 				 const char *hostnqn, struct spdk_nvmf_host_opts *opts)
982 {
983 	struct spdk_nvmf_host *host;
984 	struct spdk_nvmf_transport *transport;
985 	struct spdk_key *key;
986 	int rc;
987 
988 	if (!nvmf_nqn_is_valid(hostnqn)) {
989 		return -EINVAL;
990 	}
991 
992 	pthread_mutex_lock(&subsystem->mutex);
993 
994 	if (nvmf_subsystem_find_host(subsystem, hostnqn)) {
995 		/* This subsystem already allows the specified host. */
996 		pthread_mutex_unlock(&subsystem->mutex);
997 		return -EINVAL;
998 	}
999 
1000 	host = calloc(1, sizeof(*host));
1001 	if (!host) {
1002 		pthread_mutex_unlock(&subsystem->mutex);
1003 		return -ENOMEM;
1004 	}
1005 
1006 	key = SPDK_GET_FIELD(opts, dhchap_key, NULL);
1007 	if (key != NULL) {
1008 		if (!nvmf_auth_is_supported()) {
1009 			SPDK_ERRLOG("NVMe in-band authentication is unsupported\n");
1010 			pthread_mutex_unlock(&subsystem->mutex);
1011 			nvmf_host_free(host);
1012 			return -EINVAL;
1013 		}
1014 		host->dhchap_key = spdk_key_dup(key);
1015 		if (host->dhchap_key == NULL) {
1016 			pthread_mutex_unlock(&subsystem->mutex);
1017 			nvmf_host_free(host);
1018 			return -EINVAL;
1019 		}
1020 		key = SPDK_GET_FIELD(opts, dhchap_ctrlr_key, NULL);
1021 		if (key != NULL) {
1022 			host->dhchap_ctrlr_key = spdk_key_dup(key);
1023 			if (host->dhchap_ctrlr_key == NULL) {
1024 				pthread_mutex_unlock(&subsystem->mutex);
1025 				nvmf_host_free(host);
1026 				return -EINVAL;
1027 			}
1028 		}
1029 	} else if (SPDK_GET_FIELD(opts, dhchap_ctrlr_key, NULL) != NULL) {
1030 		SPDK_ERRLOG("DH-HMAC-CHAP controller key requires host key to be set\n");
1031 		pthread_mutex_unlock(&subsystem->mutex);
1032 		nvmf_host_free(host);
1033 		return -EINVAL;
1034 	}
1035 
1036 	snprintf(host->nqn, sizeof(host->nqn), "%s", hostnqn);
1037 
1038 	SPDK_DTRACE_PROBE2(nvmf_subsystem_add_host, subsystem->subnqn, host->nqn);
1039 
1040 	TAILQ_INSERT_HEAD(&subsystem->hosts, host, link);
1041 
1042 	if (!TAILQ_EMPTY(&subsystem->listeners)) {
1043 		nvmf_update_discovery_log(subsystem->tgt, hostnqn);
1044 	}
1045 
1046 	for (transport = spdk_nvmf_transport_get_first(subsystem->tgt); transport;
1047 	     transport = spdk_nvmf_transport_get_next(transport)) {
1048 		if (transport->ops->subsystem_add_host) {
1049 			rc = transport->ops->subsystem_add_host(transport, subsystem, hostnqn,
1050 								SPDK_GET_FIELD(opts, params, NULL));
1051 			if (rc) {
1052 				SPDK_ERRLOG("Unable to add host to %s transport\n", transport->ops->name);
1053 				/* Remove this host from all transports we've managed to add it to. */
1054 				pthread_mutex_unlock(&subsystem->mutex);
1055 				spdk_nvmf_subsystem_remove_host(subsystem, hostnqn);
1056 				return rc;
1057 			}
1058 		}
1059 	}
1060 
1061 	pthread_mutex_unlock(&subsystem->mutex);
1062 
1063 	return 0;
1064 }
1065 
1066 int
1067 spdk_nvmf_subsystem_add_host(struct spdk_nvmf_subsystem *subsystem, const char *hostnqn,
1068 			     const struct spdk_json_val *params)
1069 {
1070 	struct spdk_nvmf_host_opts opts = {};
1071 
1072 	opts.size = SPDK_SIZEOF(&opts, params);
1073 	opts.params = params;
1074 
1075 	return spdk_nvmf_subsystem_add_host_ext(subsystem, hostnqn, &opts);
1076 }
1077 
1078 int
1079 spdk_nvmf_subsystem_remove_host(struct spdk_nvmf_subsystem *subsystem, const char *hostnqn)
1080 {
1081 	struct spdk_nvmf_host *host;
1082 	struct spdk_nvmf_transport *transport;
1083 
1084 	pthread_mutex_lock(&subsystem->mutex);
1085 
1086 	host = nvmf_subsystem_find_host(subsystem, hostnqn);
1087 	if (host == NULL) {
1088 		pthread_mutex_unlock(&subsystem->mutex);
1089 		return -ENOENT;
1090 	}
1091 
1092 	SPDK_DTRACE_PROBE2(nvmf_subsystem_remove_host, subsystem->subnqn, host->nqn);
1093 
1094 	nvmf_subsystem_remove_host(subsystem, host);
1095 
1096 	if (!TAILQ_EMPTY(&subsystem->listeners)) {
1097 		nvmf_update_discovery_log(subsystem->tgt, hostnqn);
1098 	}
1099 
1100 	for (transport = spdk_nvmf_transport_get_first(subsystem->tgt); transport;
1101 	     transport = spdk_nvmf_transport_get_next(transport)) {
1102 		if (transport->ops->subsystem_remove_host) {
1103 			transport->ops->subsystem_remove_host(transport, subsystem, hostnqn);
1104 		}
1105 	}
1106 
1107 	pthread_mutex_unlock(&subsystem->mutex);
1108 
1109 	return 0;
1110 }
1111 
1112 struct nvmf_subsystem_disconnect_host_ctx {
1113 	struct spdk_nvmf_subsystem		*subsystem;
1114 	char					*hostnqn;
1115 	spdk_nvmf_tgt_subsystem_listen_done_fn	cb_fn;
1116 	void					*cb_arg;
1117 };
1118 
1119 static void
1120 nvmf_subsystem_disconnect_host_fini(struct spdk_io_channel_iter *i, int status)
1121 {
1122 	struct nvmf_subsystem_disconnect_host_ctx *ctx;
1123 
1124 	ctx = spdk_io_channel_iter_get_ctx(i);
1125 
1126 	if (ctx->cb_fn) {
1127 		ctx->cb_fn(ctx->cb_arg, status);
1128 	}
1129 	free(ctx->hostnqn);
1130 	free(ctx);
1131 }
1132 
1133 static void
1134 nvmf_subsystem_disconnect_qpairs_by_host(struct spdk_io_channel_iter *i)
1135 {
1136 	struct nvmf_subsystem_disconnect_host_ctx *ctx;
1137 	struct spdk_nvmf_poll_group *group;
1138 	struct spdk_io_channel *ch;
1139 	struct spdk_nvmf_qpair *qpair, *tmp_qpair;
1140 	struct spdk_nvmf_ctrlr *ctrlr;
1141 
1142 	ctx = spdk_io_channel_iter_get_ctx(i);
1143 	ch = spdk_io_channel_iter_get_channel(i);
1144 	group = spdk_io_channel_get_ctx(ch);
1145 
1146 	TAILQ_FOREACH_SAFE(qpair, &group->qpairs, link, tmp_qpair) {
1147 		ctrlr = qpair->ctrlr;
1148 
1149 		if (ctrlr == NULL || ctrlr->subsys != ctx->subsystem) {
1150 			continue;
1151 		}
1152 
1153 		if (strncmp(ctrlr->hostnqn, ctx->hostnqn, sizeof(ctrlr->hostnqn)) == 0) {
1154 			/* Right now this does not wait for the queue pairs to actually disconnect. */
1155 			spdk_nvmf_qpair_disconnect(qpair);
1156 		}
1157 	}
1158 	spdk_for_each_channel_continue(i, 0);
1159 }
1160 
1161 int
1162 spdk_nvmf_subsystem_disconnect_host(struct spdk_nvmf_subsystem *subsystem,
1163 				    const char *hostnqn,
1164 				    spdk_nvmf_tgt_subsystem_listen_done_fn cb_fn,
1165 				    void *cb_arg)
1166 {
1167 	struct nvmf_subsystem_disconnect_host_ctx *ctx;
1168 
1169 	ctx = calloc(1, sizeof(struct nvmf_subsystem_disconnect_host_ctx));
1170 	if (ctx == NULL) {
1171 		return -ENOMEM;
1172 	}
1173 
1174 	ctx->hostnqn = strdup(hostnqn);
1175 	if (ctx->hostnqn == NULL) {
1176 		free(ctx);
1177 		return -ENOMEM;
1178 	}
1179 
1180 	ctx->subsystem = subsystem;
1181 	ctx->cb_fn = cb_fn;
1182 	ctx->cb_arg = cb_arg;
1183 
1184 	spdk_for_each_channel(subsystem->tgt, nvmf_subsystem_disconnect_qpairs_by_host, ctx,
1185 			      nvmf_subsystem_disconnect_host_fini);
1186 
1187 	return 0;
1188 }
1189 
1190 int
1191 spdk_nvmf_subsystem_set_allow_any_host(struct spdk_nvmf_subsystem *subsystem, bool allow_any_host)
1192 {
1193 	pthread_mutex_lock(&subsystem->mutex);
1194 	subsystem->allow_any_host = allow_any_host;
1195 	if (!TAILQ_EMPTY(&subsystem->listeners)) {
1196 		nvmf_update_discovery_log(subsystem->tgt, NULL);
1197 	}
1198 	pthread_mutex_unlock(&subsystem->mutex);
1199 
1200 	return 0;
1201 }
1202 
1203 bool
1204 spdk_nvmf_subsystem_get_allow_any_host(const struct spdk_nvmf_subsystem *subsystem)
1205 {
1206 	bool allow_any_host;
1207 	struct spdk_nvmf_subsystem *sub;
1208 
1209 	/* Technically, taking the mutex modifies data in the subsystem. But the const
1210 	 * is still important to convey that this doesn't mutate any other data. Cast
1211 	 * it away to work around this. */
1212 	sub = (struct spdk_nvmf_subsystem *)subsystem;
1213 
1214 	pthread_mutex_lock(&sub->mutex);
1215 	allow_any_host = sub->allow_any_host;
1216 	pthread_mutex_unlock(&sub->mutex);
1217 
1218 	return allow_any_host;
1219 }
1220 
1221 bool
1222 spdk_nvmf_subsystem_host_allowed(struct spdk_nvmf_subsystem *subsystem, const char *hostnqn)
1223 {
1224 	bool allowed;
1225 
1226 	if (!hostnqn) {
1227 		return false;
1228 	}
1229 
1230 	pthread_mutex_lock(&subsystem->mutex);
1231 
1232 	if (subsystem->allow_any_host) {
1233 		pthread_mutex_unlock(&subsystem->mutex);
1234 		return true;
1235 	}
1236 
1237 	allowed =  nvmf_subsystem_find_host(subsystem, hostnqn) != NULL;
1238 	pthread_mutex_unlock(&subsystem->mutex);
1239 
1240 	return allowed;
1241 }
1242 
1243 bool
1244 nvmf_subsystem_host_auth_required(struct spdk_nvmf_subsystem *subsystem, const char *hostnqn)
1245 {
1246 	struct spdk_nvmf_host *host;
1247 	bool status;
1248 
1249 	pthread_mutex_lock(&subsystem->mutex);
1250 	host = nvmf_subsystem_find_host(subsystem, hostnqn);
1251 	status = host != NULL && host->dhchap_key != NULL;
1252 	pthread_mutex_unlock(&subsystem->mutex);
1253 
1254 	return status;
1255 }
1256 
1257 struct spdk_key *
1258 nvmf_subsystem_get_dhchap_key(struct spdk_nvmf_subsystem *subsystem, const char *hostnqn,
1259 			      enum nvmf_auth_key_type type)
1260 {
1261 	struct spdk_nvmf_host *host;
1262 	struct spdk_key *key = NULL;
1263 
1264 	pthread_mutex_lock(&subsystem->mutex);
1265 	host = nvmf_subsystem_find_host(subsystem, hostnqn);
1266 	if (host != NULL) {
1267 		switch (type) {
1268 		case NVMF_AUTH_KEY_HOST:
1269 			key = host->dhchap_key;
1270 			break;
1271 		case NVMF_AUTH_KEY_CTRLR:
1272 			key = host->dhchap_ctrlr_key;
1273 			break;
1274 		}
1275 		if (key != NULL) {
1276 			key = spdk_key_dup(key);
1277 		}
1278 	}
1279 	pthread_mutex_unlock(&subsystem->mutex);
1280 
1281 	return key;
1282 }
1283 
1284 struct spdk_nvmf_host *
1285 spdk_nvmf_subsystem_get_first_host(struct spdk_nvmf_subsystem *subsystem)
1286 {
1287 	return TAILQ_FIRST(&subsystem->hosts);
1288 }
1289 
1290 
1291 struct spdk_nvmf_host *
1292 spdk_nvmf_subsystem_get_next_host(struct spdk_nvmf_subsystem *subsystem,
1293 				  struct spdk_nvmf_host *prev_host)
1294 {
1295 	return TAILQ_NEXT(prev_host, link);
1296 }
1297 
1298 const char *
1299 spdk_nvmf_host_get_nqn(const struct spdk_nvmf_host *host)
1300 {
1301 	return host->nqn;
1302 }
1303 
1304 struct spdk_nvmf_subsystem_listener *
1305 nvmf_subsystem_find_listener(struct spdk_nvmf_subsystem *subsystem,
1306 			     const struct spdk_nvme_transport_id *trid)
1307 {
1308 	struct spdk_nvmf_subsystem_listener *listener;
1309 
1310 	TAILQ_FOREACH(listener, &subsystem->listeners, link) {
1311 		if (spdk_nvme_transport_id_compare(listener->trid, trid) == 0) {
1312 			return listener;
1313 		}
1314 	}
1315 
1316 	return NULL;
1317 }
1318 
1319 /**
1320  * Function to be called once the target is listening.
1321  *
1322  * \param ctx Context argument passed to this function.
1323  * \param status 0 if it completed successfully, or negative errno if it failed.
1324  */
1325 static void
1326 _nvmf_subsystem_add_listener_done(void *ctx, int status)
1327 {
1328 	struct spdk_nvmf_subsystem_listener *listener = ctx;
1329 
1330 	if (status) {
1331 		listener->cb_fn(listener->cb_arg, status);
1332 		free(listener);
1333 		return;
1334 	}
1335 
1336 	TAILQ_INSERT_HEAD(&listener->subsystem->listeners, listener, link);
1337 	nvmf_update_discovery_log(listener->subsystem->tgt, NULL);
1338 	listener->cb_fn(listener->cb_arg, status);
1339 }
1340 
1341 void
1342 spdk_nvmf_subsystem_listener_opts_init(struct spdk_nvmf_listener_opts *opts, size_t size)
1343 {
1344 	if (opts == NULL) {
1345 		SPDK_ERRLOG("opts should not be NULL\n");
1346 		assert(false);
1347 		return;
1348 	}
1349 	if (size == 0) {
1350 		SPDK_ERRLOG("size should not be zero\n");
1351 		assert(false);
1352 		return;
1353 	}
1354 
1355 	memset(opts, 0, size);
1356 	opts->opts_size = size;
1357 
1358 #define FIELD_OK(field) \
1359 	offsetof(struct spdk_nvmf_listener_opts, field) + sizeof(opts->field) <= size
1360 
1361 #define SET_FIELD(field, value) \
1362 	if (FIELD_OK(field)) { \
1363 		opts->field = value; \
1364 	} \
1365 
1366 	SET_FIELD(secure_channel, false);
1367 	SET_FIELD(ana_state, SPDK_NVME_ANA_OPTIMIZED_STATE);
1368 	SET_FIELD(sock_impl, NULL);
1369 
1370 #undef FIELD_OK
1371 #undef SET_FIELD
1372 }
1373 
1374 static int
1375 listener_opts_copy(struct spdk_nvmf_listener_opts *src, struct spdk_nvmf_listener_opts *dst)
1376 {
1377 	if (src->opts_size == 0) {
1378 		SPDK_ERRLOG("source structure size should not be zero\n");
1379 		assert(false);
1380 		return -EINVAL;
1381 	}
1382 
1383 	memset(dst, 0, sizeof(*dst));
1384 	dst->opts_size = src->opts_size;
1385 
1386 #define FIELD_OK(field) \
1387 	offsetof(struct spdk_nvmf_listener_opts, field) + sizeof(src->field) <= src->opts_size
1388 
1389 #define SET_FIELD(field) \
1390 	if (FIELD_OK(field)) { \
1391 		dst->field = src->field; \
1392 	} \
1393 
1394 	SET_FIELD(secure_channel);
1395 	SET_FIELD(ana_state);
1396 	SET_FIELD(sock_impl);
1397 	/* We should not remove this statement, but need to update the assert statement
1398 	 * if we add a new field, and also add a corresponding SET_FIELD statement. */
1399 	SPDK_STATIC_ASSERT(sizeof(struct spdk_nvmf_listener_opts) == 24, "Incorrect size");
1400 
1401 #undef SET_FIELD
1402 #undef FIELD_OK
1403 
1404 	return 0;
1405 }
1406 
1407 static void
1408 _nvmf_subsystem_add_listener(struct spdk_nvmf_subsystem *subsystem,
1409 			     struct spdk_nvme_transport_id *trid,
1410 			     spdk_nvmf_tgt_subsystem_listen_done_fn cb_fn,
1411 			     void *cb_arg, struct spdk_nvmf_listener_opts *opts)
1412 {
1413 	struct spdk_nvmf_transport *transport;
1414 	struct spdk_nvmf_subsystem_listener *listener;
1415 	struct spdk_nvmf_listener *tr_listener;
1416 	uint32_t i;
1417 	uint32_t id;
1418 	int rc = 0;
1419 
1420 	assert(cb_fn != NULL);
1421 
1422 	if (!(subsystem->state == SPDK_NVMF_SUBSYSTEM_INACTIVE ||
1423 	      subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSED)) {
1424 		cb_fn(cb_arg, -EAGAIN);
1425 		return;
1426 	}
1427 
1428 	if (nvmf_subsystem_find_listener(subsystem, trid)) {
1429 		/* Listener already exists in this subsystem */
1430 		cb_fn(cb_arg, 0);
1431 		return;
1432 	}
1433 
1434 	transport = spdk_nvmf_tgt_get_transport(subsystem->tgt, trid->trstring);
1435 	if (!transport) {
1436 		SPDK_ERRLOG("Unable to find %s transport. The transport must be created first also make sure it is properly registered.\n",
1437 			    trid->trstring);
1438 		cb_fn(cb_arg, -EINVAL);
1439 		return;
1440 	}
1441 
1442 	tr_listener = nvmf_transport_find_listener(transport, trid);
1443 	if (!tr_listener) {
1444 		SPDK_ERRLOG("Cannot find transport listener for %s\n", trid->traddr);
1445 		cb_fn(cb_arg, -EINVAL);
1446 		return;
1447 	}
1448 
1449 	listener = calloc(1, sizeof(*listener));
1450 	if (!listener) {
1451 		cb_fn(cb_arg, -ENOMEM);
1452 		return;
1453 	}
1454 
1455 	listener->trid = &tr_listener->trid;
1456 	listener->transport = transport;
1457 	listener->cb_fn = cb_fn;
1458 	listener->cb_arg = cb_arg;
1459 	listener->subsystem = subsystem;
1460 	listener->ana_state = calloc(subsystem->max_nsid, sizeof(enum spdk_nvme_ana_state));
1461 	if (!listener->ana_state) {
1462 		free(listener);
1463 		cb_fn(cb_arg, -ENOMEM);
1464 		return;
1465 	}
1466 
1467 	spdk_nvmf_subsystem_listener_opts_init(&listener->opts, sizeof(listener->opts));
1468 	if (opts != NULL) {
1469 		rc = listener_opts_copy(opts, &listener->opts);
1470 		if (rc) {
1471 			SPDK_ERRLOG("Unable to copy listener options\n");
1472 			free(listener->ana_state);
1473 			free(listener);
1474 			cb_fn(cb_arg, -EINVAL);
1475 			return;
1476 		}
1477 	}
1478 
1479 	id = spdk_bit_array_find_first_clear(subsystem->used_listener_ids, 0);
1480 	if (id == UINT32_MAX) {
1481 		SPDK_ERRLOG("Cannot add any more listeners\n");
1482 		free(listener->ana_state);
1483 		free(listener->opts.sock_impl);
1484 		free(listener);
1485 		cb_fn(cb_arg, -EINVAL);
1486 		return;
1487 	}
1488 
1489 	spdk_bit_array_set(subsystem->used_listener_ids, id);
1490 	listener->id = id;
1491 
1492 	for (i = 0; i < subsystem->max_nsid; i++) {
1493 		listener->ana_state[i] = listener->opts.ana_state;
1494 	}
1495 
1496 	if (transport->ops->listen_associate != NULL) {
1497 		rc = transport->ops->listen_associate(transport, subsystem, trid);
1498 	}
1499 
1500 	SPDK_DTRACE_PROBE4(nvmf_subsystem_add_listener, subsystem->subnqn, listener->trid->trtype,
1501 			   listener->trid->traddr, listener->trid->trsvcid);
1502 
1503 	_nvmf_subsystem_add_listener_done(listener, rc);
1504 }
1505 
1506 void
1507 spdk_nvmf_subsystem_add_listener(struct spdk_nvmf_subsystem *subsystem,
1508 				 struct spdk_nvme_transport_id *trid,
1509 				 spdk_nvmf_tgt_subsystem_listen_done_fn cb_fn,
1510 				 void *cb_arg)
1511 {
1512 	_nvmf_subsystem_add_listener(subsystem, trid, cb_fn, cb_arg, NULL);
1513 }
1514 
1515 void
1516 spdk_nvmf_subsystem_add_listener_ext(struct spdk_nvmf_subsystem *subsystem,
1517 				     struct spdk_nvme_transport_id *trid,
1518 				     spdk_nvmf_tgt_subsystem_listen_done_fn cb_fn,
1519 				     void *cb_arg, struct spdk_nvmf_listener_opts *opts)
1520 {
1521 	_nvmf_subsystem_add_listener(subsystem, trid, cb_fn, cb_arg, opts);
1522 }
1523 
1524 int
1525 spdk_nvmf_subsystem_remove_listener(struct spdk_nvmf_subsystem *subsystem,
1526 				    const struct spdk_nvme_transport_id *trid)
1527 {
1528 	struct spdk_nvmf_subsystem_listener *listener;
1529 
1530 	if (!(subsystem->state == SPDK_NVMF_SUBSYSTEM_INACTIVE ||
1531 	      subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSED)) {
1532 		return -EAGAIN;
1533 	}
1534 
1535 	listener = nvmf_subsystem_find_listener(subsystem, trid);
1536 	if (listener == NULL) {
1537 		return -ENOENT;
1538 	}
1539 
1540 	SPDK_DTRACE_PROBE4(nvmf_subsystem_remove_listener, subsystem->subnqn, listener->trid->trtype,
1541 			   listener->trid->traddr, listener->trid->trsvcid);
1542 
1543 	_nvmf_subsystem_remove_listener(subsystem, listener, false);
1544 
1545 	return 0;
1546 }
1547 
1548 void
1549 nvmf_subsystem_remove_all_listeners(struct spdk_nvmf_subsystem *subsystem,
1550 				    bool stop)
1551 {
1552 	struct spdk_nvmf_subsystem_listener *listener, *listener_tmp;
1553 
1554 	TAILQ_FOREACH_SAFE(listener, &subsystem->listeners, link, listener_tmp) {
1555 		_nvmf_subsystem_remove_listener(subsystem, listener, stop);
1556 	}
1557 }
1558 
1559 bool
1560 spdk_nvmf_subsystem_listener_allowed(struct spdk_nvmf_subsystem *subsystem,
1561 				     const struct spdk_nvme_transport_id *trid)
1562 {
1563 	struct spdk_nvmf_subsystem_listener *listener;
1564 
1565 	TAILQ_FOREACH(listener, &subsystem->listeners, link) {
1566 		if (spdk_nvme_transport_id_compare(listener->trid, trid) == 0) {
1567 			return true;
1568 		}
1569 	}
1570 
1571 	if (!strcmp(subsystem->subnqn, SPDK_NVMF_DISCOVERY_NQN)) {
1572 		SPDK_WARNLOG("Allowing connection to discovery subsystem on %s/%s/%s, "
1573 			     "even though this listener was not added to the discovery "
1574 			     "subsystem.  This behavior is deprecated and will be removed "
1575 			     "in a future release.\n",
1576 			     spdk_nvme_transport_id_trtype_str(trid->trtype), trid->traddr, trid->trsvcid);
1577 		return true;
1578 	}
1579 
1580 	return false;
1581 }
1582 
1583 struct spdk_nvmf_subsystem_listener *
1584 spdk_nvmf_subsystem_get_first_listener(struct spdk_nvmf_subsystem *subsystem)
1585 {
1586 	return TAILQ_FIRST(&subsystem->listeners);
1587 }
1588 
1589 struct spdk_nvmf_subsystem_listener *
1590 spdk_nvmf_subsystem_get_next_listener(struct spdk_nvmf_subsystem *subsystem,
1591 				      struct spdk_nvmf_subsystem_listener *prev_listener)
1592 {
1593 	return TAILQ_NEXT(prev_listener, link);
1594 }
1595 
1596 const struct spdk_nvme_transport_id *
1597 spdk_nvmf_subsystem_listener_get_trid(struct spdk_nvmf_subsystem_listener *listener)
1598 {
1599 	return listener->trid;
1600 }
1601 
1602 void
1603 spdk_nvmf_subsystem_allow_any_listener(struct spdk_nvmf_subsystem *subsystem,
1604 				       bool allow_any_listener)
1605 {
1606 	subsystem->flags.allow_any_listener = allow_any_listener;
1607 }
1608 
1609 bool
1610 spdk_nvmf_subsystem_any_listener_allowed(struct spdk_nvmf_subsystem *subsystem)
1611 {
1612 	return subsystem->flags.allow_any_listener;
1613 }
1614 
1615 struct subsystem_update_ns_ctx {
1616 	struct spdk_nvmf_subsystem *subsystem;
1617 
1618 	spdk_nvmf_subsystem_state_change_done cb_fn;
1619 	void *cb_arg;
1620 };
1621 
1622 static void
1623 subsystem_update_ns_done(struct spdk_io_channel_iter *i, int status)
1624 {
1625 	struct subsystem_update_ns_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
1626 
1627 	if (ctx->cb_fn) {
1628 		ctx->cb_fn(ctx->subsystem, ctx->cb_arg, status);
1629 	}
1630 	free(ctx);
1631 }
1632 
1633 static void
1634 subsystem_update_ns_on_pg(struct spdk_io_channel_iter *i)
1635 {
1636 	int rc;
1637 	struct subsystem_update_ns_ctx *ctx;
1638 	struct spdk_nvmf_poll_group *group;
1639 	struct spdk_nvmf_subsystem *subsystem;
1640 
1641 	ctx = spdk_io_channel_iter_get_ctx(i);
1642 	group = spdk_io_channel_get_ctx(spdk_io_channel_iter_get_channel(i));
1643 	subsystem = ctx->subsystem;
1644 
1645 	rc = nvmf_poll_group_update_subsystem(group, subsystem);
1646 	spdk_for_each_channel_continue(i, rc);
1647 }
1648 
1649 static int
1650 nvmf_subsystem_update_ns(struct spdk_nvmf_subsystem *subsystem,
1651 			 spdk_nvmf_subsystem_state_change_done cb_fn, void *cb_arg)
1652 {
1653 	struct subsystem_update_ns_ctx *ctx;
1654 
1655 	ctx = calloc(1, sizeof(*ctx));
1656 	if (ctx == NULL) {
1657 		SPDK_ERRLOG("Can't alloc subsystem poll group update context\n");
1658 		return -ENOMEM;
1659 	}
1660 	ctx->subsystem = subsystem;
1661 	ctx->cb_fn = cb_fn;
1662 	ctx->cb_arg = cb_arg;
1663 
1664 	spdk_for_each_channel(subsystem->tgt,
1665 			      subsystem_update_ns_on_pg,
1666 			      ctx,
1667 			      subsystem_update_ns_done);
1668 	return 0;
1669 }
1670 
1671 static void
1672 nvmf_subsystem_ns_changed(struct spdk_nvmf_subsystem *subsystem, uint32_t nsid)
1673 {
1674 	struct spdk_nvmf_ctrlr *ctrlr;
1675 
1676 	TAILQ_FOREACH(ctrlr, &subsystem->ctrlrs, link) {
1677 		if (nvmf_ctrlr_ns_is_visible(ctrlr, nsid)) {
1678 			nvmf_ctrlr_ns_changed(ctrlr, nsid);
1679 		}
1680 	}
1681 }
1682 
1683 static uint32_t nvmf_ns_reservation_clear_all_registrants(struct spdk_nvmf_ns *ns);
1684 
1685 int
1686 spdk_nvmf_subsystem_remove_ns(struct spdk_nvmf_subsystem *subsystem, uint32_t nsid)
1687 {
1688 	struct spdk_nvmf_transport *transport;
1689 	struct spdk_nvmf_ns *ns;
1690 	struct spdk_nvmf_host *host, *tmp;
1691 	struct spdk_nvmf_ctrlr *ctrlr;
1692 
1693 	if (!(subsystem->state == SPDK_NVMF_SUBSYSTEM_INACTIVE ||
1694 	      subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSED)) {
1695 		assert(false);
1696 		return -1;
1697 	}
1698 
1699 	if (nsid == 0 || nsid > subsystem->max_nsid) {
1700 		return -1;
1701 	}
1702 
1703 	ns = subsystem->ns[nsid - 1];
1704 	if (!ns) {
1705 		return -1;
1706 	}
1707 
1708 	subsystem->ns[nsid - 1] = NULL;
1709 
1710 	assert(ns->anagrpid - 1 < subsystem->max_nsid);
1711 	assert(subsystem->ana_group[ns->anagrpid - 1] > 0);
1712 
1713 	subsystem->ana_group[ns->anagrpid - 1]--;
1714 
1715 	TAILQ_FOREACH_SAFE(host, &ns->hosts, link, tmp) {
1716 		nvmf_ns_remove_host(ns, host);
1717 	}
1718 
1719 	free(ns->ptpl_file);
1720 	nvmf_ns_reservation_clear_all_registrants(ns);
1721 	spdk_bdev_module_release_bdev(ns->bdev);
1722 	spdk_bdev_close(ns->desc);
1723 	free(ns);
1724 
1725 	if (subsystem->fdp_supported && !spdk_nvmf_subsystem_get_first_ns(subsystem)) {
1726 		subsystem->fdp_supported = false;
1727 		SPDK_DEBUGLOG(nvmf, "Subsystem with id: %u doesn't have FDP capability.\n",
1728 			      subsystem->id);
1729 	}
1730 
1731 	for (transport = spdk_nvmf_transport_get_first(subsystem->tgt); transport;
1732 	     transport = spdk_nvmf_transport_get_next(transport)) {
1733 		if (transport->ops->subsystem_remove_ns) {
1734 			transport->ops->subsystem_remove_ns(transport, subsystem, nsid);
1735 		}
1736 	}
1737 
1738 	nvmf_subsystem_ns_changed(subsystem, nsid);
1739 
1740 	TAILQ_FOREACH(ctrlr, &subsystem->ctrlrs, link) {
1741 		spdk_bit_array_clear(ctrlr->visible_ns, nsid - 1);
1742 	}
1743 
1744 	return 0;
1745 }
1746 
1747 struct subsystem_ns_change_ctx {
1748 	struct spdk_nvmf_subsystem		*subsystem;
1749 	spdk_nvmf_subsystem_state_change_done	cb_fn;
1750 	uint32_t				nsid;
1751 };
1752 
1753 static void
1754 _nvmf_ns_hot_remove(struct spdk_nvmf_subsystem *subsystem,
1755 		    void *cb_arg, int status)
1756 {
1757 	struct subsystem_ns_change_ctx *ctx = cb_arg;
1758 	int rc;
1759 
1760 	rc = spdk_nvmf_subsystem_remove_ns(subsystem, ctx->nsid);
1761 	if (rc != 0) {
1762 		SPDK_ERRLOG("Failed to make changes to NVME-oF subsystem with id: %u\n", subsystem->id);
1763 	}
1764 
1765 	rc = spdk_nvmf_subsystem_resume(subsystem, NULL, NULL);
1766 	if (rc != 0) {
1767 		SPDK_ERRLOG("Failed to resume NVME-oF subsystem with id: %u\n", subsystem->id);
1768 	}
1769 
1770 	free(ctx);
1771 }
1772 
1773 static void
1774 nvmf_ns_change_msg(void *ns_ctx)
1775 {
1776 	struct subsystem_ns_change_ctx *ctx = ns_ctx;
1777 	int rc;
1778 
1779 	SPDK_DTRACE_PROBE2(nvmf_ns_change, ctx->nsid, ctx->subsystem->subnqn);
1780 
1781 	rc = spdk_nvmf_subsystem_pause(ctx->subsystem, ctx->nsid, ctx->cb_fn, ctx);
1782 	if (rc) {
1783 		if (rc == -EBUSY) {
1784 			/* Try again, this is not a permanent situation. */
1785 			spdk_thread_send_msg(spdk_get_thread(), nvmf_ns_change_msg, ctx);
1786 		} else {
1787 			free(ctx);
1788 			SPDK_ERRLOG("Unable to pause subsystem to process namespace removal!\n");
1789 		}
1790 	}
1791 }
1792 
1793 static void
1794 nvmf_ns_hot_remove(void *remove_ctx)
1795 {
1796 	struct spdk_nvmf_ns *ns = remove_ctx;
1797 	struct subsystem_ns_change_ctx *ns_ctx;
1798 	int rc;
1799 
1800 	/* We have to allocate a new context because this op
1801 	 * is asynchronous and we could lose the ns in the middle.
1802 	 */
1803 	ns_ctx = calloc(1, sizeof(struct subsystem_ns_change_ctx));
1804 	if (!ns_ctx) {
1805 		SPDK_ERRLOG("Unable to allocate context to process namespace removal!\n");
1806 		return;
1807 	}
1808 
1809 	ns_ctx->subsystem = ns->subsystem;
1810 	ns_ctx->nsid = ns->opts.nsid;
1811 	ns_ctx->cb_fn = _nvmf_ns_hot_remove;
1812 
1813 	rc = spdk_nvmf_subsystem_pause(ns->subsystem, ns_ctx->nsid, _nvmf_ns_hot_remove, ns_ctx);
1814 	if (rc) {
1815 		if (rc == -EBUSY) {
1816 			/* Try again, this is not a permanent situation. */
1817 			spdk_thread_send_msg(spdk_get_thread(), nvmf_ns_change_msg, ns_ctx);
1818 		} else {
1819 			SPDK_ERRLOG("Unable to pause subsystem to process namespace removal!\n");
1820 			free(ns_ctx);
1821 		}
1822 	}
1823 }
1824 
1825 static void
1826 _nvmf_ns_resize(struct spdk_nvmf_subsystem *subsystem, void *cb_arg, int status)
1827 {
1828 	struct subsystem_ns_change_ctx *ctx = cb_arg;
1829 
1830 	nvmf_subsystem_ns_changed(subsystem, ctx->nsid);
1831 	if (spdk_nvmf_subsystem_resume(subsystem, NULL, NULL) != 0) {
1832 		SPDK_ERRLOG("Failed to resume NVME-oF subsystem with id: %u\n", subsystem->id);
1833 	}
1834 
1835 	free(ctx);
1836 }
1837 
1838 static void
1839 nvmf_ns_resize(void *event_ctx)
1840 {
1841 	struct spdk_nvmf_ns *ns = event_ctx;
1842 	struct subsystem_ns_change_ctx *ns_ctx;
1843 	int rc;
1844 
1845 	/* We have to allocate a new context because this op
1846 	 * is asynchronous and we could lose the ns in the middle.
1847 	 */
1848 	ns_ctx = calloc(1, sizeof(struct subsystem_ns_change_ctx));
1849 	if (!ns_ctx) {
1850 		SPDK_ERRLOG("Unable to allocate context to process namespace removal!\n");
1851 		return;
1852 	}
1853 
1854 	ns_ctx->subsystem = ns->subsystem;
1855 	ns_ctx->nsid = ns->opts.nsid;
1856 	ns_ctx->cb_fn = _nvmf_ns_resize;
1857 
1858 	/* Specify 0 for the nsid here, because we do not need to pause the namespace.
1859 	 * Namespaces can only be resized bigger, so there is no need to quiesce I/O.
1860 	 */
1861 	rc = spdk_nvmf_subsystem_pause(ns->subsystem, 0, _nvmf_ns_resize, ns_ctx);
1862 	if (rc) {
1863 		if (rc == -EBUSY) {
1864 			/* Try again, this is not a permanent situation. */
1865 			spdk_thread_send_msg(spdk_get_thread(), nvmf_ns_change_msg, ns_ctx);
1866 		} else {
1867 			SPDK_ERRLOG("Unable to pause subsystem to process namespace resize!\n");
1868 			free(ns_ctx);
1869 		}
1870 	}
1871 }
1872 
1873 static void
1874 nvmf_ns_event(enum spdk_bdev_event_type type,
1875 	      struct spdk_bdev *bdev,
1876 	      void *event_ctx)
1877 {
1878 	SPDK_DEBUGLOG(nvmf, "Bdev event: type %d, name %s, subsystem_id %d, ns_id %d\n",
1879 		      type,
1880 		      spdk_bdev_get_name(bdev),
1881 		      ((struct spdk_nvmf_ns *)event_ctx)->subsystem->id,
1882 		      ((struct spdk_nvmf_ns *)event_ctx)->nsid);
1883 
1884 	switch (type) {
1885 	case SPDK_BDEV_EVENT_REMOVE:
1886 		nvmf_ns_hot_remove(event_ctx);
1887 		break;
1888 	case SPDK_BDEV_EVENT_RESIZE:
1889 		nvmf_ns_resize(event_ctx);
1890 		break;
1891 	default:
1892 		SPDK_NOTICELOG("Unsupported bdev event: type %d\n", type);
1893 		break;
1894 	}
1895 }
1896 
1897 void
1898 spdk_nvmf_ns_opts_get_defaults(struct spdk_nvmf_ns_opts *opts, size_t opts_size)
1899 {
1900 	if (!opts) {
1901 		SPDK_ERRLOG("opts should not be NULL.\n");
1902 		return;
1903 	}
1904 
1905 	if (!opts_size) {
1906 		SPDK_ERRLOG("opts_size should not be zero.\n");
1907 		return;
1908 	}
1909 
1910 	memset(opts, 0, opts_size);
1911 	opts->opts_size = opts_size;
1912 
1913 #define FIELD_OK(field) \
1914 	offsetof(struct spdk_nvmf_ns_opts, field) + sizeof(opts->field) <= opts_size
1915 
1916 #define SET_FIELD(field, value) \
1917 	if (FIELD_OK(field)) { \
1918 		opts->field = value; \
1919 	} \
1920 
1921 	/* All current fields are set to 0 by default. */
1922 	SET_FIELD(nsid, 0);
1923 	if (FIELD_OK(nguid)) {
1924 		memset(opts->nguid, 0, sizeof(opts->nguid));
1925 	}
1926 	if (FIELD_OK(eui64)) {
1927 		memset(opts->eui64, 0, sizeof(opts->eui64));
1928 	}
1929 	if (FIELD_OK(uuid)) {
1930 		spdk_uuid_set_null(&opts->uuid);
1931 	}
1932 	SET_FIELD(anagrpid, 0);
1933 	SET_FIELD(transport_specific, NULL);
1934 
1935 #undef FIELD_OK
1936 #undef SET_FIELD
1937 }
1938 
1939 static void
1940 nvmf_ns_opts_copy(struct spdk_nvmf_ns_opts *opts,
1941 		  const struct spdk_nvmf_ns_opts *user_opts,
1942 		  size_t opts_size)
1943 {
1944 #define FIELD_OK(field)	\
1945 	offsetof(struct spdk_nvmf_ns_opts, field) + sizeof(opts->field) <= user_opts->opts_size
1946 
1947 #define SET_FIELD(field) \
1948 	if (FIELD_OK(field)) { \
1949 		opts->field = user_opts->field;	\
1950 	} \
1951 
1952 	SET_FIELD(nsid);
1953 	if (FIELD_OK(nguid)) {
1954 		memcpy(opts->nguid, user_opts->nguid, sizeof(opts->nguid));
1955 	}
1956 	if (FIELD_OK(eui64)) {
1957 		memcpy(opts->eui64, user_opts->eui64, sizeof(opts->eui64));
1958 	}
1959 	if (FIELD_OK(uuid)) {
1960 		spdk_uuid_copy(&opts->uuid, &user_opts->uuid);
1961 	}
1962 	SET_FIELD(anagrpid);
1963 	SET_FIELD(no_auto_visible);
1964 	SET_FIELD(transport_specific);
1965 
1966 	opts->opts_size = user_opts->opts_size;
1967 
1968 	/* We should not remove this statement, but need to update the assert statement
1969 	 * if we add a new field, and also add a corresponding SET_FIELD statement.
1970 	 */
1971 	SPDK_STATIC_ASSERT(sizeof(struct spdk_nvmf_ns_opts) == 72, "Incorrect size");
1972 
1973 #undef FIELD_OK
1974 #undef SET_FIELD
1975 }
1976 
1977 /* Dummy bdev module used to to claim bdevs. */
1978 static struct spdk_bdev_module ns_bdev_module = {
1979 	.name	= "NVMe-oF Target",
1980 };
1981 
1982 static int nvmf_ns_reservation_update(const struct spdk_nvmf_ns *ns,
1983 				      const struct spdk_nvmf_reservation_info *info);
1984 static int nvmf_ns_reservation_load(const struct spdk_nvmf_ns *ns,
1985 				    struct spdk_nvmf_reservation_info *info);
1986 static int nvmf_ns_reservation_restore(struct spdk_nvmf_ns *ns,
1987 				       struct spdk_nvmf_reservation_info *info);
1988 
1989 bool
1990 nvmf_subsystem_zone_append_supported(struct spdk_nvmf_subsystem *subsystem)
1991 {
1992 	struct spdk_nvmf_ns *ns;
1993 
1994 	for (ns = spdk_nvmf_subsystem_get_first_ns(subsystem);
1995 	     ns != NULL;
1996 	     ns = spdk_nvmf_subsystem_get_next_ns(subsystem, ns)) {
1997 		if (spdk_bdev_is_zoned(ns->bdev) &&
1998 		    spdk_bdev_io_type_supported(ns->bdev, SPDK_BDEV_IO_TYPE_ZONE_APPEND)) {
1999 			return true;
2000 		}
2001 	}
2002 
2003 	return false;
2004 }
2005 
2006 uint32_t
2007 spdk_nvmf_subsystem_add_ns_ext(struct spdk_nvmf_subsystem *subsystem, const char *bdev_name,
2008 			       const struct spdk_nvmf_ns_opts *user_opts, size_t opts_size,
2009 			       const char *ptpl_file)
2010 {
2011 	struct spdk_nvmf_transport *transport;
2012 	struct spdk_nvmf_ns_opts opts;
2013 	struct spdk_nvmf_ns *ns, *first_ns;
2014 	struct spdk_nvmf_ctrlr *ctrlr;
2015 	struct spdk_nvmf_reservation_info info = {0};
2016 	int rc;
2017 	bool zone_append_supported;
2018 	uint64_t max_zone_append_size_kib;
2019 
2020 	if (!(subsystem->state == SPDK_NVMF_SUBSYSTEM_INACTIVE ||
2021 	      subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSED)) {
2022 		return 0;
2023 	}
2024 
2025 	spdk_nvmf_ns_opts_get_defaults(&opts, sizeof(opts));
2026 	if (user_opts) {
2027 		nvmf_ns_opts_copy(&opts, user_opts, opts_size);
2028 	}
2029 
2030 	if (opts.nsid == SPDK_NVME_GLOBAL_NS_TAG) {
2031 		SPDK_ERRLOG("Invalid NSID %" PRIu32 "\n", opts.nsid);
2032 		return 0;
2033 	}
2034 
2035 	if (opts.nsid == 0) {
2036 		/*
2037 		 * NSID not specified - find a free index.
2038 		 *
2039 		 * If no free slots are found, return error.
2040 		 */
2041 		for (opts.nsid = 1; opts.nsid <= subsystem->max_nsid; opts.nsid++) {
2042 			if (_nvmf_subsystem_get_ns(subsystem, opts.nsid) == NULL) {
2043 				break;
2044 			}
2045 		}
2046 		if (opts.nsid > subsystem->max_nsid) {
2047 			SPDK_ERRLOG("No free namespace slot available in the subsystem\n");
2048 			return 0;
2049 		}
2050 	}
2051 
2052 	if (opts.nsid > subsystem->max_nsid) {
2053 		SPDK_ERRLOG("NSID greater than maximum not allowed\n");
2054 		return 0;
2055 	}
2056 
2057 	if (_nvmf_subsystem_get_ns(subsystem, opts.nsid)) {
2058 		SPDK_ERRLOG("Requested NSID %" PRIu32 " already in use\n", opts.nsid);
2059 		return 0;
2060 	}
2061 
2062 	if (opts.anagrpid == 0) {
2063 		opts.anagrpid = opts.nsid;
2064 	}
2065 
2066 	if (opts.anagrpid > subsystem->max_nsid) {
2067 		SPDK_ERRLOG("ANAGRPID greater than maximum NSID not allowed\n");
2068 		return 0;
2069 	}
2070 
2071 	ns = calloc(1, sizeof(*ns));
2072 	if (ns == NULL) {
2073 		SPDK_ERRLOG("Namespace allocation failed\n");
2074 		return 0;
2075 	}
2076 
2077 	TAILQ_INIT(&ns->hosts);
2078 	ns->always_visible = !opts.no_auto_visible;
2079 	if (ns->always_visible) {
2080 		TAILQ_FOREACH(ctrlr, &subsystem->ctrlrs, link) {
2081 			spdk_bit_array_set(ctrlr->visible_ns, opts.nsid - 1);
2082 		}
2083 	}
2084 
2085 	rc = spdk_bdev_open_ext(bdev_name, true, nvmf_ns_event, ns, &ns->desc);
2086 	if (rc != 0) {
2087 		SPDK_ERRLOG("Subsystem %s: bdev %s cannot be opened, error=%d\n",
2088 			    subsystem->subnqn, bdev_name, rc);
2089 		free(ns);
2090 		return 0;
2091 	}
2092 
2093 	ns->bdev = spdk_bdev_desc_get_bdev(ns->desc);
2094 
2095 	if (spdk_bdev_get_md_size(ns->bdev) != 0) {
2096 		if (!spdk_bdev_is_md_interleaved(ns->bdev)) {
2097 			SPDK_ERRLOG("Can't attach bdev with separate metadata.\n");
2098 			spdk_bdev_close(ns->desc);
2099 			free(ns);
2100 			return 0;
2101 		}
2102 
2103 		if (spdk_bdev_get_md_size(ns->bdev) > SPDK_BDEV_MAX_INTERLEAVED_MD_SIZE) {
2104 			SPDK_ERRLOG("Maximum supported interleaved md size %u, current md size %u\n",
2105 				    SPDK_BDEV_MAX_INTERLEAVED_MD_SIZE, spdk_bdev_get_md_size(ns->bdev));
2106 			spdk_bdev_close(ns->desc);
2107 			free(ns);
2108 			return 0;
2109 		}
2110 	}
2111 
2112 	rc = spdk_bdev_module_claim_bdev(ns->bdev, ns->desc, &ns_bdev_module);
2113 	if (rc != 0) {
2114 		spdk_bdev_close(ns->desc);
2115 		free(ns);
2116 		return 0;
2117 	}
2118 
2119 	/* Cache the zcopy capability of the bdev device */
2120 	ns->zcopy = spdk_bdev_io_type_supported(ns->bdev, SPDK_BDEV_IO_TYPE_ZCOPY);
2121 
2122 	if (spdk_uuid_is_null(&opts.uuid)) {
2123 		opts.uuid = *spdk_bdev_get_uuid(ns->bdev);
2124 	}
2125 
2126 	/* if nguid descriptor is supported by bdev module (nvme) then uuid = nguid */
2127 	if (spdk_mem_all_zero(opts.nguid, sizeof(opts.nguid))) {
2128 		SPDK_STATIC_ASSERT(sizeof(opts.nguid) == sizeof(opts.uuid), "size mismatch");
2129 		memcpy(opts.nguid, spdk_bdev_get_uuid(ns->bdev), sizeof(opts.nguid));
2130 	}
2131 
2132 	if (spdk_bdev_is_zoned(ns->bdev)) {
2133 		SPDK_DEBUGLOG(nvmf, "The added namespace is backed by a zoned block device.\n");
2134 		ns->csi = SPDK_NVME_CSI_ZNS;
2135 
2136 		zone_append_supported = spdk_bdev_io_type_supported(ns->bdev,
2137 					SPDK_BDEV_IO_TYPE_ZONE_APPEND);
2138 		max_zone_append_size_kib = spdk_bdev_get_max_zone_append_size(
2139 						   ns->bdev) * spdk_bdev_get_block_size(ns->bdev);
2140 
2141 		if (_nvmf_subsystem_get_first_zoned_ns(subsystem) != NULL &&
2142 		    (nvmf_subsystem_zone_append_supported(subsystem) != zone_append_supported ||
2143 		     subsystem->max_zone_append_size_kib != max_zone_append_size_kib)) {
2144 			SPDK_ERRLOG("Namespaces with different zone append support or different zone append size are not allowed.\n");
2145 			goto err;
2146 		}
2147 
2148 		subsystem->max_zone_append_size_kib = max_zone_append_size_kib;
2149 	}
2150 
2151 	first_ns = spdk_nvmf_subsystem_get_first_ns(subsystem);
2152 	if (!first_ns) {
2153 		if (spdk_bdev_get_nvme_ctratt(ns->bdev).bits.fdps) {
2154 			SPDK_DEBUGLOG(nvmf, "Subsystem with id: %u has FDP capability.\n",
2155 				      subsystem->id);
2156 			subsystem->fdp_supported = true;
2157 		}
2158 	} else {
2159 		if (spdk_bdev_get_nvme_ctratt(first_ns->bdev).bits.fdps !=
2160 		    spdk_bdev_get_nvme_ctratt(ns->bdev).bits.fdps) {
2161 			SPDK_ERRLOG("Subsystem with id: %u can%s FDP namespace.\n", subsystem->id,
2162 				    spdk_bdev_get_nvme_ctratt(first_ns->bdev).bits.fdps ? " only add" : "not add");
2163 			goto err;
2164 		}
2165 	}
2166 
2167 	ns->opts = opts;
2168 	ns->subsystem = subsystem;
2169 	subsystem->ns[opts.nsid - 1] = ns;
2170 	ns->nsid = opts.nsid;
2171 	ns->anagrpid = opts.anagrpid;
2172 	subsystem->ana_group[ns->anagrpid - 1]++;
2173 	TAILQ_INIT(&ns->registrants);
2174 	if (ptpl_file) {
2175 		ns->ptpl_file = strdup(ptpl_file);
2176 		if (!ns->ptpl_file) {
2177 			SPDK_ERRLOG("Namespace ns->ptpl_file allocation failed\n");
2178 			goto err;
2179 		}
2180 	}
2181 
2182 	if (nvmf_ns_is_ptpl_capable(ns)) {
2183 		rc = nvmf_ns_reservation_load(ns, &info);
2184 		if (rc) {
2185 			SPDK_ERRLOG("Subsystem load reservation failed\n");
2186 			goto err;
2187 		}
2188 
2189 		rc = nvmf_ns_reservation_restore(ns, &info);
2190 		if (rc) {
2191 			SPDK_ERRLOG("Subsystem restore reservation failed\n");
2192 			goto err;
2193 		}
2194 	}
2195 
2196 	for (transport = spdk_nvmf_transport_get_first(subsystem->tgt); transport;
2197 	     transport = spdk_nvmf_transport_get_next(transport)) {
2198 		if (transport->ops->subsystem_add_ns) {
2199 			rc = transport->ops->subsystem_add_ns(transport, subsystem, ns);
2200 			if (rc) {
2201 				SPDK_ERRLOG("Namespace attachment is not allowed by %s transport\n", transport->ops->name);
2202 				nvmf_ns_reservation_clear_all_registrants(ns);
2203 				goto err;
2204 			}
2205 		}
2206 	}
2207 
2208 	/* JSON value obj is freed before sending the response. Set NULL to prevent usage of dangling pointer. */
2209 	ns->opts.transport_specific = NULL;
2210 
2211 	SPDK_DEBUGLOG(nvmf, "Subsystem %s: bdev %s assigned nsid %" PRIu32 "\n",
2212 		      spdk_nvmf_subsystem_get_nqn(subsystem),
2213 		      bdev_name,
2214 		      opts.nsid);
2215 
2216 	nvmf_subsystem_ns_changed(subsystem, opts.nsid);
2217 
2218 	SPDK_DTRACE_PROBE2(nvmf_subsystem_add_ns, subsystem->subnqn, ns->nsid);
2219 
2220 	return opts.nsid;
2221 err:
2222 	subsystem->ns[opts.nsid - 1] = NULL;
2223 	spdk_bdev_module_release_bdev(ns->bdev);
2224 	spdk_bdev_close(ns->desc);
2225 	free(ns->ptpl_file);
2226 	free(ns);
2227 
2228 	return 0;
2229 }
2230 
2231 static uint32_t
2232 nvmf_subsystem_get_next_allocated_nsid(struct spdk_nvmf_subsystem *subsystem,
2233 				       uint32_t prev_nsid)
2234 {
2235 	uint32_t nsid;
2236 
2237 	if (prev_nsid >= subsystem->max_nsid) {
2238 		return 0;
2239 	}
2240 
2241 	for (nsid = prev_nsid + 1; nsid <= subsystem->max_nsid; nsid++) {
2242 		if (subsystem->ns[nsid - 1]) {
2243 			return nsid;
2244 		}
2245 	}
2246 
2247 	return 0;
2248 }
2249 
2250 struct spdk_nvmf_ns *
2251 spdk_nvmf_subsystem_get_first_ns(struct spdk_nvmf_subsystem *subsystem)
2252 {
2253 	uint32_t first_nsid;
2254 
2255 	first_nsid = nvmf_subsystem_get_next_allocated_nsid(subsystem, 0);
2256 	return _nvmf_subsystem_get_ns(subsystem, first_nsid);
2257 }
2258 
2259 struct spdk_nvmf_ns *
2260 spdk_nvmf_subsystem_get_next_ns(struct spdk_nvmf_subsystem *subsystem,
2261 				struct spdk_nvmf_ns *prev_ns)
2262 {
2263 	uint32_t next_nsid;
2264 
2265 	next_nsid = nvmf_subsystem_get_next_allocated_nsid(subsystem, prev_ns->opts.nsid);
2266 	return _nvmf_subsystem_get_ns(subsystem, next_nsid);
2267 }
2268 
2269 struct spdk_nvmf_ns *
2270 spdk_nvmf_subsystem_get_ns(struct spdk_nvmf_subsystem *subsystem, uint32_t nsid)
2271 {
2272 	return _nvmf_subsystem_get_ns(subsystem, nsid);
2273 }
2274 
2275 uint32_t
2276 spdk_nvmf_ns_get_id(const struct spdk_nvmf_ns *ns)
2277 {
2278 	return ns->opts.nsid;
2279 }
2280 
2281 struct spdk_bdev *
2282 spdk_nvmf_ns_get_bdev(struct spdk_nvmf_ns *ns)
2283 {
2284 	return ns->bdev;
2285 }
2286 
2287 void
2288 spdk_nvmf_ns_get_opts(const struct spdk_nvmf_ns *ns, struct spdk_nvmf_ns_opts *opts,
2289 		      size_t opts_size)
2290 {
2291 	memset(opts, 0, opts_size);
2292 	memcpy(opts, &ns->opts, spdk_min(sizeof(ns->opts), opts_size));
2293 }
2294 
2295 const char *
2296 spdk_nvmf_subsystem_get_sn(const struct spdk_nvmf_subsystem *subsystem)
2297 {
2298 	return subsystem->sn;
2299 }
2300 
2301 int
2302 spdk_nvmf_subsystem_set_sn(struct spdk_nvmf_subsystem *subsystem, const char *sn)
2303 {
2304 	size_t len, max_len;
2305 
2306 	max_len = sizeof(subsystem->sn) - 1;
2307 	len = strlen(sn);
2308 	if (len > max_len) {
2309 		SPDK_DEBUGLOG(nvmf, "Invalid sn \"%s\": length %zu > max %zu\n",
2310 			      sn, len, max_len);
2311 		return -1;
2312 	}
2313 
2314 	if (!nvmf_valid_ascii_string(sn, len)) {
2315 		SPDK_DEBUGLOG(nvmf, "Non-ASCII sn\n");
2316 		SPDK_LOGDUMP(nvmf, "sn", sn, len);
2317 		return -1;
2318 	}
2319 
2320 	snprintf(subsystem->sn, sizeof(subsystem->sn), "%s", sn);
2321 
2322 	return 0;
2323 }
2324 
2325 const char *
2326 spdk_nvmf_subsystem_get_mn(const struct spdk_nvmf_subsystem *subsystem)
2327 {
2328 	return subsystem->mn;
2329 }
2330 
2331 int
2332 spdk_nvmf_subsystem_set_mn(struct spdk_nvmf_subsystem *subsystem, const char *mn)
2333 {
2334 	size_t len, max_len;
2335 
2336 	if (mn == NULL) {
2337 		mn = MODEL_NUMBER_DEFAULT;
2338 	}
2339 	max_len = sizeof(subsystem->mn) - 1;
2340 	len = strlen(mn);
2341 	if (len > max_len) {
2342 		SPDK_DEBUGLOG(nvmf, "Invalid mn \"%s\": length %zu > max %zu\n",
2343 			      mn, len, max_len);
2344 		return -1;
2345 	}
2346 
2347 	if (!nvmf_valid_ascii_string(mn, len)) {
2348 		SPDK_DEBUGLOG(nvmf, "Non-ASCII mn\n");
2349 		SPDK_LOGDUMP(nvmf, "mn", mn, len);
2350 		return -1;
2351 	}
2352 
2353 	snprintf(subsystem->mn, sizeof(subsystem->mn), "%s", mn);
2354 
2355 	return 0;
2356 }
2357 
2358 const char *
2359 spdk_nvmf_subsystem_get_nqn(const struct spdk_nvmf_subsystem *subsystem)
2360 {
2361 	return subsystem->subnqn;
2362 }
2363 
2364 /* We have to use the typedef in the function declaration to appease astyle. */
2365 typedef enum spdk_nvmf_subtype spdk_nvmf_subtype_t;
2366 
2367 spdk_nvmf_subtype_t
2368 spdk_nvmf_subsystem_get_type(struct spdk_nvmf_subsystem *subsystem)
2369 {
2370 	return subsystem->subtype;
2371 }
2372 
2373 uint32_t
2374 spdk_nvmf_subsystem_get_max_nsid(struct spdk_nvmf_subsystem *subsystem)
2375 {
2376 	return subsystem->max_nsid;
2377 }
2378 
2379 int
2380 spdk_nvmf_subsystem_set_cntlid_range(struct spdk_nvmf_subsystem *subsystem,
2381 				     uint16_t min_cntlid, uint16_t max_cntlid)
2382 {
2383 	if (subsystem->state != SPDK_NVMF_SUBSYSTEM_INACTIVE) {
2384 		return -EAGAIN;
2385 	}
2386 
2387 	if (min_cntlid > max_cntlid) {
2388 		return -EINVAL;
2389 	}
2390 	/* The spec reserves cntlid values in the range FFF0h to FFFFh. */
2391 	if (min_cntlid < NVMF_MIN_CNTLID || min_cntlid > NVMF_MAX_CNTLID ||
2392 	    max_cntlid < NVMF_MIN_CNTLID || max_cntlid > NVMF_MAX_CNTLID) {
2393 		return -EINVAL;
2394 	}
2395 	subsystem->min_cntlid = min_cntlid;
2396 	subsystem->max_cntlid = max_cntlid;
2397 	if (subsystem->next_cntlid < min_cntlid || subsystem->next_cntlid > max_cntlid - 1) {
2398 		subsystem->next_cntlid = min_cntlid - 1;
2399 	}
2400 
2401 	return 0;
2402 }
2403 
2404 static uint16_t
2405 nvmf_subsystem_gen_cntlid(struct spdk_nvmf_subsystem *subsystem)
2406 {
2407 	int count;
2408 
2409 	/*
2410 	 * In the worst case, we might have to try all CNTLID values between min_cntlid and max_cntlid
2411 	 * before we find one that is unused (or find that all values are in use).
2412 	 */
2413 	for (count = 0; count < subsystem->max_cntlid - subsystem->min_cntlid + 1; count++) {
2414 		subsystem->next_cntlid++;
2415 		if (subsystem->next_cntlid > subsystem->max_cntlid) {
2416 			subsystem->next_cntlid = subsystem->min_cntlid;
2417 		}
2418 
2419 		/* Check if a controller with this cntlid currently exists. */
2420 		if (nvmf_subsystem_get_ctrlr(subsystem, subsystem->next_cntlid) == NULL) {
2421 			/* Found unused cntlid */
2422 			return subsystem->next_cntlid;
2423 		}
2424 	}
2425 
2426 	/* All valid cntlid values are in use. */
2427 	return 0xFFFF;
2428 }
2429 
2430 int
2431 nvmf_subsystem_add_ctrlr(struct spdk_nvmf_subsystem *subsystem, struct spdk_nvmf_ctrlr *ctrlr)
2432 {
2433 
2434 	if (ctrlr->dynamic_ctrlr) {
2435 		ctrlr->cntlid = nvmf_subsystem_gen_cntlid(subsystem);
2436 		if (ctrlr->cntlid == 0xFFFF) {
2437 			/* Unable to get a cntlid */
2438 			SPDK_ERRLOG("Reached max simultaneous ctrlrs\n");
2439 			return -EBUSY;
2440 		}
2441 	} else if (nvmf_subsystem_get_ctrlr(subsystem, ctrlr->cntlid) != NULL) {
2442 		SPDK_ERRLOG("Ctrlr with cntlid %u already exist\n", ctrlr->cntlid);
2443 		return -EEXIST;
2444 	}
2445 
2446 	TAILQ_INSERT_TAIL(&subsystem->ctrlrs, ctrlr, link);
2447 
2448 	SPDK_DTRACE_PROBE3(nvmf_subsystem_add_ctrlr, subsystem->subnqn, ctrlr, ctrlr->hostnqn);
2449 
2450 	return 0;
2451 }
2452 
2453 void
2454 nvmf_subsystem_remove_ctrlr(struct spdk_nvmf_subsystem *subsystem,
2455 			    struct spdk_nvmf_ctrlr *ctrlr)
2456 {
2457 	SPDK_DTRACE_PROBE3(nvmf_subsystem_remove_ctrlr, subsystem->subnqn, ctrlr, ctrlr->hostnqn);
2458 
2459 	assert(spdk_get_thread() == subsystem->thread);
2460 	assert(subsystem == ctrlr->subsys);
2461 	SPDK_DEBUGLOG(nvmf, "remove ctrlr %p id 0x%x from subsys %p %s\n", ctrlr, ctrlr->cntlid, subsystem,
2462 		      subsystem->subnqn);
2463 	TAILQ_REMOVE(&subsystem->ctrlrs, ctrlr, link);
2464 }
2465 
2466 struct spdk_nvmf_ctrlr *
2467 nvmf_subsystem_get_ctrlr(struct spdk_nvmf_subsystem *subsystem, uint16_t cntlid)
2468 {
2469 	struct spdk_nvmf_ctrlr *ctrlr;
2470 
2471 	TAILQ_FOREACH(ctrlr, &subsystem->ctrlrs, link) {
2472 		if (ctrlr->cntlid == cntlid) {
2473 			return ctrlr;
2474 		}
2475 	}
2476 
2477 	return NULL;
2478 }
2479 
2480 uint32_t
2481 spdk_nvmf_subsystem_get_max_namespaces(const struct spdk_nvmf_subsystem *subsystem)
2482 {
2483 	return subsystem->max_nsid;
2484 }
2485 
2486 uint16_t
2487 spdk_nvmf_subsystem_get_min_cntlid(const struct spdk_nvmf_subsystem *subsystem)
2488 {
2489 	return subsystem->min_cntlid;
2490 }
2491 
2492 uint16_t
2493 spdk_nvmf_subsystem_get_max_cntlid(const struct spdk_nvmf_subsystem *subsystem)
2494 {
2495 	return subsystem->max_cntlid;
2496 }
2497 
2498 struct _nvmf_ns_registrant {
2499 	uint64_t		rkey;
2500 	char			*host_uuid;
2501 };
2502 
2503 struct _nvmf_ns_registrants {
2504 	size_t				num_regs;
2505 	struct _nvmf_ns_registrant	reg[SPDK_NVMF_MAX_NUM_REGISTRANTS];
2506 };
2507 
2508 struct _nvmf_ns_reservation {
2509 	bool					ptpl_activated;
2510 	enum spdk_nvme_reservation_type		rtype;
2511 	uint64_t				crkey;
2512 	char					*bdev_uuid;
2513 	char					*holder_uuid;
2514 	struct _nvmf_ns_registrants		regs;
2515 };
2516 
2517 static const struct spdk_json_object_decoder nvmf_ns_pr_reg_decoders[] = {
2518 	{"rkey", offsetof(struct _nvmf_ns_registrant, rkey), spdk_json_decode_uint64},
2519 	{"host_uuid", offsetof(struct _nvmf_ns_registrant, host_uuid), spdk_json_decode_string},
2520 };
2521 
2522 static int
2523 nvmf_decode_ns_pr_reg(const struct spdk_json_val *val, void *out)
2524 {
2525 	struct _nvmf_ns_registrant *reg = out;
2526 
2527 	return spdk_json_decode_object(val, nvmf_ns_pr_reg_decoders,
2528 				       SPDK_COUNTOF(nvmf_ns_pr_reg_decoders), reg);
2529 }
2530 
2531 static int
2532 nvmf_decode_ns_pr_regs(const struct spdk_json_val *val, void *out)
2533 {
2534 	struct _nvmf_ns_registrants *regs = out;
2535 
2536 	return spdk_json_decode_array(val, nvmf_decode_ns_pr_reg, regs->reg,
2537 				      SPDK_NVMF_MAX_NUM_REGISTRANTS, &regs->num_regs,
2538 				      sizeof(struct _nvmf_ns_registrant));
2539 }
2540 
2541 static const struct spdk_json_object_decoder nvmf_ns_pr_decoders[] = {
2542 	{"ptpl", offsetof(struct _nvmf_ns_reservation, ptpl_activated), spdk_json_decode_bool, true},
2543 	{"rtype", offsetof(struct _nvmf_ns_reservation, rtype), spdk_json_decode_uint32, true},
2544 	{"crkey", offsetof(struct _nvmf_ns_reservation, crkey), spdk_json_decode_uint64, true},
2545 	{"bdev_uuid", offsetof(struct _nvmf_ns_reservation, bdev_uuid), spdk_json_decode_string},
2546 	{"holder_uuid", offsetof(struct _nvmf_ns_reservation, holder_uuid), spdk_json_decode_string, true},
2547 	{"registrants", offsetof(struct _nvmf_ns_reservation, regs), nvmf_decode_ns_pr_regs},
2548 };
2549 
2550 static int
2551 nvmf_ns_reservation_load_json(const struct spdk_nvmf_ns *ns,
2552 			      struct spdk_nvmf_reservation_info *info)
2553 {
2554 	size_t json_size;
2555 	ssize_t values_cnt, rc;
2556 	void *json = NULL, *end;
2557 	struct spdk_json_val *values = NULL;
2558 	struct _nvmf_ns_reservation res = {};
2559 	const char *file = ns->ptpl_file;
2560 	uint32_t i;
2561 
2562 	/* It's not an error if the file does not exist */
2563 	if (access(file, F_OK) != 0) {
2564 		SPDK_DEBUGLOG(nvmf, "File %s does not exist\n", file);
2565 		return 0;
2566 	}
2567 
2568 	/* Load all persist file contents into a local buffer */
2569 	json = spdk_posix_file_load_from_name(file, &json_size);
2570 	if (!json) {
2571 		SPDK_ERRLOG("Load persist file %s failed\n", file);
2572 		return -ENOMEM;
2573 	}
2574 
2575 	rc = spdk_json_parse(json, json_size, NULL, 0, &end, 0);
2576 	if (rc < 0) {
2577 		SPDK_NOTICELOG("Parsing JSON configuration failed (%zd)\n", rc);
2578 		goto exit;
2579 	}
2580 
2581 	values_cnt = rc;
2582 	values = calloc(values_cnt, sizeof(struct spdk_json_val));
2583 	if (values == NULL) {
2584 		goto exit;
2585 	}
2586 
2587 	rc = spdk_json_parse(json, json_size, values, values_cnt, &end, 0);
2588 	if (rc != values_cnt) {
2589 		SPDK_ERRLOG("Parsing JSON configuration failed (%zd)\n", rc);
2590 		goto exit;
2591 	}
2592 
2593 	/* Decode json */
2594 	if (spdk_json_decode_object(values, nvmf_ns_pr_decoders,
2595 				    SPDK_COUNTOF(nvmf_ns_pr_decoders),
2596 				    &res)) {
2597 		SPDK_ERRLOG("Invalid objects in the persist file %s\n", file);
2598 		rc = -EINVAL;
2599 		goto exit;
2600 	}
2601 
2602 	if (res.regs.num_regs > SPDK_NVMF_MAX_NUM_REGISTRANTS) {
2603 		SPDK_ERRLOG("Can only support up to %u registrants\n", SPDK_NVMF_MAX_NUM_REGISTRANTS);
2604 		rc = -ERANGE;
2605 		goto exit;
2606 	}
2607 
2608 	rc = 0;
2609 	info->ptpl_activated = res.ptpl_activated;
2610 	info->rtype = res.rtype;
2611 	info->crkey = res.crkey;
2612 	snprintf(info->bdev_uuid, sizeof(info->bdev_uuid), "%s", res.bdev_uuid);
2613 	snprintf(info->holder_uuid, sizeof(info->holder_uuid), "%s", res.holder_uuid);
2614 	info->num_regs = res.regs.num_regs;
2615 	for (i = 0; i < res.regs.num_regs; i++) {
2616 		info->registrants[i].rkey = res.regs.reg[i].rkey;
2617 		snprintf(info->registrants[i].host_uuid, sizeof(info->registrants[i].host_uuid), "%s",
2618 			 res.regs.reg[i].host_uuid);
2619 	}
2620 
2621 exit:
2622 	free(json);
2623 	free(values);
2624 	free(res.bdev_uuid);
2625 	free(res.holder_uuid);
2626 	for (i = 0; i < res.regs.num_regs; i++) {
2627 		free(res.regs.reg[i].host_uuid);
2628 	}
2629 
2630 	return rc;
2631 }
2632 
2633 static bool nvmf_ns_reservation_all_registrants_type(struct spdk_nvmf_ns *ns);
2634 
2635 static int
2636 nvmf_ns_reservation_restore(struct spdk_nvmf_ns *ns, struct spdk_nvmf_reservation_info *info)
2637 {
2638 	uint32_t i;
2639 	struct spdk_nvmf_registrant *reg, *holder = NULL;
2640 	struct spdk_uuid bdev_uuid, holder_uuid;
2641 	bool rkey_flag = false;
2642 
2643 	SPDK_DEBUGLOG(nvmf, "NSID %u, PTPL %u, Number of registrants %u\n",
2644 		      ns->nsid, info->ptpl_activated, info->num_regs);
2645 
2646 	/* it's not an error */
2647 	if (!info->ptpl_activated || !info->num_regs) {
2648 		return 0;
2649 	}
2650 
2651 	/* Check info->crkey exist or not in info->registrants[i].rkey */
2652 	for (i = 0; i < info->num_regs; i++) {
2653 		if (info->crkey == info->registrants[i].rkey) {
2654 			rkey_flag = true;
2655 		}
2656 	}
2657 	if (!rkey_flag && info->crkey != 0) {
2658 		return -EINVAL;
2659 	}
2660 
2661 	spdk_uuid_parse(&bdev_uuid, info->bdev_uuid);
2662 	if (spdk_uuid_compare(&bdev_uuid, spdk_bdev_get_uuid(ns->bdev))) {
2663 		SPDK_ERRLOG("Existing bdev UUID is not same with configuration file\n");
2664 		return -EINVAL;
2665 	}
2666 
2667 	ns->crkey = info->crkey;
2668 	ns->rtype = info->rtype;
2669 	ns->ptpl_activated = info->ptpl_activated;
2670 	spdk_uuid_parse(&holder_uuid, info->holder_uuid);
2671 
2672 	SPDK_DEBUGLOG(nvmf, "Bdev UUID %s\n", info->bdev_uuid);
2673 	if (info->rtype) {
2674 		SPDK_DEBUGLOG(nvmf, "Holder UUID %s, RTYPE %u, RKEY 0x%"PRIx64"\n",
2675 			      info->holder_uuid, info->rtype, info->crkey);
2676 	}
2677 
2678 	for (i = 0; i < info->num_regs; i++) {
2679 		reg = calloc(1, sizeof(*reg));
2680 		if (!reg) {
2681 			return -ENOMEM;
2682 		}
2683 		spdk_uuid_parse(&reg->hostid, info->registrants[i].host_uuid);
2684 		reg->rkey = info->registrants[i].rkey;
2685 		TAILQ_INSERT_TAIL(&ns->registrants, reg, link);
2686 		if (info->crkey != 0 && !spdk_uuid_compare(&holder_uuid, &reg->hostid)) {
2687 			holder = reg;
2688 		}
2689 		SPDK_DEBUGLOG(nvmf, "Registrant RKEY 0x%"PRIx64", Host UUID %s\n",
2690 			      info->registrants[i].rkey, info->registrants[i].host_uuid);
2691 	}
2692 
2693 	if (nvmf_ns_reservation_all_registrants_type(ns)) {
2694 		ns->holder = TAILQ_FIRST(&ns->registrants);
2695 	} else {
2696 		ns->holder = holder;
2697 	}
2698 
2699 	return 0;
2700 }
2701 
2702 static int
2703 nvmf_ns_json_write_cb(void *cb_ctx, const void *data, size_t size)
2704 {
2705 	char *file = cb_ctx;
2706 	size_t rc;
2707 	FILE *fd;
2708 
2709 	fd = fopen(file, "w");
2710 	if (!fd) {
2711 		SPDK_ERRLOG("Can't open file %s for write\n", file);
2712 		return -ENOENT;
2713 	}
2714 	rc = fwrite(data, 1, size, fd);
2715 	fclose(fd);
2716 
2717 	return rc == size ? 0 : -1;
2718 }
2719 
2720 static int
2721 nvmf_ns_reservation_update_json(const struct spdk_nvmf_ns *ns,
2722 				const struct spdk_nvmf_reservation_info *info)
2723 {
2724 	const char *file = ns->ptpl_file;
2725 	struct spdk_json_write_ctx *w;
2726 	uint32_t i;
2727 	int rc = 0;
2728 
2729 	w = spdk_json_write_begin(nvmf_ns_json_write_cb, (void *)file, 0);
2730 	if (w == NULL) {
2731 		return -ENOMEM;
2732 	}
2733 	/* clear the configuration file */
2734 	if (!info->ptpl_activated) {
2735 		goto exit;
2736 	}
2737 
2738 	spdk_json_write_object_begin(w);
2739 	spdk_json_write_named_bool(w, "ptpl", info->ptpl_activated);
2740 	spdk_json_write_named_uint32(w, "rtype", info->rtype);
2741 	spdk_json_write_named_uint64(w, "crkey", info->crkey);
2742 	spdk_json_write_named_string(w, "bdev_uuid", info->bdev_uuid);
2743 	spdk_json_write_named_string(w, "holder_uuid", info->holder_uuid);
2744 
2745 	spdk_json_write_named_array_begin(w, "registrants");
2746 	for (i = 0; i < info->num_regs; i++) {
2747 		spdk_json_write_object_begin(w);
2748 		spdk_json_write_named_uint64(w, "rkey", info->registrants[i].rkey);
2749 		spdk_json_write_named_string(w, "host_uuid", info->registrants[i].host_uuid);
2750 		spdk_json_write_object_end(w);
2751 	}
2752 	spdk_json_write_array_end(w);
2753 	spdk_json_write_object_end(w);
2754 
2755 exit:
2756 	rc = spdk_json_write_end(w);
2757 	return rc;
2758 }
2759 
2760 static int
2761 nvmf_ns_update_reservation_info(struct spdk_nvmf_ns *ns)
2762 {
2763 	struct spdk_nvmf_reservation_info info;
2764 	struct spdk_nvmf_registrant *reg, *tmp;
2765 	uint32_t i = 0;
2766 
2767 	assert(ns != NULL);
2768 
2769 	if (!ns->bdev || !nvmf_ns_is_ptpl_capable(ns)) {
2770 		return 0;
2771 	}
2772 
2773 	memset(&info, 0, sizeof(info));
2774 	spdk_uuid_fmt_lower(info.bdev_uuid, sizeof(info.bdev_uuid), spdk_bdev_get_uuid(ns->bdev));
2775 
2776 	if (ns->rtype) {
2777 		info.rtype = ns->rtype;
2778 		info.crkey = ns->crkey;
2779 		if (!nvmf_ns_reservation_all_registrants_type(ns)) {
2780 			assert(ns->holder != NULL);
2781 			spdk_uuid_fmt_lower(info.holder_uuid, sizeof(info.holder_uuid), &ns->holder->hostid);
2782 		}
2783 	}
2784 
2785 	TAILQ_FOREACH_SAFE(reg, &ns->registrants, link, tmp) {
2786 		spdk_uuid_fmt_lower(info.registrants[i].host_uuid, sizeof(info.registrants[i].host_uuid),
2787 				    &reg->hostid);
2788 		info.registrants[i++].rkey = reg->rkey;
2789 	}
2790 
2791 	info.num_regs = i;
2792 	info.ptpl_activated = ns->ptpl_activated;
2793 
2794 	return nvmf_ns_reservation_update(ns, &info);
2795 }
2796 
2797 static struct spdk_nvmf_registrant *
2798 nvmf_ns_reservation_get_registrant(struct spdk_nvmf_ns *ns,
2799 				   struct spdk_uuid *uuid)
2800 {
2801 	struct spdk_nvmf_registrant *reg, *tmp;
2802 
2803 	TAILQ_FOREACH_SAFE(reg, &ns->registrants, link, tmp) {
2804 		if (!spdk_uuid_compare(&reg->hostid, uuid)) {
2805 			return reg;
2806 		}
2807 	}
2808 
2809 	return NULL;
2810 }
2811 
2812 /* Generate reservation notice log to registered HostID controllers */
2813 static void
2814 nvmf_subsystem_gen_ctrlr_notification(struct spdk_nvmf_subsystem *subsystem,
2815 				      struct spdk_nvmf_ns *ns,
2816 				      struct spdk_uuid *hostid_list,
2817 				      uint32_t num_hostid,
2818 				      enum spdk_nvme_reservation_notification_log_page_type type)
2819 {
2820 	struct spdk_nvmf_ctrlr *ctrlr;
2821 	uint32_t i;
2822 
2823 	for (i = 0; i < num_hostid; i++) {
2824 		TAILQ_FOREACH(ctrlr, &subsystem->ctrlrs, link) {
2825 			if (!spdk_uuid_compare(&ctrlr->hostid, &hostid_list[i])) {
2826 				nvmf_ctrlr_reservation_notice_log(ctrlr, ns, type);
2827 			}
2828 		}
2829 	}
2830 }
2831 
2832 /* Get all registrants' hostid other than the controller who issued the command */
2833 static uint32_t
2834 nvmf_ns_reservation_get_all_other_hostid(struct spdk_nvmf_ns *ns,
2835 		struct spdk_uuid *hostid_list,
2836 		uint32_t max_num_hostid,
2837 		struct spdk_uuid *current_hostid)
2838 {
2839 	struct spdk_nvmf_registrant *reg, *tmp;
2840 	uint32_t num_hostid = 0;
2841 
2842 	TAILQ_FOREACH_SAFE(reg, &ns->registrants, link, tmp) {
2843 		if (spdk_uuid_compare(&reg->hostid, current_hostid)) {
2844 			if (num_hostid == max_num_hostid) {
2845 				assert(false);
2846 				return max_num_hostid;
2847 			}
2848 			hostid_list[num_hostid++] = reg->hostid;
2849 		}
2850 	}
2851 
2852 	return num_hostid;
2853 }
2854 
2855 /* Calculate the unregistered HostID list according to list
2856  * prior to execute preempt command and list after executing
2857  * preempt command.
2858  */
2859 static uint32_t
2860 nvmf_ns_reservation_get_unregistered_hostid(struct spdk_uuid *old_hostid_list,
2861 		uint32_t old_num_hostid,
2862 		struct spdk_uuid *remaining_hostid_list,
2863 		uint32_t remaining_num_hostid)
2864 {
2865 	struct spdk_uuid temp_hostid_list[SPDK_NVMF_MAX_NUM_REGISTRANTS];
2866 	uint32_t i, j, num_hostid = 0;
2867 	bool found;
2868 
2869 	if (!remaining_num_hostid) {
2870 		return old_num_hostid;
2871 	}
2872 
2873 	for (i = 0; i < old_num_hostid; i++) {
2874 		found = false;
2875 		for (j = 0; j < remaining_num_hostid; j++) {
2876 			if (!spdk_uuid_compare(&old_hostid_list[i], &remaining_hostid_list[j])) {
2877 				found = true;
2878 				break;
2879 			}
2880 		}
2881 		if (!found) {
2882 			spdk_uuid_copy(&temp_hostid_list[num_hostid++], &old_hostid_list[i]);
2883 		}
2884 	}
2885 
2886 	if (num_hostid) {
2887 		memcpy(old_hostid_list, temp_hostid_list, sizeof(struct spdk_uuid) * num_hostid);
2888 	}
2889 
2890 	return num_hostid;
2891 }
2892 
2893 /* current reservation type is all registrants or not */
2894 static bool
2895 nvmf_ns_reservation_all_registrants_type(struct spdk_nvmf_ns *ns)
2896 {
2897 	return (ns->rtype == SPDK_NVME_RESERVE_WRITE_EXCLUSIVE_ALL_REGS ||
2898 		ns->rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_ALL_REGS);
2899 }
2900 
2901 /* current registrant is reservation holder or not */
2902 static bool
2903 nvmf_ns_reservation_registrant_is_holder(struct spdk_nvmf_ns *ns,
2904 		struct spdk_nvmf_registrant *reg)
2905 {
2906 	if (!reg) {
2907 		return false;
2908 	}
2909 
2910 	if (nvmf_ns_reservation_all_registrants_type(ns)) {
2911 		return true;
2912 	}
2913 
2914 	return (ns->holder == reg);
2915 }
2916 
2917 static int
2918 nvmf_ns_reservation_add_registrant(struct spdk_nvmf_ns *ns,
2919 				   struct spdk_nvmf_ctrlr *ctrlr,
2920 				   uint64_t nrkey)
2921 {
2922 	struct spdk_nvmf_registrant *reg;
2923 
2924 	reg = calloc(1, sizeof(*reg));
2925 	if (!reg) {
2926 		return -ENOMEM;
2927 	}
2928 
2929 	reg->rkey = nrkey;
2930 	/* set hostid for the registrant */
2931 	spdk_uuid_copy(&reg->hostid, &ctrlr->hostid);
2932 	TAILQ_INSERT_TAIL(&ns->registrants, reg, link);
2933 	ns->gen++;
2934 
2935 	return 0;
2936 }
2937 
2938 static void
2939 nvmf_ns_reservation_release_reservation(struct spdk_nvmf_ns *ns)
2940 {
2941 	ns->rtype = 0;
2942 	ns->crkey = 0;
2943 	ns->holder = NULL;
2944 }
2945 
2946 /* release the reservation if the last registrant was removed */
2947 static void
2948 nvmf_ns_reservation_check_release_on_remove_registrant(struct spdk_nvmf_ns *ns,
2949 		struct spdk_nvmf_registrant *reg)
2950 {
2951 	struct spdk_nvmf_registrant *next_reg;
2952 
2953 	/* no reservation holder */
2954 	if (!ns->holder) {
2955 		assert(ns->rtype == 0);
2956 		return;
2957 	}
2958 
2959 	next_reg = TAILQ_FIRST(&ns->registrants);
2960 	if (next_reg && nvmf_ns_reservation_all_registrants_type(ns)) {
2961 		/* the next valid registrant is the new holder now */
2962 		ns->holder = next_reg;
2963 	} else if (nvmf_ns_reservation_registrant_is_holder(ns, reg)) {
2964 		/* release the reservation */
2965 		nvmf_ns_reservation_release_reservation(ns);
2966 	}
2967 }
2968 
2969 static void
2970 nvmf_ns_reservation_remove_registrant(struct spdk_nvmf_ns *ns,
2971 				      struct spdk_nvmf_registrant *reg)
2972 {
2973 	TAILQ_REMOVE(&ns->registrants, reg, link);
2974 	nvmf_ns_reservation_check_release_on_remove_registrant(ns, reg);
2975 	free(reg);
2976 	ns->gen++;
2977 	return;
2978 }
2979 
2980 static uint32_t
2981 nvmf_ns_reservation_remove_registrants_by_key(struct spdk_nvmf_ns *ns,
2982 		uint64_t rkey)
2983 {
2984 	struct spdk_nvmf_registrant *reg, *tmp;
2985 	uint32_t count = 0;
2986 
2987 	TAILQ_FOREACH_SAFE(reg, &ns->registrants, link, tmp) {
2988 		if (reg->rkey == rkey) {
2989 			nvmf_ns_reservation_remove_registrant(ns, reg);
2990 			count++;
2991 		}
2992 	}
2993 	return count;
2994 }
2995 
2996 static uint32_t
2997 nvmf_ns_reservation_remove_all_other_registrants(struct spdk_nvmf_ns *ns,
2998 		struct spdk_nvmf_registrant *reg)
2999 {
3000 	struct spdk_nvmf_registrant *reg_tmp, *reg_tmp2;
3001 	uint32_t count = 0;
3002 
3003 	TAILQ_FOREACH_SAFE(reg_tmp, &ns->registrants, link, reg_tmp2) {
3004 		if (reg_tmp != reg) {
3005 			nvmf_ns_reservation_remove_registrant(ns, reg_tmp);
3006 			count++;
3007 		}
3008 	}
3009 	return count;
3010 }
3011 
3012 static uint32_t
3013 nvmf_ns_reservation_clear_all_registrants(struct spdk_nvmf_ns *ns)
3014 {
3015 	struct spdk_nvmf_registrant *reg, *reg_tmp;
3016 	uint32_t count = 0;
3017 
3018 	TAILQ_FOREACH_SAFE(reg, &ns->registrants, link, reg_tmp) {
3019 		nvmf_ns_reservation_remove_registrant(ns, reg);
3020 		count++;
3021 	}
3022 	return count;
3023 }
3024 
3025 static void
3026 nvmf_ns_reservation_acquire_reservation(struct spdk_nvmf_ns *ns, uint64_t rkey,
3027 					enum spdk_nvme_reservation_type rtype,
3028 					struct spdk_nvmf_registrant *holder)
3029 {
3030 	ns->rtype = rtype;
3031 	ns->crkey = rkey;
3032 	assert(ns->holder == NULL);
3033 	ns->holder = holder;
3034 }
3035 
3036 static bool
3037 nvmf_ns_reservation_register(struct spdk_nvmf_ns *ns,
3038 			     struct spdk_nvmf_ctrlr *ctrlr,
3039 			     struct spdk_nvmf_request *req)
3040 {
3041 	struct spdk_nvme_reservation_register_data key = { 0 };
3042 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3043 	uint8_t rrega, iekey, cptpl, rtype;
3044 	struct spdk_nvmf_registrant *reg;
3045 	uint8_t status = SPDK_NVME_SC_SUCCESS;
3046 	bool update_sgroup = false;
3047 	struct spdk_uuid hostid_list[SPDK_NVMF_MAX_NUM_REGISTRANTS];
3048 	uint32_t num_hostid = 0;
3049 	int rc;
3050 
3051 	rrega = cmd->cdw10_bits.resv_register.rrega;
3052 	iekey = cmd->cdw10_bits.resv_register.iekey;
3053 	cptpl = cmd->cdw10_bits.resv_register.cptpl;
3054 
3055 	if (req->iovcnt > 0 && req->length >= sizeof(key)) {
3056 		struct spdk_iov_xfer ix;
3057 		spdk_iov_xfer_init(&ix, req->iov, req->iovcnt);
3058 		spdk_iov_xfer_to_buf(&ix, &key, sizeof(key));
3059 	} else {
3060 		SPDK_ERRLOG("No key provided. Failing request.\n");
3061 		status = SPDK_NVME_SC_INVALID_FIELD;
3062 		goto exit;
3063 	}
3064 
3065 	SPDK_DEBUGLOG(nvmf, "REGISTER: RREGA %u, IEKEY %u, CPTPL %u, "
3066 		      "NRKEY 0x%"PRIx64", NRKEY 0x%"PRIx64"\n",
3067 		      rrega, iekey, cptpl, key.crkey, key.nrkey);
3068 
3069 	if (cptpl == SPDK_NVME_RESERVE_PTPL_CLEAR_POWER_ON) {
3070 		/* Ture to OFF state, and need to be updated in the configuration file */
3071 		if (ns->ptpl_activated) {
3072 			ns->ptpl_activated = 0;
3073 			update_sgroup = true;
3074 		}
3075 	} else if (cptpl == SPDK_NVME_RESERVE_PTPL_PERSIST_POWER_LOSS) {
3076 		if (!nvmf_ns_is_ptpl_capable(ns)) {
3077 			status = SPDK_NVME_SC_INVALID_FIELD;
3078 			goto exit;
3079 		} else if (ns->ptpl_activated == 0) {
3080 			ns->ptpl_activated = 1;
3081 			update_sgroup = true;
3082 		}
3083 	}
3084 
3085 	/* current Host Identifier has registrant or not */
3086 	reg = nvmf_ns_reservation_get_registrant(ns, &ctrlr->hostid);
3087 
3088 	switch (rrega) {
3089 	case SPDK_NVME_RESERVE_REGISTER_KEY:
3090 		if (!reg) {
3091 			/* register new controller */
3092 			if (key.nrkey == 0) {
3093 				SPDK_ERRLOG("Can't register zeroed new key\n");
3094 				status = SPDK_NVME_SC_INVALID_FIELD;
3095 				goto exit;
3096 			}
3097 			rc = nvmf_ns_reservation_add_registrant(ns, ctrlr, key.nrkey);
3098 			if (rc < 0) {
3099 				status = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
3100 				goto exit;
3101 			}
3102 			update_sgroup = true;
3103 		} else {
3104 			/* register with same key is not an error */
3105 			if (reg->rkey != key.nrkey) {
3106 				SPDK_ERRLOG("The same host already register a "
3107 					    "key with 0x%"PRIx64"\n",
3108 					    reg->rkey);
3109 				status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3110 				goto exit;
3111 			}
3112 		}
3113 		break;
3114 	case SPDK_NVME_RESERVE_UNREGISTER_KEY:
3115 		if (!reg || (!iekey && reg->rkey != key.crkey)) {
3116 			SPDK_ERRLOG("No registrant or current key doesn't match "
3117 				    "with existing registrant key\n");
3118 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3119 			goto exit;
3120 		}
3121 
3122 		rtype = ns->rtype;
3123 		num_hostid = nvmf_ns_reservation_get_all_other_hostid(ns, hostid_list,
3124 				SPDK_NVMF_MAX_NUM_REGISTRANTS,
3125 				&ctrlr->hostid);
3126 
3127 		nvmf_ns_reservation_remove_registrant(ns, reg);
3128 
3129 		if (!ns->rtype && num_hostid && (rtype == SPDK_NVME_RESERVE_WRITE_EXCLUSIVE_REG_ONLY ||
3130 						 rtype == SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_REG_ONLY)) {
3131 			nvmf_subsystem_gen_ctrlr_notification(ns->subsystem, ns,
3132 							      hostid_list,
3133 							      num_hostid,
3134 							      SPDK_NVME_RESERVATION_RELEASED);
3135 		}
3136 		update_sgroup = true;
3137 		break;
3138 	case SPDK_NVME_RESERVE_REPLACE_KEY:
3139 		if (key.nrkey == 0) {
3140 			SPDK_ERRLOG("Can't register zeroed new key\n");
3141 			status = SPDK_NVME_SC_INVALID_FIELD;
3142 			goto exit;
3143 		}
3144 		/* Registrant exists */
3145 		if (reg) {
3146 			if (!iekey && reg->rkey != key.crkey) {
3147 				SPDK_ERRLOG("Current key doesn't match "
3148 					    "existing registrant key\n");
3149 				status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3150 				goto exit;
3151 			}
3152 			if (reg->rkey == key.nrkey) {
3153 				goto exit;
3154 			}
3155 			reg->rkey = key.nrkey;
3156 		} else if (iekey) { /* No registrant but IEKEY is set */
3157 			/* new registrant */
3158 			rc = nvmf_ns_reservation_add_registrant(ns, ctrlr, key.nrkey);
3159 			if (rc < 0) {
3160 				status = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
3161 				goto exit;
3162 			}
3163 		} else { /* No registrant */
3164 			SPDK_ERRLOG("No registrant\n");
3165 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3166 			goto exit;
3167 
3168 		}
3169 		update_sgroup = true;
3170 		break;
3171 	default:
3172 		status = SPDK_NVME_SC_INVALID_FIELD;
3173 		goto exit;
3174 	}
3175 
3176 exit:
3177 	req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3178 	req->rsp->nvme_cpl.status.sc = status;
3179 	return update_sgroup;
3180 }
3181 
3182 static bool
3183 nvmf_ns_reservation_acquire(struct spdk_nvmf_ns *ns,
3184 			    struct spdk_nvmf_ctrlr *ctrlr,
3185 			    struct spdk_nvmf_request *req)
3186 {
3187 	struct spdk_nvme_reservation_acquire_data key = { 0 };
3188 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3189 	uint8_t racqa, iekey, rtype;
3190 	struct spdk_nvmf_registrant *reg;
3191 	bool all_regs = false;
3192 	uint32_t count = 0;
3193 	bool update_sgroup = true;
3194 	struct spdk_uuid hostid_list[SPDK_NVMF_MAX_NUM_REGISTRANTS];
3195 	uint32_t num_hostid = 0;
3196 	struct spdk_uuid new_hostid_list[SPDK_NVMF_MAX_NUM_REGISTRANTS];
3197 	uint32_t new_num_hostid = 0;
3198 	bool reservation_released = false;
3199 	uint8_t status = SPDK_NVME_SC_SUCCESS;
3200 
3201 	racqa = cmd->cdw10_bits.resv_acquire.racqa;
3202 	iekey = cmd->cdw10_bits.resv_acquire.iekey;
3203 	rtype = cmd->cdw10_bits.resv_acquire.rtype;
3204 
3205 	if (req->iovcnt > 0 && req->length >= sizeof(key)) {
3206 		struct spdk_iov_xfer ix;
3207 		spdk_iov_xfer_init(&ix, req->iov, req->iovcnt);
3208 		spdk_iov_xfer_to_buf(&ix, &key, sizeof(key));
3209 	} else {
3210 		SPDK_ERRLOG("No key provided. Failing request.\n");
3211 		status = SPDK_NVME_SC_INVALID_FIELD;
3212 		goto exit;
3213 	}
3214 
3215 	SPDK_DEBUGLOG(nvmf, "ACQUIRE: RACQA %u, IEKEY %u, RTYPE %u, "
3216 		      "NRKEY 0x%"PRIx64", PRKEY 0x%"PRIx64"\n",
3217 		      racqa, iekey, rtype, key.crkey, key.prkey);
3218 
3219 	if (iekey || rtype > SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS_ALL_REGS) {
3220 		SPDK_ERRLOG("Ignore existing key field set to 1\n");
3221 		status = SPDK_NVME_SC_INVALID_FIELD;
3222 		update_sgroup = false;
3223 		goto exit;
3224 	}
3225 
3226 	reg = nvmf_ns_reservation_get_registrant(ns, &ctrlr->hostid);
3227 	/* must be registrant and CRKEY must match */
3228 	if (!reg || reg->rkey != key.crkey) {
3229 		SPDK_ERRLOG("No registrant or current key doesn't match "
3230 			    "with existing registrant key\n");
3231 		status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3232 		update_sgroup = false;
3233 		goto exit;
3234 	}
3235 
3236 	all_regs = nvmf_ns_reservation_all_registrants_type(ns);
3237 
3238 	switch (racqa) {
3239 	case SPDK_NVME_RESERVE_ACQUIRE:
3240 		/* it's not an error for the holder to acquire same reservation type again */
3241 		if (nvmf_ns_reservation_registrant_is_holder(ns, reg) && ns->rtype == rtype) {
3242 			/* do nothing */
3243 			update_sgroup = false;
3244 		} else if (ns->holder == NULL) {
3245 			/* first time to acquire the reservation */
3246 			nvmf_ns_reservation_acquire_reservation(ns, key.crkey, rtype, reg);
3247 		} else {
3248 			SPDK_ERRLOG("Invalid rtype or current registrant is not holder\n");
3249 			status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3250 			update_sgroup = false;
3251 			goto exit;
3252 		}
3253 		break;
3254 	case SPDK_NVME_RESERVE_PREEMPT:
3255 		/* no reservation holder */
3256 		if (!ns->holder) {
3257 			/* unregister with PRKEY */
3258 			nvmf_ns_reservation_remove_registrants_by_key(ns, key.prkey);
3259 			break;
3260 		}
3261 		num_hostid = nvmf_ns_reservation_get_all_other_hostid(ns, hostid_list,
3262 				SPDK_NVMF_MAX_NUM_REGISTRANTS,
3263 				&ctrlr->hostid);
3264 
3265 		/* only 1 reservation holder and reservation key is valid */
3266 		if (!all_regs) {
3267 			/* preempt itself */
3268 			if (nvmf_ns_reservation_registrant_is_holder(ns, reg) &&
3269 			    ns->crkey == key.prkey) {
3270 				ns->rtype = rtype;
3271 				reservation_released = true;
3272 				break;
3273 			}
3274 
3275 			if (ns->crkey == key.prkey) {
3276 				nvmf_ns_reservation_remove_registrant(ns, ns->holder);
3277 				nvmf_ns_reservation_acquire_reservation(ns, key.crkey, rtype, reg);
3278 				reservation_released = true;
3279 			} else if (key.prkey != 0) {
3280 				nvmf_ns_reservation_remove_registrants_by_key(ns, key.prkey);
3281 			} else {
3282 				/* PRKEY is zero */
3283 				SPDK_ERRLOG("Current PRKEY is zero\n");
3284 				status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3285 				update_sgroup = false;
3286 				goto exit;
3287 			}
3288 		} else {
3289 			/* release all other registrants except for the current one */
3290 			if (key.prkey == 0) {
3291 				nvmf_ns_reservation_remove_all_other_registrants(ns, reg);
3292 				assert(ns->holder == reg);
3293 			} else {
3294 				count = nvmf_ns_reservation_remove_registrants_by_key(ns, key.prkey);
3295 				if (count == 0) {
3296 					SPDK_ERRLOG("PRKEY doesn't match any registrant\n");
3297 					status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3298 					update_sgroup = false;
3299 					goto exit;
3300 				}
3301 			}
3302 		}
3303 		break;
3304 	default:
3305 		status = SPDK_NVME_SC_INVALID_FIELD;
3306 		update_sgroup = false;
3307 		break;
3308 	}
3309 
3310 exit:
3311 	if (update_sgroup && racqa == SPDK_NVME_RESERVE_PREEMPT) {
3312 		new_num_hostid = nvmf_ns_reservation_get_all_other_hostid(ns, new_hostid_list,
3313 				 SPDK_NVMF_MAX_NUM_REGISTRANTS,
3314 				 &ctrlr->hostid);
3315 		/* Preempt notification occurs on the unregistered controllers
3316 		 * other than the controller who issued the command.
3317 		 */
3318 		num_hostid = nvmf_ns_reservation_get_unregistered_hostid(hostid_list,
3319 				num_hostid,
3320 				new_hostid_list,
3321 				new_num_hostid);
3322 		if (num_hostid) {
3323 			nvmf_subsystem_gen_ctrlr_notification(ns->subsystem, ns,
3324 							      hostid_list,
3325 							      num_hostid,
3326 							      SPDK_NVME_REGISTRATION_PREEMPTED);
3327 
3328 		}
3329 		/* Reservation released notification occurs on the
3330 		 * controllers which are the remaining registrants other than
3331 		 * the controller who issued the command.
3332 		 */
3333 		if (reservation_released && new_num_hostid) {
3334 			nvmf_subsystem_gen_ctrlr_notification(ns->subsystem, ns,
3335 							      new_hostid_list,
3336 							      new_num_hostid,
3337 							      SPDK_NVME_RESERVATION_RELEASED);
3338 
3339 		}
3340 	}
3341 	req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3342 	req->rsp->nvme_cpl.status.sc = status;
3343 	return update_sgroup;
3344 }
3345 
3346 static bool
3347 nvmf_ns_reservation_release(struct spdk_nvmf_ns *ns,
3348 			    struct spdk_nvmf_ctrlr *ctrlr,
3349 			    struct spdk_nvmf_request *req)
3350 {
3351 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3352 	uint8_t rrela, iekey, rtype;
3353 	struct spdk_nvmf_registrant *reg;
3354 	uint64_t crkey = 0;
3355 	uint8_t status = SPDK_NVME_SC_SUCCESS;
3356 	bool update_sgroup = true;
3357 	struct spdk_uuid hostid_list[SPDK_NVMF_MAX_NUM_REGISTRANTS];
3358 	uint32_t num_hostid = 0;
3359 
3360 	rrela = cmd->cdw10_bits.resv_release.rrela;
3361 	iekey = cmd->cdw10_bits.resv_release.iekey;
3362 	rtype = cmd->cdw10_bits.resv_release.rtype;
3363 
3364 	if (req->iovcnt > 0 && req->length >= sizeof(crkey)) {
3365 		struct spdk_iov_xfer ix;
3366 		spdk_iov_xfer_init(&ix, req->iov, req->iovcnt);
3367 		spdk_iov_xfer_to_buf(&ix, &crkey, sizeof(crkey));
3368 	} else {
3369 		SPDK_ERRLOG("No key provided. Failing request.\n");
3370 		status = SPDK_NVME_SC_INVALID_FIELD;
3371 		goto exit;
3372 	}
3373 
3374 	SPDK_DEBUGLOG(nvmf, "RELEASE: RRELA %u, IEKEY %u, RTYPE %u, "
3375 		      "CRKEY 0x%"PRIx64"\n",  rrela, iekey, rtype, crkey);
3376 
3377 	if (iekey) {
3378 		SPDK_ERRLOG("Ignore existing key field set to 1\n");
3379 		status = SPDK_NVME_SC_INVALID_FIELD;
3380 		update_sgroup = false;
3381 		goto exit;
3382 	}
3383 
3384 	reg = nvmf_ns_reservation_get_registrant(ns, &ctrlr->hostid);
3385 	if (!reg || reg->rkey != crkey) {
3386 		SPDK_ERRLOG("No registrant or current key doesn't match "
3387 			    "with existing registrant key\n");
3388 		status = SPDK_NVME_SC_RESERVATION_CONFLICT;
3389 		update_sgroup = false;
3390 		goto exit;
3391 	}
3392 
3393 	num_hostid = nvmf_ns_reservation_get_all_other_hostid(ns, hostid_list,
3394 			SPDK_NVMF_MAX_NUM_REGISTRANTS,
3395 			&ctrlr->hostid);
3396 
3397 	switch (rrela) {
3398 	case SPDK_NVME_RESERVE_RELEASE:
3399 		if (!ns->holder) {
3400 			SPDK_DEBUGLOG(nvmf, "RELEASE: no holder\n");
3401 			update_sgroup = false;
3402 			goto exit;
3403 		}
3404 		if (ns->rtype != rtype) {
3405 			SPDK_ERRLOG("Type doesn't match\n");
3406 			status = SPDK_NVME_SC_INVALID_FIELD;
3407 			update_sgroup = false;
3408 			goto exit;
3409 		}
3410 		if (!nvmf_ns_reservation_registrant_is_holder(ns, reg)) {
3411 			/* not the reservation holder, this isn't an error */
3412 			update_sgroup = false;
3413 			goto exit;
3414 		}
3415 
3416 		rtype = ns->rtype;
3417 		nvmf_ns_reservation_release_reservation(ns);
3418 
3419 		if (num_hostid && rtype != SPDK_NVME_RESERVE_WRITE_EXCLUSIVE &&
3420 		    rtype != SPDK_NVME_RESERVE_EXCLUSIVE_ACCESS) {
3421 			nvmf_subsystem_gen_ctrlr_notification(ns->subsystem, ns,
3422 							      hostid_list,
3423 							      num_hostid,
3424 							      SPDK_NVME_RESERVATION_RELEASED);
3425 		}
3426 		break;
3427 	case SPDK_NVME_RESERVE_CLEAR:
3428 		nvmf_ns_reservation_clear_all_registrants(ns);
3429 		if (num_hostid) {
3430 			nvmf_subsystem_gen_ctrlr_notification(ns->subsystem, ns,
3431 							      hostid_list,
3432 							      num_hostid,
3433 							      SPDK_NVME_RESERVATION_PREEMPTED);
3434 		}
3435 		break;
3436 	default:
3437 		status = SPDK_NVME_SC_INVALID_FIELD;
3438 		update_sgroup = false;
3439 		goto exit;
3440 	}
3441 
3442 exit:
3443 	req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3444 	req->rsp->nvme_cpl.status.sc = status;
3445 	return update_sgroup;
3446 }
3447 
3448 static void
3449 nvmf_ns_reservation_report(struct spdk_nvmf_ns *ns,
3450 			   struct spdk_nvmf_ctrlr *ctrlr,
3451 			   struct spdk_nvmf_request *req)
3452 {
3453 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3454 	struct spdk_nvmf_registrant *reg, *tmp;
3455 	struct spdk_nvme_reservation_status_extended_data status_data = { 0 };
3456 	struct spdk_iov_xfer ix;
3457 	uint32_t transfer_len;
3458 	uint32_t regctl = 0;
3459 	uint8_t status = SPDK_NVME_SC_SUCCESS;
3460 
3461 	if (req->iovcnt == 0) {
3462 		SPDK_ERRLOG("No data transfer specified for request. "
3463 			    " Unable to transfer back response.\n");
3464 		status = SPDK_NVME_SC_INVALID_FIELD;
3465 		goto exit;
3466 	}
3467 
3468 	if (!cmd->cdw11_bits.resv_report.eds) {
3469 		SPDK_ERRLOG("NVMeoF uses extended controller data structure, "
3470 			    "please set EDS bit in cdw11 and try again\n");
3471 		status = SPDK_NVME_SC_HOSTID_INCONSISTENT_FORMAT;
3472 		goto exit;
3473 	}
3474 
3475 	/* Number of Dwords of the Reservation Status data structure to transfer */
3476 	transfer_len = (cmd->cdw10 + 1) * sizeof(uint32_t);
3477 
3478 	if (transfer_len < sizeof(struct spdk_nvme_reservation_status_extended_data)) {
3479 		status = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
3480 		goto exit;
3481 	}
3482 
3483 	spdk_iov_xfer_init(&ix, req->iov, req->iovcnt);
3484 
3485 	status_data.data.gen = ns->gen;
3486 	status_data.data.rtype = ns->rtype;
3487 	status_data.data.ptpls = ns->ptpl_activated;
3488 
3489 	TAILQ_FOREACH_SAFE(reg, &ns->registrants, link, tmp) {
3490 		regctl++;
3491 	}
3492 
3493 	/*
3494 	 * We report the number of registrants as per the spec here, even if
3495 	 * the iov isn't big enough to contain them all. In that case, the
3496 	 * spdk_iov_xfer_from_buf() won't actually copy any of the remaining
3497 	 * data; as it keeps track of the iov cursor itself, it's simplest to
3498 	 * just walk the entire list anyway.
3499 	 */
3500 	status_data.data.regctl = regctl;
3501 
3502 	spdk_iov_xfer_from_buf(&ix, &status_data, sizeof(status_data));
3503 
3504 	TAILQ_FOREACH_SAFE(reg, &ns->registrants, link, tmp) {
3505 		struct spdk_nvme_registered_ctrlr_extended_data ctrlr_data = { 0 };
3506 
3507 		/* Set to 0xffffh for dynamic controller */
3508 		ctrlr_data.cntlid = 0xffff;
3509 		ctrlr_data.rcsts.status = (ns->holder == reg) ? true : false;
3510 		ctrlr_data.rkey = reg->rkey;
3511 		spdk_uuid_copy((struct spdk_uuid *)ctrlr_data.hostid, &reg->hostid);
3512 
3513 		spdk_iov_xfer_from_buf(&ix, &ctrlr_data, sizeof(ctrlr_data));
3514 	}
3515 
3516 exit:
3517 	req->rsp->nvme_cpl.status.sct = SPDK_NVME_SCT_GENERIC;
3518 	req->rsp->nvme_cpl.status.sc = status;
3519 	return;
3520 }
3521 
3522 static void
3523 nvmf_ns_reservation_complete(void *ctx)
3524 {
3525 	struct spdk_nvmf_request *req = ctx;
3526 
3527 	spdk_nvmf_request_complete(req);
3528 }
3529 
3530 static void
3531 _nvmf_ns_reservation_update_done(struct spdk_nvmf_subsystem *subsystem,
3532 				 void *cb_arg, int status)
3533 {
3534 	struct spdk_nvmf_request *req = (struct spdk_nvmf_request *)cb_arg;
3535 	struct spdk_nvmf_poll_group *group = req->qpair->group;
3536 
3537 	spdk_thread_send_msg(group->thread, nvmf_ns_reservation_complete, req);
3538 }
3539 
3540 void
3541 nvmf_ns_reservation_request(void *ctx)
3542 {
3543 	struct spdk_nvmf_request *req = (struct spdk_nvmf_request *)ctx;
3544 	struct spdk_nvme_cmd *cmd = &req->cmd->nvme_cmd;
3545 	struct spdk_nvmf_ctrlr *ctrlr = req->qpair->ctrlr;
3546 	uint32_t nsid;
3547 	struct spdk_nvmf_ns *ns;
3548 	bool update_sgroup = false;
3549 	int status = 0;
3550 
3551 	nsid = cmd->nsid;
3552 	ns = _nvmf_subsystem_get_ns(ctrlr->subsys, nsid);
3553 	assert(ns != NULL);
3554 
3555 	switch (cmd->opc) {
3556 	case SPDK_NVME_OPC_RESERVATION_REGISTER:
3557 		update_sgroup = nvmf_ns_reservation_register(ns, ctrlr, req);
3558 		break;
3559 	case SPDK_NVME_OPC_RESERVATION_ACQUIRE:
3560 		update_sgroup = nvmf_ns_reservation_acquire(ns, ctrlr, req);
3561 		break;
3562 	case SPDK_NVME_OPC_RESERVATION_RELEASE:
3563 		update_sgroup = nvmf_ns_reservation_release(ns, ctrlr, req);
3564 		break;
3565 	case SPDK_NVME_OPC_RESERVATION_REPORT:
3566 		nvmf_ns_reservation_report(ns, ctrlr, req);
3567 		break;
3568 	default:
3569 		break;
3570 	}
3571 
3572 	/* update reservation information to subsystem's poll group */
3573 	if (update_sgroup) {
3574 		if (ns->ptpl_activated || cmd->opc == SPDK_NVME_OPC_RESERVATION_REGISTER) {
3575 			if (nvmf_ns_update_reservation_info(ns) != 0) {
3576 				req->rsp->nvme_cpl.status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
3577 			}
3578 		}
3579 		status = nvmf_subsystem_update_ns(ctrlr->subsys, _nvmf_ns_reservation_update_done, req);
3580 		if (status == 0) {
3581 			return;
3582 		}
3583 	}
3584 
3585 	_nvmf_ns_reservation_update_done(ctrlr->subsys, req, status);
3586 }
3587 
3588 static bool
3589 nvmf_ns_is_ptpl_capable_json(const struct spdk_nvmf_ns *ns)
3590 {
3591 	return ns->ptpl_file != NULL;
3592 }
3593 
3594 static struct spdk_nvmf_ns_reservation_ops g_reservation_ops = {
3595 	.is_ptpl_capable = nvmf_ns_is_ptpl_capable_json,
3596 	.update = nvmf_ns_reservation_update_json,
3597 	.load = nvmf_ns_reservation_load_json,
3598 };
3599 
3600 bool
3601 nvmf_ns_is_ptpl_capable(const struct spdk_nvmf_ns *ns)
3602 {
3603 	return g_reservation_ops.is_ptpl_capable(ns);
3604 }
3605 
3606 static int
3607 nvmf_ns_reservation_update(const struct spdk_nvmf_ns *ns,
3608 			   const struct spdk_nvmf_reservation_info *info)
3609 {
3610 	return g_reservation_ops.update(ns, info);
3611 }
3612 
3613 static int
3614 nvmf_ns_reservation_load(const struct spdk_nvmf_ns *ns, struct spdk_nvmf_reservation_info *info)
3615 {
3616 	return g_reservation_ops.load(ns, info);
3617 }
3618 
3619 void
3620 spdk_nvmf_set_custom_ns_reservation_ops(const struct spdk_nvmf_ns_reservation_ops *ops)
3621 {
3622 	g_reservation_ops = *ops;
3623 }
3624 
3625 int
3626 spdk_nvmf_subsystem_set_ana_reporting(struct spdk_nvmf_subsystem *subsystem,
3627 				      bool ana_reporting)
3628 {
3629 	if (subsystem->state != SPDK_NVMF_SUBSYSTEM_INACTIVE) {
3630 		return -EAGAIN;
3631 	}
3632 
3633 	subsystem->flags.ana_reporting = ana_reporting;
3634 
3635 	return 0;
3636 }
3637 
3638 bool
3639 spdk_nvmf_subsystem_get_ana_reporting(struct spdk_nvmf_subsystem *subsystem)
3640 {
3641 	return subsystem->flags.ana_reporting;
3642 }
3643 
3644 struct subsystem_listener_update_ctx {
3645 	struct spdk_nvmf_subsystem_listener *listener;
3646 
3647 	spdk_nvmf_tgt_subsystem_listen_done_fn cb_fn;
3648 	void *cb_arg;
3649 };
3650 
3651 static void
3652 subsystem_listener_update_done(struct spdk_io_channel_iter *i, int status)
3653 {
3654 	struct subsystem_listener_update_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
3655 
3656 	if (ctx->cb_fn) {
3657 		ctx->cb_fn(ctx->cb_arg, status);
3658 	}
3659 	free(ctx);
3660 }
3661 
3662 static void
3663 subsystem_listener_update_on_pg(struct spdk_io_channel_iter *i)
3664 {
3665 	struct subsystem_listener_update_ctx *ctx = spdk_io_channel_iter_get_ctx(i);
3666 	struct spdk_nvmf_subsystem_listener *listener;
3667 	struct spdk_nvmf_poll_group *group;
3668 	struct spdk_nvmf_ctrlr *ctrlr;
3669 
3670 	listener = ctx->listener;
3671 	group = spdk_io_channel_get_ctx(spdk_io_channel_iter_get_channel(i));
3672 
3673 	TAILQ_FOREACH(ctrlr, &listener->subsystem->ctrlrs, link) {
3674 		if (ctrlr->thread != spdk_get_thread()) {
3675 			continue;
3676 		}
3677 
3678 		if (ctrlr->admin_qpair && ctrlr->admin_qpair->group == group && ctrlr->listener == listener) {
3679 			nvmf_ctrlr_async_event_ana_change_notice(ctrlr);
3680 		}
3681 	}
3682 
3683 	spdk_for_each_channel_continue(i, 0);
3684 }
3685 
3686 void
3687 spdk_nvmf_subsystem_set_ana_state(struct spdk_nvmf_subsystem *subsystem,
3688 				  const struct spdk_nvme_transport_id *trid,
3689 				  enum spdk_nvme_ana_state ana_state, uint32_t anagrpid,
3690 				  spdk_nvmf_tgt_subsystem_listen_done_fn cb_fn, void *cb_arg)
3691 {
3692 	struct spdk_nvmf_subsystem_listener *listener;
3693 	struct subsystem_listener_update_ctx *ctx;
3694 	uint32_t i;
3695 
3696 	assert(cb_fn != NULL);
3697 	assert(subsystem->state == SPDK_NVMF_SUBSYSTEM_INACTIVE ||
3698 	       subsystem->state == SPDK_NVMF_SUBSYSTEM_PAUSED);
3699 
3700 	if (!subsystem->flags.ana_reporting) {
3701 		SPDK_ERRLOG("ANA reporting is disabled\n");
3702 		cb_fn(cb_arg, -EINVAL);
3703 		return;
3704 	}
3705 
3706 	/* ANA Change state is not used, ANA Persistent Loss state
3707 	 * is not supported yet.
3708 	 */
3709 	if (!(ana_state == SPDK_NVME_ANA_OPTIMIZED_STATE ||
3710 	      ana_state == SPDK_NVME_ANA_NON_OPTIMIZED_STATE ||
3711 	      ana_state == SPDK_NVME_ANA_INACCESSIBLE_STATE)) {
3712 		SPDK_ERRLOG("ANA state %d is not supported\n", ana_state);
3713 		cb_fn(cb_arg, -ENOTSUP);
3714 		return;
3715 	}
3716 
3717 	if (anagrpid > subsystem->max_nsid) {
3718 		SPDK_ERRLOG("ANA group ID %" PRIu32 " is more than maximum\n", anagrpid);
3719 		cb_fn(cb_arg, -EINVAL);
3720 		return;
3721 	}
3722 
3723 	listener = nvmf_subsystem_find_listener(subsystem, trid);
3724 	if (!listener) {
3725 		SPDK_ERRLOG("Unable to find listener.\n");
3726 		cb_fn(cb_arg, -EINVAL);
3727 		return;
3728 	}
3729 
3730 	if (anagrpid != 0 && listener->ana_state[anagrpid - 1] == ana_state) {
3731 		cb_fn(cb_arg, 0);
3732 		return;
3733 	}
3734 
3735 	ctx = calloc(1, sizeof(*ctx));
3736 	if (!ctx) {
3737 		SPDK_ERRLOG("Unable to allocate context\n");
3738 		cb_fn(cb_arg, -ENOMEM);
3739 		return;
3740 	}
3741 
3742 	for (i = 1; i <= subsystem->max_nsid; i++) {
3743 		if (anagrpid == 0 || i == anagrpid) {
3744 			listener->ana_state[i - 1] = ana_state;
3745 		}
3746 	}
3747 	listener->ana_state_change_count++;
3748 
3749 	ctx->listener = listener;
3750 	ctx->cb_fn = cb_fn;
3751 	ctx->cb_arg = cb_arg;
3752 
3753 	spdk_for_each_channel(subsystem->tgt,
3754 			      subsystem_listener_update_on_pg,
3755 			      ctx,
3756 			      subsystem_listener_update_done);
3757 }
3758 
3759 int
3760 spdk_nvmf_subsystem_get_ana_state(struct spdk_nvmf_subsystem *subsystem,
3761 				  const struct spdk_nvme_transport_id *trid,
3762 				  uint32_t anagrpid,
3763 				  enum spdk_nvme_ana_state *ana_state)
3764 {
3765 	assert(ana_state != NULL);
3766 
3767 	struct spdk_nvmf_subsystem_listener *listener;
3768 
3769 	if (!subsystem->flags.ana_reporting) {
3770 		SPDK_ERRLOG("ANA reporting is disabled\n");
3771 		return -EINVAL;
3772 	}
3773 
3774 	if (anagrpid <= 0 || anagrpid > subsystem->max_nsid) {
3775 		SPDK_ERRLOG("ANA group ID %" PRIu32 " is invalid\n", anagrpid);
3776 		return -EINVAL;
3777 	}
3778 
3779 	listener = nvmf_subsystem_find_listener(subsystem, trid);
3780 	if (!listener) {
3781 		SPDK_ERRLOG("Unable to find listener.\n");
3782 		return -EINVAL;
3783 	}
3784 
3785 	*ana_state = listener->ana_state[anagrpid - 1];
3786 	return 0;
3787 }
3788 
3789 bool
3790 spdk_nvmf_subsystem_is_discovery(struct spdk_nvmf_subsystem *subsystem)
3791 {
3792 	return subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY_CURRENT ||
3793 	       subsystem->subtype == SPDK_NVMF_SUBTYPE_DISCOVERY;
3794 }
3795 
3796 bool
3797 nvmf_nqn_is_discovery(const char *nqn)
3798 {
3799 	return strcmp(nqn, SPDK_NVMF_DISCOVERY_NQN) == 0;
3800 }
3801