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