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