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