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