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