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