xref: /linux/drivers/nvme/target/core.c (revision deb2326729eafd10dd876c6b5c3e3443e708fa3a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Common code for the NVMe target.
4  * Copyright (c) 2015-2016 HGST, a Western Digital Company.
5  */
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 #include <linux/hex.h>
8 #include <linux/module.h>
9 #include <linux/random.h>
10 #include <linux/rculist.h>
11 #include <linux/pci-p2pdma.h>
12 #include <linux/scatterlist.h>
13 
14 #include <generated/utsrelease.h>
15 
16 #define CREATE_TRACE_POINTS
17 #include "trace.h"
18 
19 #include "nvmet.h"
20 #include "debugfs.h"
21 
22 struct kmem_cache *nvmet_bvec_cache;
23 struct workqueue_struct *buffered_io_wq;
24 struct workqueue_struct *zbd_wq;
25 static const struct nvmet_fabrics_ops *nvmet_transports[NVMF_TRTYPE_MAX];
26 static DEFINE_IDA(cntlid_ida);
27 
28 struct workqueue_struct *nvmet_wq;
29 EXPORT_SYMBOL_GPL(nvmet_wq);
30 struct workqueue_struct *nvmet_aen_wq;
31 EXPORT_SYMBOL_GPL(nvmet_aen_wq);
32 
33 /*
34  * This read/write semaphore is used to synchronize access to configuration
35  * information on a target system that will result in discovery log page
36  * information change for at least one host.
37  * The full list of resources to protected by this semaphore is:
38  *
39  *  - subsystems list
40  *  - per-subsystem allowed hosts list
41  *  - allow_any_host subsystem attribute
42  *  - nvmet_genctr
43  *  - the nvmet_transports array
44  *
45  * When updating any of those lists/structures write lock should be obtained,
46  * while when reading (populating discovery log page or checking host-subsystem
47  * link) read lock is obtained to allow concurrent reads.
48  */
49 DECLARE_RWSEM(nvmet_config_sem);
50 
51 u32 nvmet_ana_group_enabled[NVMET_MAX_ANAGRPS + 1];
52 u64 nvmet_ana_chgcnt;
53 DECLARE_RWSEM(nvmet_ana_sem);
54 
55 inline u16 errno_to_nvme_status(struct nvmet_req *req, int errno)
56 {
57 	switch (errno) {
58 	case 0:
59 		return NVME_SC_SUCCESS;
60 	case -ENOSPC:
61 		req->error_loc = offsetof(struct nvme_rw_command, length);
62 		return NVME_SC_CAP_EXCEEDED | NVME_STATUS_DNR;
63 	case -EREMOTEIO:
64 		req->error_loc = offsetof(struct nvme_rw_command, slba);
65 		return  NVME_SC_LBA_RANGE | NVME_STATUS_DNR;
66 	case -EOPNOTSUPP:
67 		req->error_loc = offsetof(struct nvme_common_command, opcode);
68 		return NVME_SC_INVALID_OPCODE | NVME_STATUS_DNR;
69 	case -ENODATA:
70 		req->error_loc = offsetof(struct nvme_rw_command, nsid);
71 		return NVME_SC_ACCESS_DENIED;
72 	case -EIO:
73 		fallthrough;
74 	default:
75 		req->error_loc = offsetof(struct nvme_common_command, opcode);
76 		return NVME_SC_INTERNAL | NVME_STATUS_DNR;
77 	}
78 }
79 
80 u16 nvmet_report_invalid_opcode(struct nvmet_req *req)
81 {
82 	pr_debug("unhandled cmd %d on qid %d\n", req->cmd->common.opcode,
83 		 req->sq->qid);
84 
85 	req->error_loc = offsetof(struct nvme_common_command, opcode);
86 	return NVME_SC_INVALID_OPCODE | NVME_STATUS_DNR;
87 }
88 
89 static struct nvmet_subsys *nvmet_find_get_subsys(struct nvmet_port *port,
90 		const char *subsysnqn);
91 
92 u16 nvmet_copy_to_sgl(struct nvmet_req *req, off_t off, const void *buf,
93 		size_t len)
94 {
95 	if (sg_pcopy_from_buffer(req->sg, req->sg_cnt, buf, len, off) != len) {
96 		req->error_loc = offsetof(struct nvme_common_command, dptr);
97 		return NVME_SC_SGL_INVALID_DATA | NVME_STATUS_DNR;
98 	}
99 	return 0;
100 }
101 
102 u16 nvmet_copy_from_sgl(struct nvmet_req *req, off_t off, void *buf, size_t len)
103 {
104 	if (sg_pcopy_to_buffer(req->sg, req->sg_cnt, buf, len, off) != len) {
105 		req->error_loc = offsetof(struct nvme_common_command, dptr);
106 		return NVME_SC_SGL_INVALID_DATA | NVME_STATUS_DNR;
107 	}
108 	return 0;
109 }
110 
111 u16 nvmet_zero_sgl(struct nvmet_req *req, off_t off, size_t len)
112 {
113 	if (sg_zero_buffer(req->sg, req->sg_cnt, len, off) != len) {
114 		req->error_loc = offsetof(struct nvme_common_command, dptr);
115 		return NVME_SC_SGL_INVALID_DATA | NVME_STATUS_DNR;
116 	}
117 	return 0;
118 }
119 
120 static u32 nvmet_max_nsid(struct nvmet_subsys *subsys)
121 {
122 	struct nvmet_ns *cur;
123 	unsigned long idx;
124 	u32 nsid = 0;
125 
126 	nvmet_for_each_enabled_ns(&subsys->namespaces, idx, cur)
127 		nsid = cur->nsid;
128 
129 	return nsid;
130 }
131 
132 static u32 nvmet_async_event_result(struct nvmet_async_event *aen)
133 {
134 	return aen->event_type | (aen->event_info << 8) | (aen->log_page << 16);
135 }
136 
137 static void nvmet_async_events_failall(struct nvmet_ctrl *ctrl)
138 {
139 	struct nvmet_req *req;
140 
141 	mutex_lock(&ctrl->lock);
142 	while (ctrl->nr_async_event_cmds) {
143 		req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds];
144 		mutex_unlock(&ctrl->lock);
145 		nvmet_req_complete(req, NVME_SC_INTERNAL | NVME_STATUS_DNR);
146 		mutex_lock(&ctrl->lock);
147 	}
148 	mutex_unlock(&ctrl->lock);
149 }
150 
151 static void nvmet_async_events_process(struct nvmet_ctrl *ctrl)
152 {
153 	struct nvmet_async_event *aen;
154 	struct nvmet_req *req;
155 
156 	mutex_lock(&ctrl->lock);
157 	while (ctrl->nr_async_event_cmds && !list_empty(&ctrl->async_events)) {
158 		aen = list_first_entry(&ctrl->async_events,
159 				       struct nvmet_async_event, entry);
160 		req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds];
161 		nvmet_set_result(req, nvmet_async_event_result(aen));
162 
163 		list_del(&aen->entry);
164 		kfree(aen);
165 
166 		mutex_unlock(&ctrl->lock);
167 		trace_nvmet_async_event(ctrl, req->cqe->result.u32);
168 		nvmet_req_complete(req, 0);
169 		mutex_lock(&ctrl->lock);
170 	}
171 	mutex_unlock(&ctrl->lock);
172 }
173 
174 static void nvmet_async_events_free(struct nvmet_ctrl *ctrl)
175 {
176 	struct nvmet_async_event *aen, *tmp;
177 
178 	mutex_lock(&ctrl->lock);
179 	list_for_each_entry_safe(aen, tmp, &ctrl->async_events, entry) {
180 		list_del(&aen->entry);
181 		kfree(aen);
182 	}
183 	mutex_unlock(&ctrl->lock);
184 }
185 
186 static void nvmet_async_event_work(struct work_struct *work)
187 {
188 	struct nvmet_ctrl *ctrl =
189 		container_of(work, struct nvmet_ctrl, async_event_work);
190 
191 	nvmet_async_events_process(ctrl);
192 }
193 
194 void nvmet_add_async_event(struct nvmet_ctrl *ctrl, u8 event_type,
195 		u8 event_info, u8 log_page)
196 {
197 	struct nvmet_async_event *aen;
198 
199 	aen = kmalloc_obj(*aen);
200 	if (!aen)
201 		return;
202 
203 	aen->event_type = event_type;
204 	aen->event_info = event_info;
205 	aen->log_page = log_page;
206 
207 	mutex_lock(&ctrl->lock);
208 	list_add_tail(&aen->entry, &ctrl->async_events);
209 	mutex_unlock(&ctrl->lock);
210 
211 	queue_work(nvmet_aen_wq, &ctrl->async_event_work);
212 }
213 
214 static void nvmet_add_to_changed_ns_log(struct nvmet_ctrl *ctrl, __le32 nsid)
215 {
216 	u32 i;
217 
218 	mutex_lock(&ctrl->lock);
219 	if (ctrl->nr_changed_ns > NVME_MAX_CHANGED_NAMESPACES)
220 		goto out_unlock;
221 
222 	for (i = 0; i < ctrl->nr_changed_ns; i++) {
223 		if (ctrl->changed_ns_list[i] == nsid)
224 			goto out_unlock;
225 	}
226 
227 	if (ctrl->nr_changed_ns == NVME_MAX_CHANGED_NAMESPACES) {
228 		ctrl->changed_ns_list[0] = cpu_to_le32(0xffffffff);
229 		ctrl->nr_changed_ns = U32_MAX;
230 		goto out_unlock;
231 	}
232 
233 	ctrl->changed_ns_list[ctrl->nr_changed_ns++] = nsid;
234 out_unlock:
235 	mutex_unlock(&ctrl->lock);
236 }
237 
238 void nvmet_ns_changed(struct nvmet_subsys *subsys, u32 nsid)
239 {
240 	struct nvmet_ctrl *ctrl;
241 
242 	lockdep_assert_held(&subsys->lock);
243 
244 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
245 		nvmet_add_to_changed_ns_log(ctrl, cpu_to_le32(nsid));
246 		if (nvmet_aen_bit_disabled(ctrl, NVME_AEN_BIT_NS_ATTR))
247 			continue;
248 		nvmet_add_async_event(ctrl, NVME_AER_NOTICE,
249 				NVME_AER_NOTICE_NS_CHANGED,
250 				NVME_LOG_CHANGED_NS);
251 	}
252 }
253 
254 void nvmet_send_ana_event(struct nvmet_subsys *subsys,
255 		struct nvmet_port *port)
256 {
257 	struct nvmet_ctrl *ctrl;
258 
259 	mutex_lock(&subsys->lock);
260 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
261 		if (port && ctrl->port != port)
262 			continue;
263 		if (nvmet_aen_bit_disabled(ctrl, NVME_AEN_BIT_ANA_CHANGE))
264 			continue;
265 		nvmet_add_async_event(ctrl, NVME_AER_NOTICE,
266 				NVME_AER_NOTICE_ANA, NVME_LOG_ANA);
267 	}
268 	mutex_unlock(&subsys->lock);
269 }
270 
271 void nvmet_port_send_ana_event(struct nvmet_port *port)
272 {
273 	struct nvmet_subsys_link *p;
274 
275 	down_read(&nvmet_config_sem);
276 	list_for_each_entry(p, &port->subsystems, entry)
277 		nvmet_send_ana_event(p->subsys, port);
278 	up_read(&nvmet_config_sem);
279 }
280 
281 int nvmet_register_transport(const struct nvmet_fabrics_ops *ops)
282 {
283 	int ret = 0;
284 
285 	down_write(&nvmet_config_sem);
286 	if (nvmet_transports[ops->type])
287 		ret = -EINVAL;
288 	else
289 		nvmet_transports[ops->type] = ops;
290 	up_write(&nvmet_config_sem);
291 
292 	return ret;
293 }
294 EXPORT_SYMBOL_GPL(nvmet_register_transport);
295 
296 void nvmet_unregister_transport(const struct nvmet_fabrics_ops *ops)
297 {
298 	down_write(&nvmet_config_sem);
299 	nvmet_transports[ops->type] = NULL;
300 	up_write(&nvmet_config_sem);
301 }
302 EXPORT_SYMBOL_GPL(nvmet_unregister_transport);
303 
304 void nvmet_port_del_ctrls(struct nvmet_port *port, struct nvmet_subsys *subsys)
305 {
306 	struct nvmet_ctrl *ctrl;
307 
308 	mutex_lock(&subsys->lock);
309 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
310 		if (ctrl->port == port)
311 			ctrl->ops->delete_ctrl(ctrl);
312 	}
313 	mutex_unlock(&subsys->lock);
314 }
315 
316 int nvmet_enable_port(struct nvmet_port *port)
317 {
318 	const struct nvmet_fabrics_ops *ops;
319 	int ret;
320 
321 	lockdep_assert_held(&nvmet_config_sem);
322 
323 	if (port->disc_addr.trtype == NVMF_TRTYPE_MAX)
324 		return -EINVAL;
325 
326 	ops = nvmet_transports[port->disc_addr.trtype];
327 	if (!ops) {
328 		up_write(&nvmet_config_sem);
329 		request_module("nvmet-transport-%d", port->disc_addr.trtype);
330 		down_write(&nvmet_config_sem);
331 		ops = nvmet_transports[port->disc_addr.trtype];
332 		if (!ops) {
333 			pr_err("transport type %d not supported\n",
334 				port->disc_addr.trtype);
335 			return -EINVAL;
336 		}
337 	}
338 
339 	if (!try_module_get(ops->owner))
340 		return -EINVAL;
341 
342 	/*
343 	 * If the user requested PI support and the transport isn't pi capable,
344 	 * don't enable the port.
345 	 */
346 	if (port->pi_enable && !(ops->flags & NVMF_METADATA_SUPPORTED)) {
347 		pr_err("T10-PI is not supported by transport type %d\n",
348 		       port->disc_addr.trtype);
349 		ret = -EINVAL;
350 		goto out_put;
351 	}
352 
353 	ret = ops->add_port(port);
354 	if (ret)
355 		goto out_put;
356 
357 	/* If the transport didn't set inline_data_size, then disable it. */
358 	if (port->inline_data_size < 0)
359 		port->inline_data_size = 0;
360 
361 	/*
362 	 * If the transport didn't set the max_queue_size properly, then clamp
363 	 * it to the target limits. Also set default values in case the
364 	 * transport didn't set it at all.
365 	 */
366 	if (port->max_queue_size < 0)
367 		port->max_queue_size = NVMET_MAX_QUEUE_SIZE;
368 	else
369 		port->max_queue_size = clamp_t(int, port->max_queue_size,
370 					       NVMET_MIN_QUEUE_SIZE,
371 					       NVMET_MAX_QUEUE_SIZE);
372 
373 	/*
374 	 * If the transport didn't set the mdts properly, then clamp it to the
375 	 * target limits. Also set default values in case the transport didn't
376 	 * set it at all.
377 	 */
378 	if (port->mdts < 0 || port->mdts > NVMET_MAX_MDTS)
379 		port->mdts = 0;
380 
381 	port->enabled = true;
382 	port->tr_ops = ops;
383 	return 0;
384 
385 out_put:
386 	module_put(ops->owner);
387 	return ret;
388 }
389 
390 void nvmet_disable_port(struct nvmet_port *port)
391 {
392 	const struct nvmet_fabrics_ops *ops;
393 
394 	lockdep_assert_held(&nvmet_config_sem);
395 
396 	if (!port->enabled)
397 		return;
398 
399 	ops = port->tr_ops;
400 	port->enabled = false;
401 	ops->remove_port(port);
402 	port->tr_ops = NULL;
403 	module_put(ops->owner);
404 }
405 
406 static void nvmet_keep_alive_timer(struct work_struct *work)
407 {
408 	struct nvmet_ctrl *ctrl = container_of(to_delayed_work(work),
409 			struct nvmet_ctrl, ka_work);
410 	bool reset_tbkas = ctrl->reset_tbkas;
411 
412 	ctrl->reset_tbkas = false;
413 	if (reset_tbkas) {
414 		pr_debug("ctrl %d reschedule traffic based keep-alive timer\n",
415 			ctrl->cntlid);
416 		queue_delayed_work(nvmet_wq, &ctrl->ka_work, ctrl->kato * HZ);
417 		return;
418 	}
419 
420 	pr_err("ctrl %d keep-alive timer (%d seconds) expired!\n",
421 		ctrl->cntlid, ctrl->kato);
422 
423 	nvmet_ctrl_fatal_error(ctrl);
424 }
425 
426 void nvmet_start_keep_alive_timer(struct nvmet_ctrl *ctrl)
427 {
428 	if (unlikely(ctrl->kato == 0))
429 		return;
430 
431 	pr_debug("ctrl %d start keep-alive timer for %d secs\n",
432 		ctrl->cntlid, ctrl->kato);
433 
434 	queue_delayed_work(nvmet_wq, &ctrl->ka_work, ctrl->kato * HZ);
435 }
436 
437 void nvmet_stop_keep_alive_timer(struct nvmet_ctrl *ctrl)
438 {
439 	if (unlikely(ctrl->kato == 0))
440 		return;
441 
442 	pr_debug("ctrl %d stop keep-alive\n", ctrl->cntlid);
443 
444 	cancel_delayed_work_sync(&ctrl->ka_work);
445 }
446 
447 u16 nvmet_req_find_ns(struct nvmet_req *req)
448 {
449 	u32 nsid = le32_to_cpu(req->cmd->common.nsid);
450 	struct nvmet_subsys *subsys = nvmet_req_subsys(req);
451 	u16 status = NVME_SC_SUCCESS;
452 
453 	rcu_read_lock();
454 	req->ns = xa_load(&subsys->namespaces, nsid);
455 	if (unlikely(!req->ns) ||
456 	    !test_bit(NVMET_NS_IO_LIVE, &req->ns->flags) ||
457 	    !percpu_ref_tryget_live_rcu(&req->ns->ref)) {
458 		req->error_loc = offsetof(struct nvme_common_command, nsid);
459 		if (!req->ns) { /* ns doesn't exist! */
460 			status = NVME_SC_INVALID_NS | NVME_STATUS_DNR;
461 			goto unlock;
462 		}
463 
464 		/* ns exists but it's disabled */
465 		req->ns = NULL;
466 		status = NVME_SC_INTERNAL_PATH_ERROR;
467 	}
468 unlock:
469 	rcu_read_unlock();
470 
471 	return status;
472 }
473 
474 static void nvmet_destroy_namespace(struct percpu_ref *ref)
475 {
476 	struct nvmet_ns *ns = container_of(ref, struct nvmet_ns, ref);
477 
478 	complete(&ns->disable_done);
479 }
480 
481 void nvmet_put_namespace(struct nvmet_ns *ns)
482 {
483 	percpu_ref_put(&ns->ref);
484 }
485 
486 static void nvmet_ns_dev_disable(struct nvmet_ns *ns)
487 {
488 	nvmet_bdev_ns_disable(ns);
489 	nvmet_file_ns_disable(ns);
490 }
491 
492 static int nvmet_p2pmem_ns_enable(struct nvmet_ns *ns)
493 {
494 	int ret;
495 	struct pci_dev *p2p_dev;
496 
497 	if (!ns->use_p2pmem)
498 		return 0;
499 
500 	if (!ns->bdev) {
501 		pr_err("peer-to-peer DMA is not supported by non-block device namespaces\n");
502 		return -EINVAL;
503 	}
504 
505 	if (!blk_queue_pci_p2pdma(ns->bdev->bd_disk->queue)) {
506 		pr_err("peer-to-peer DMA is not supported by the driver of %s\n",
507 		       ns->device_path);
508 		return -EINVAL;
509 	}
510 
511 	if (ns->p2p_dev) {
512 		ret = pci_p2pdma_distance(ns->p2p_dev, nvmet_ns_dev(ns), true);
513 		if (ret < 0)
514 			return -EINVAL;
515 	} else {
516 		/*
517 		 * Right now we just check that there is p2pmem available so
518 		 * we can report an error to the user right away if there
519 		 * is not. We'll find the actual device to use once we
520 		 * setup the controller when the port's device is available.
521 		 */
522 
523 		p2p_dev = pci_p2pmem_find(nvmet_ns_dev(ns));
524 		if (!p2p_dev) {
525 			pr_err("no peer-to-peer memory is available for %s\n",
526 			       ns->device_path);
527 			return -EINVAL;
528 		}
529 
530 		pci_dev_put(p2p_dev);
531 	}
532 
533 	return 0;
534 }
535 
536 static void nvmet_p2pmem_ns_add_p2p(struct nvmet_ctrl *ctrl,
537 				    struct nvmet_ns *ns)
538 {
539 	struct device *clients[2];
540 	struct pci_dev *p2p_dev;
541 	int ret;
542 
543 	lockdep_assert_held(&ctrl->subsys->lock);
544 
545 	if (!ctrl->p2p_client || !ns->use_p2pmem)
546 		return;
547 
548 	if (ns->p2p_dev) {
549 		ret = pci_p2pdma_distance(ns->p2p_dev, ctrl->p2p_client, true);
550 		if (ret < 0)
551 			return;
552 
553 		p2p_dev = pci_dev_get(ns->p2p_dev);
554 	} else {
555 		clients[0] = ctrl->p2p_client;
556 		clients[1] = nvmet_ns_dev(ns);
557 
558 		p2p_dev = pci_p2pmem_find_many(clients, ARRAY_SIZE(clients));
559 		if (!p2p_dev) {
560 			pr_err("no peer-to-peer memory is available that's supported by %s and %s\n",
561 			       dev_name(ctrl->p2p_client), ns->device_path);
562 			return;
563 		}
564 	}
565 
566 	ret = radix_tree_insert(&ctrl->p2p_ns_map, ns->nsid, p2p_dev);
567 	if (ret < 0)
568 		pci_dev_put(p2p_dev);
569 
570 	pr_info("using p2pmem on %s for nsid %u\n", pci_name(p2p_dev),
571 		ns->nsid);
572 }
573 
574 bool nvmet_ns_revalidate(struct nvmet_ns *ns)
575 {
576 	loff_t oldsize = ns->size;
577 
578 	if (ns->bdev)
579 		nvmet_bdev_ns_revalidate(ns);
580 	else
581 		nvmet_file_ns_revalidate(ns);
582 
583 	return oldsize != ns->size;
584 }
585 
586 int nvmet_ns_enable(struct nvmet_ns *ns)
587 {
588 	struct nvmet_subsys *subsys = ns->subsys;
589 	struct nvmet_ctrl *ctrl;
590 	int ret;
591 
592 	mutex_lock(&subsys->lock);
593 	ret = 0;
594 
595 	if (nvmet_is_passthru_subsys(subsys)) {
596 		pr_info("cannot enable both passthru and regular namespaces for a single subsystem");
597 		goto out_unlock;
598 	}
599 
600 	if (ns->enabled)
601 		goto out_unlock;
602 
603 	if (!ns->device_path) {
604 		ret = -EINVAL;
605 		goto out_unlock;
606 	}
607 
608 	ret = nvmet_bdev_ns_enable(ns);
609 	if (ret == -ENOTBLK)
610 		ret = nvmet_file_ns_enable(ns);
611 	if (ret)
612 		goto out_unlock;
613 
614 	ret = nvmet_p2pmem_ns_enable(ns);
615 	if (ret)
616 		goto out_dev_disable;
617 
618 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
619 		nvmet_p2pmem_ns_add_p2p(ctrl, ns);
620 
621 	if (ns->pr.enable) {
622 		ret = nvmet_pr_init_ns(ns);
623 		if (ret)
624 			goto out_dev_put;
625 	}
626 
627 	ret = percpu_ref_init(&ns->ref, nvmet_destroy_namespace, 0, GFP_KERNEL);
628 	if (ret)
629 		goto out_pr_exit;
630 
631 	nvmet_ns_changed(subsys, ns->nsid);
632 	ns->enabled = true;
633 	xa_set_mark(&subsys->namespaces, ns->nsid, NVMET_NS_ENABLED);
634 	nvmet_debugfs_ns_setup(ns);
635 	set_bit(NVMET_NS_IO_LIVE, &ns->flags);
636 	ret = 0;
637 out_unlock:
638 	mutex_unlock(&subsys->lock);
639 	return ret;
640 out_pr_exit:
641 	if (ns->pr.enable)
642 		nvmet_pr_exit_ns(ns);
643 out_dev_put:
644 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
645 		pci_dev_put(radix_tree_delete(&ctrl->p2p_ns_map, ns->nsid));
646 out_dev_disable:
647 	nvmet_ns_dev_disable(ns);
648 	goto out_unlock;
649 }
650 
651 void nvmet_ns_disable(struct nvmet_ns *ns)
652 {
653 	struct nvmet_subsys *subsys = ns->subsys;
654 	struct nvmet_ctrl *ctrl;
655 
656 	if (!test_and_clear_bit(NVMET_NS_IO_LIVE, &ns->flags))
657 		return;
658 
659 	mutex_lock(&subsys->lock);
660 
661 	xa_clear_mark(&subsys->namespaces, ns->nsid, NVMET_NS_ENABLED);
662 	nvmet_debugfs_ns_free(ns);
663 
664 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
665 		pci_dev_put(radix_tree_delete(&ctrl->p2p_ns_map, ns->nsid));
666 
667 	mutex_unlock(&subsys->lock);
668 
669 	/*
670 	 * Now that we removed the namespaces from the lookup list, we
671 	 * can kill the per_cpu ref and wait for any remaining references
672 	 * to be dropped, as well as a RCU grace period for anyone only
673 	 * using the namespace under rcu_read_lock().  Note that we can't
674 	 * use call_rcu here as we need to ensure the namespaces have
675 	 * been fully destroyed before unloading the module.
676 	 */
677 	percpu_ref_kill(&ns->ref);
678 	synchronize_rcu();
679 	wait_for_completion(&ns->disable_done);
680 	percpu_ref_exit(&ns->ref);
681 
682 	if (ns->pr.enable)
683 		nvmet_pr_exit_ns(ns);
684 
685 	mutex_lock(&subsys->lock);
686 	nvmet_ns_changed(subsys, ns->nsid);
687 	nvmet_ns_dev_disable(ns);
688 	ns->enabled = false;
689 	mutex_unlock(&subsys->lock);
690 }
691 
692 void nvmet_ns_free(struct nvmet_ns *ns)
693 {
694 	struct nvmet_subsys *subsys = ns->subsys;
695 
696 	nvmet_ns_disable(ns);
697 
698 	mutex_lock(&subsys->lock);
699 
700 	xa_erase(&subsys->namespaces, ns->nsid);
701 	if (ns->nsid == subsys->max_nsid)
702 		subsys->max_nsid = nvmet_max_nsid(subsys);
703 
704 	subsys->nr_namespaces--;
705 	mutex_unlock(&subsys->lock);
706 
707 	down_write(&nvmet_ana_sem);
708 	nvmet_ana_group_enabled[ns->anagrpid]--;
709 	up_write(&nvmet_ana_sem);
710 
711 	kfree(ns->device_path);
712 	kfree(ns);
713 }
714 
715 struct nvmet_ns *nvmet_ns_alloc(struct nvmet_subsys *subsys, u32 nsid)
716 {
717 	struct nvmet_ns *ns;
718 
719 	mutex_lock(&subsys->lock);
720 
721 	if (subsys->nr_namespaces == NVMET_MAX_NAMESPACES)
722 		goto out_unlock;
723 
724 	ns = kzalloc_obj(*ns);
725 	if (!ns)
726 		goto out_unlock;
727 
728 	init_completion(&ns->disable_done);
729 
730 	ns->nsid = nsid;
731 	ns->subsys = subsys;
732 
733 	if (ns->nsid > subsys->max_nsid)
734 		subsys->max_nsid = nsid;
735 
736 	if (xa_insert(&subsys->namespaces, ns->nsid, ns, GFP_KERNEL))
737 		goto out_exit;
738 
739 	subsys->nr_namespaces++;
740 
741 	mutex_unlock(&subsys->lock);
742 
743 	down_write(&nvmet_ana_sem);
744 	ns->anagrpid = NVMET_DEFAULT_ANA_GRPID;
745 	nvmet_ana_group_enabled[ns->anagrpid]++;
746 	up_write(&nvmet_ana_sem);
747 
748 	uuid_gen(&ns->uuid);
749 	ns->buffered_io = false;
750 	ns->csi = NVME_CSI_NVM;
751 
752 	return ns;
753 out_exit:
754 	subsys->max_nsid = nvmet_max_nsid(subsys);
755 	kfree(ns);
756 out_unlock:
757 	mutex_unlock(&subsys->lock);
758 	return NULL;
759 }
760 
761 static void nvmet_update_sq_head(struct nvmet_req *req)
762 {
763 	if (req->sq->size) {
764 		u32 old_sqhd, new_sqhd;
765 
766 		old_sqhd = READ_ONCE(req->sq->sqhd);
767 		do {
768 			new_sqhd = (old_sqhd + 1) % req->sq->size;
769 		} while (!try_cmpxchg(&req->sq->sqhd, &old_sqhd, new_sqhd));
770 	}
771 	req->cqe->sq_head = cpu_to_le16(req->sq->sqhd & 0x0000FFFF);
772 }
773 
774 static void nvmet_set_error(struct nvmet_req *req, u16 status)
775 {
776 	struct nvmet_ctrl *ctrl = req->sq->ctrl;
777 	struct nvme_error_slot *new_error_slot;
778 	unsigned long flags;
779 
780 	req->cqe->status = cpu_to_le16(status << 1);
781 
782 	if (!ctrl || req->error_loc == NVMET_NO_ERROR_LOC)
783 		return;
784 
785 	spin_lock_irqsave(&ctrl->error_lock, flags);
786 	ctrl->err_counter++;
787 	new_error_slot =
788 		&ctrl->slots[ctrl->err_counter % NVMET_ERROR_LOG_SLOTS];
789 
790 	new_error_slot->error_count = cpu_to_le64(ctrl->err_counter);
791 	new_error_slot->sqid = cpu_to_le16(req->sq->qid);
792 	new_error_slot->cmdid = cpu_to_le16(req->cmd->common.command_id);
793 	new_error_slot->status_field = cpu_to_le16(status << 1);
794 	new_error_slot->param_error_location = cpu_to_le16(req->error_loc);
795 	new_error_slot->lba = cpu_to_le64(req->error_slba);
796 	new_error_slot->nsid = req->cmd->common.nsid;
797 	spin_unlock_irqrestore(&ctrl->error_lock, flags);
798 
799 	/* set the more bit for this request */
800 	req->cqe->status |= cpu_to_le16(1 << 14);
801 }
802 
803 static void __nvmet_req_complete(struct nvmet_req *req, u16 status)
804 {
805 	struct nvmet_ns *ns = req->ns;
806 	struct nvmet_pr_per_ctrl_ref *pc_ref = req->pc_ref;
807 
808 	if (!req->sq->sqhd_disabled)
809 		nvmet_update_sq_head(req);
810 	req->cqe->sq_id = cpu_to_le16(req->sq->qid);
811 	req->cqe->command_id = req->cmd->common.command_id;
812 
813 	if (unlikely(status))
814 		nvmet_set_error(req, status);
815 
816 	trace_nvmet_req_complete(req);
817 
818 	req->ops->queue_response(req);
819 
820 	if (pc_ref)
821 		nvmet_pr_put_ns_pc_ref(pc_ref);
822 	if (ns)
823 		nvmet_put_namespace(ns);
824 
825 	nvmet_put_passthru_ref(req);
826 }
827 
828 void nvmet_req_complete(struct nvmet_req *req, u16 status)
829 {
830 	struct nvmet_sq *sq = req->sq;
831 
832 	__nvmet_req_complete(req, status);
833 	percpu_ref_put(&sq->ref);
834 }
835 EXPORT_SYMBOL_GPL(nvmet_req_complete);
836 
837 void nvmet_cq_init(struct nvmet_cq *cq)
838 {
839 	refcount_set(&cq->ref, 1);
840 }
841 EXPORT_SYMBOL_GPL(nvmet_cq_init);
842 
843 bool nvmet_cq_get(struct nvmet_cq *cq)
844 {
845 	return refcount_inc_not_zero(&cq->ref);
846 }
847 EXPORT_SYMBOL_GPL(nvmet_cq_get);
848 
849 void nvmet_cq_put(struct nvmet_cq *cq)
850 {
851 	if (refcount_dec_and_test(&cq->ref))
852 		nvmet_cq_destroy(cq);
853 }
854 EXPORT_SYMBOL_GPL(nvmet_cq_put);
855 
856 void nvmet_cq_setup(struct nvmet_ctrl *ctrl, struct nvmet_cq *cq,
857 		u16 qid, u16 size)
858 {
859 	cq->qid = qid;
860 	cq->size = size;
861 
862 	ctrl->cqs[qid] = cq;
863 }
864 
865 void nvmet_cq_destroy(struct nvmet_cq *cq)
866 {
867 	struct nvmet_ctrl *ctrl = cq->ctrl;
868 
869 	if (ctrl) {
870 		ctrl->cqs[cq->qid] = NULL;
871 		nvmet_ctrl_put(cq->ctrl);
872 		cq->ctrl = NULL;
873 	}
874 }
875 
876 void nvmet_sq_setup(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq,
877 		u16 qid, u16 size)
878 {
879 	sq->sqhd = 0;
880 	sq->qid = qid;
881 	sq->size = size;
882 
883 	ctrl->sqs[qid] = sq;
884 }
885 
886 static void nvmet_confirm_sq(struct percpu_ref *ref)
887 {
888 	struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref);
889 
890 	complete(&sq->confirm_done);
891 }
892 
893 u16 nvmet_check_cqid(struct nvmet_ctrl *ctrl, u16 cqid, bool create)
894 {
895 	if (!ctrl->cqs)
896 		return NVME_SC_INTERNAL | NVME_STATUS_DNR;
897 
898 	if (cqid > ctrl->max_qid)
899 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
900 
901 	if ((create && ctrl->cqs[cqid]) || (!create && !ctrl->cqs[cqid]))
902 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
903 
904 	return NVME_SC_SUCCESS;
905 }
906 
907 u16 nvmet_check_io_cqid(struct nvmet_ctrl *ctrl, u16 cqid, bool create)
908 {
909 	if (!cqid)
910 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
911 	return nvmet_check_cqid(ctrl, cqid, create);
912 }
913 
914 bool nvmet_cq_in_use(struct nvmet_cq *cq)
915 {
916 	return refcount_read(&cq->ref) > 1;
917 }
918 EXPORT_SYMBOL_GPL(nvmet_cq_in_use);
919 
920 u16 nvmet_cq_create(struct nvmet_ctrl *ctrl, struct nvmet_cq *cq,
921 		    u16 qid, u16 size)
922 {
923 	u16 status;
924 
925 	status = nvmet_check_cqid(ctrl, qid, true);
926 	if (status != NVME_SC_SUCCESS)
927 		return status;
928 
929 	if (!kref_get_unless_zero(&ctrl->ref))
930 		return NVME_SC_INTERNAL | NVME_STATUS_DNR;
931 	cq->ctrl = ctrl;
932 
933 	nvmet_cq_init(cq);
934 	nvmet_cq_setup(ctrl, cq, qid, size);
935 
936 	return NVME_SC_SUCCESS;
937 }
938 EXPORT_SYMBOL_GPL(nvmet_cq_create);
939 
940 u16 nvmet_check_sqid(struct nvmet_ctrl *ctrl, u16 sqid,
941 		     bool create)
942 {
943 	if (!ctrl->sqs)
944 		return NVME_SC_INTERNAL | NVME_STATUS_DNR;
945 
946 	if (sqid > ctrl->max_qid)
947 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
948 
949 	if ((create && ctrl->sqs[sqid]) ||
950 	    (!create && !ctrl->sqs[sqid]))
951 		return NVME_SC_QID_INVALID | NVME_STATUS_DNR;
952 
953 	return NVME_SC_SUCCESS;
954 }
955 
956 u16 nvmet_sq_create(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq,
957 		    struct nvmet_cq *cq, u16 sqid, u16 size)
958 {
959 	u16 status;
960 	int ret;
961 
962 	if (!kref_get_unless_zero(&ctrl->ref))
963 		return NVME_SC_INTERNAL | NVME_STATUS_DNR;
964 
965 	status = nvmet_check_sqid(ctrl, sqid, true);
966 	if (status != NVME_SC_SUCCESS)
967 		goto ctrl_put;
968 
969 	ret = nvmet_sq_init(sq, cq);
970 	if (ret) {
971 		status = NVME_SC_INTERNAL | NVME_STATUS_DNR;
972 		goto ctrl_put;
973 	}
974 
975 	nvmet_sq_setup(ctrl, sq, sqid, size);
976 	sq->ctrl = ctrl;
977 
978 	return NVME_SC_SUCCESS;
979 
980 ctrl_put:
981 	nvmet_ctrl_put(ctrl);
982 	return status;
983 }
984 EXPORT_SYMBOL_GPL(nvmet_sq_create);
985 
986 void nvmet_sq_destroy(struct nvmet_sq *sq)
987 {
988 	struct nvmet_ctrl *ctrl = sq->ctrl;
989 
990 	/*
991 	 * If this is the admin queue, complete all AERs so that our
992 	 * queue doesn't have outstanding requests on it.
993 	 */
994 	if (ctrl && ctrl->sqs && ctrl->sqs[0] == sq)
995 		nvmet_async_events_failall(ctrl);
996 	percpu_ref_kill_and_confirm(&sq->ref, nvmet_confirm_sq);
997 	wait_for_completion(&sq->confirm_done);
998 	wait_for_completion(&sq->free_done);
999 	percpu_ref_exit(&sq->ref);
1000 	nvmet_auth_sq_destroy(sq);
1001 	nvmet_cq_put(sq->cq);
1002 
1003 	/*
1004 	 * we must reference the ctrl again after waiting for inflight IO
1005 	 * to complete. Because admin connect may have sneaked in after we
1006 	 * store sq->ctrl locally, but before we killed the percpu_ref. the
1007 	 * admin connect allocates and assigns sq->ctrl, which now needs a
1008 	 * final ref put, as this ctrl is going away.
1009 	 */
1010 	ctrl = sq->ctrl;
1011 
1012 	if (ctrl) {
1013 		/*
1014 		 * The teardown flow may take some time, and the host may not
1015 		 * send us keep-alive during this period, hence reset the
1016 		 * traffic based keep-alive timer so we don't trigger a
1017 		 * controller teardown as a result of a keep-alive expiration.
1018 		 */
1019 		ctrl->reset_tbkas = true;
1020 		sq->ctrl->sqs[sq->qid] = NULL;
1021 		nvmet_ctrl_put(ctrl);
1022 		sq->ctrl = NULL; /* allows reusing the queue later */
1023 	}
1024 }
1025 EXPORT_SYMBOL_GPL(nvmet_sq_destroy);
1026 
1027 static void nvmet_sq_free(struct percpu_ref *ref)
1028 {
1029 	struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref);
1030 
1031 	complete(&sq->free_done);
1032 }
1033 
1034 int nvmet_sq_init(struct nvmet_sq *sq, struct nvmet_cq *cq)
1035 {
1036 	int ret;
1037 
1038 	if (!nvmet_cq_get(cq))
1039 		return -EINVAL;
1040 
1041 	ret = percpu_ref_init(&sq->ref, nvmet_sq_free, 0, GFP_KERNEL);
1042 	if (ret) {
1043 		pr_err("percpu_ref init failed!\n");
1044 		nvmet_cq_put(cq);
1045 		return ret;
1046 	}
1047 	init_completion(&sq->free_done);
1048 	init_completion(&sq->confirm_done);
1049 	nvmet_auth_sq_init(sq);
1050 	sq->cq = cq;
1051 
1052 	return 0;
1053 }
1054 EXPORT_SYMBOL_GPL(nvmet_sq_init);
1055 
1056 static inline u16 nvmet_check_ana_state(struct nvmet_port *port,
1057 		struct nvmet_ns *ns)
1058 {
1059 	enum nvme_ana_state state = port->ana_state[ns->anagrpid];
1060 
1061 	if (unlikely(state == NVME_ANA_INACCESSIBLE))
1062 		return NVME_SC_ANA_INACCESSIBLE;
1063 	if (unlikely(state == NVME_ANA_PERSISTENT_LOSS))
1064 		return NVME_SC_ANA_PERSISTENT_LOSS;
1065 	if (unlikely(state == NVME_ANA_CHANGE))
1066 		return NVME_SC_ANA_TRANSITION;
1067 	return 0;
1068 }
1069 
1070 static inline u16 nvmet_io_cmd_check_access(struct nvmet_req *req)
1071 {
1072 	if (unlikely(req->ns->readonly)) {
1073 		switch (req->cmd->common.opcode) {
1074 		case nvme_cmd_read:
1075 		case nvme_cmd_flush:
1076 			break;
1077 		default:
1078 			return NVME_SC_NS_WRITE_PROTECTED;
1079 		}
1080 	}
1081 
1082 	return 0;
1083 }
1084 
1085 static u32 nvmet_io_cmd_transfer_len(struct nvmet_req *req)
1086 {
1087 	struct nvme_command *cmd = req->cmd;
1088 	u32 metadata_len = 0;
1089 
1090 	if (nvme_is_fabrics(cmd))
1091 		return nvmet_fabrics_io_cmd_data_len(req);
1092 
1093 	if (!req->ns)
1094 		return 0;
1095 
1096 	switch (req->cmd->common.opcode) {
1097 	case nvme_cmd_read:
1098 	case nvme_cmd_write:
1099 	case nvme_cmd_zone_append:
1100 		if (req->sq->ctrl->pi_support && nvmet_ns_has_pi(req->ns))
1101 			metadata_len = nvmet_rw_metadata_len(req);
1102 		return nvmet_rw_data_len(req) + metadata_len;
1103 	case nvme_cmd_dsm:
1104 		return nvmet_dsm_len(req);
1105 	case nvme_cmd_zone_mgmt_recv:
1106 		/* The handler rejects a NUMD whose byte count would wrap. */
1107 		if (le32_to_cpu(req->cmd->zmr.numd) >= U32_MAX / 4)
1108 			return 0;
1109 		return (le32_to_cpu(req->cmd->zmr.numd) + 1) << 2;
1110 	default:
1111 		return 0;
1112 	}
1113 }
1114 
1115 static u16 nvmet_parse_io_cmd(struct nvmet_req *req)
1116 {
1117 	struct nvme_command *cmd = req->cmd;
1118 	u16 ret;
1119 
1120 	if (nvme_is_fabrics(cmd))
1121 		return nvmet_parse_fabrics_io_cmd(req);
1122 
1123 	if (unlikely(!nvmet_check_auth_status(req)))
1124 		return NVME_SC_AUTH_REQUIRED | NVME_STATUS_DNR;
1125 
1126 	ret = nvmet_check_ctrl_status(req);
1127 	if (unlikely(ret))
1128 		return ret;
1129 
1130 	if (nvmet_is_passthru_req(req))
1131 		return nvmet_parse_passthru_io_cmd(req);
1132 
1133 	ret = nvmet_req_find_ns(req);
1134 	if (unlikely(ret))
1135 		return ret;
1136 
1137 	ret = nvmet_check_ana_state(req->port, req->ns);
1138 	if (unlikely(ret)) {
1139 		req->error_loc = offsetof(struct nvme_common_command, nsid);
1140 		return ret;
1141 	}
1142 	ret = nvmet_io_cmd_check_access(req);
1143 	if (unlikely(ret)) {
1144 		req->error_loc = offsetof(struct nvme_common_command, nsid);
1145 		return ret;
1146 	}
1147 
1148 	if (req->ns->pr.enable) {
1149 		ret = nvmet_parse_pr_cmd(req);
1150 		if (!ret)
1151 			return ret;
1152 	}
1153 
1154 	switch (req->ns->csi) {
1155 	case NVME_CSI_NVM:
1156 		if (req->ns->file)
1157 			ret = nvmet_file_parse_io_cmd(req);
1158 		else
1159 			ret = nvmet_bdev_parse_io_cmd(req);
1160 		break;
1161 	case NVME_CSI_ZNS:
1162 		if (IS_ENABLED(CONFIG_BLK_DEV_ZONED))
1163 			ret = nvmet_bdev_zns_parse_io_cmd(req);
1164 		else
1165 			ret = NVME_SC_INVALID_IO_CMD_SET;
1166 		break;
1167 	default:
1168 		ret = NVME_SC_INVALID_IO_CMD_SET;
1169 	}
1170 	if (ret)
1171 		return ret;
1172 
1173 	if (req->ns->pr.enable) {
1174 		ret = nvmet_pr_check_cmd_access(req);
1175 		if (ret)
1176 			return ret;
1177 
1178 		ret = nvmet_pr_get_ns_pc_ref(req);
1179 	}
1180 	return ret;
1181 }
1182 
1183 bool nvmet_req_init(struct nvmet_req *req, struct nvmet_sq *sq,
1184 		const struct nvmet_fabrics_ops *ops)
1185 {
1186 	u8 flags = req->cmd->common.flags;
1187 	u16 status;
1188 
1189 	req->cq = sq->cq;
1190 	req->sq = sq;
1191 	req->ops = ops;
1192 	req->sg = NULL;
1193 	req->metadata_sg = NULL;
1194 	req->sg_cnt = 0;
1195 	req->metadata_sg_cnt = 0;
1196 	req->transfer_len = 0;
1197 	req->metadata_len = 0;
1198 	req->cqe->result.u64 = 0;
1199 	req->cqe->status = 0;
1200 	req->cqe->sq_head = 0;
1201 	req->ns = NULL;
1202 	req->error_loc = NVMET_NO_ERROR_LOC;
1203 	req->error_slba = 0;
1204 	req->pc_ref = NULL;
1205 	req->p.ref_held = false;
1206 
1207 	/* no support for fused commands yet */
1208 	if (unlikely(flags & (NVME_CMD_FUSE_FIRST | NVME_CMD_FUSE_SECOND))) {
1209 		req->error_loc = offsetof(struct nvme_common_command, flags);
1210 		status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1211 		goto fail;
1212 	}
1213 
1214 	/*
1215 	 * For fabrics, PSDT field shall describe metadata pointer (MPTR) that
1216 	 * contains an address of a single contiguous physical buffer that is
1217 	 * byte aligned. For PCI controllers, this is optional so not enforced.
1218 	 */
1219 	if (unlikely((flags & NVME_CMD_SGL_ALL) != NVME_CMD_SGL_METABUF)) {
1220 		if (!req->sq->ctrl || !nvmet_is_pci_ctrl(req->sq->ctrl)) {
1221 			req->error_loc =
1222 				offsetof(struct nvme_common_command, flags);
1223 			status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1224 			goto fail;
1225 		}
1226 	}
1227 
1228 	if (unlikely(!req->sq->ctrl))
1229 		/* will return an error for any non-connect command: */
1230 		status = nvmet_parse_connect_cmd(req);
1231 	else if (likely(req->sq->qid != 0))
1232 		status = nvmet_parse_io_cmd(req);
1233 	else
1234 		status = nvmet_parse_admin_cmd(req);
1235 
1236 	if (status)
1237 		goto fail;
1238 
1239 	trace_nvmet_req_init(req, req->cmd);
1240 
1241 	if (unlikely(!percpu_ref_tryget_live(&sq->ref))) {
1242 		status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
1243 		goto fail;
1244 	}
1245 
1246 	if (sq->ctrl && sq->ctrl->tbkas)
1247 		sq->ctrl->reset_tbkas = true;
1248 
1249 	return true;
1250 
1251 fail:
1252 	__nvmet_req_complete(req, status);
1253 	return false;
1254 }
1255 EXPORT_SYMBOL_GPL(nvmet_req_init);
1256 
1257 void nvmet_req_uninit(struct nvmet_req *req)
1258 {
1259 	percpu_ref_put(&req->sq->ref);
1260 	if (req->pc_ref)
1261 		nvmet_pr_put_ns_pc_ref(req->pc_ref);
1262 	if (req->ns)
1263 		nvmet_put_namespace(req->ns);
1264 }
1265 EXPORT_SYMBOL_GPL(nvmet_req_uninit);
1266 
1267 size_t nvmet_req_transfer_len(struct nvmet_req *req)
1268 {
1269 	if (likely(req->sq->qid != 0))
1270 		return nvmet_io_cmd_transfer_len(req);
1271 	if (unlikely(!req->sq->ctrl))
1272 		return nvmet_connect_cmd_data_len(req);
1273 	return nvmet_admin_cmd_data_len(req);
1274 }
1275 EXPORT_SYMBOL_GPL(nvmet_req_transfer_len);
1276 
1277 bool nvmet_check_transfer_len(struct nvmet_req *req, size_t len)
1278 {
1279 	if (unlikely(len != req->transfer_len)) {
1280 		u16 status;
1281 
1282 		req->error_loc = offsetof(struct nvme_common_command, dptr);
1283 		if (req->cmd->common.flags & NVME_CMD_SGL_ALL)
1284 			status = NVME_SC_SGL_INVALID_DATA;
1285 		else
1286 			status = NVME_SC_INVALID_FIELD;
1287 		nvmet_req_complete(req, status | NVME_STATUS_DNR);
1288 		return false;
1289 	}
1290 
1291 	return true;
1292 }
1293 EXPORT_SYMBOL_GPL(nvmet_check_transfer_len);
1294 
1295 bool nvmet_check_data_len_lte(struct nvmet_req *req, size_t data_len)
1296 {
1297 	if (unlikely(data_len > req->transfer_len)) {
1298 		u16 status;
1299 
1300 		req->error_loc = offsetof(struct nvme_common_command, dptr);
1301 		if (req->cmd->common.flags & NVME_CMD_SGL_ALL)
1302 			status = NVME_SC_SGL_INVALID_DATA;
1303 		else
1304 			status = NVME_SC_INVALID_FIELD;
1305 		nvmet_req_complete(req, status | NVME_STATUS_DNR);
1306 		return false;
1307 	}
1308 
1309 	return true;
1310 }
1311 
1312 static unsigned int nvmet_data_transfer_len(struct nvmet_req *req)
1313 {
1314 	return req->transfer_len - req->metadata_len;
1315 }
1316 
1317 static int nvmet_req_alloc_p2pmem_sgls(struct pci_dev *p2p_dev,
1318 		struct nvmet_req *req)
1319 {
1320 	req->sg = pci_p2pmem_alloc_sgl(p2p_dev, &req->sg_cnt,
1321 			nvmet_data_transfer_len(req));
1322 	if (!req->sg)
1323 		goto out_err;
1324 
1325 	if (req->metadata_len) {
1326 		req->metadata_sg = pci_p2pmem_alloc_sgl(p2p_dev,
1327 				&req->metadata_sg_cnt, req->metadata_len);
1328 		if (!req->metadata_sg)
1329 			goto out_free_sg;
1330 	}
1331 
1332 	req->p2p_dev = p2p_dev;
1333 
1334 	return 0;
1335 out_free_sg:
1336 	pci_p2pmem_free_sgl(p2p_dev, req->sg);
1337 out_err:
1338 	return -ENOMEM;
1339 }
1340 
1341 static struct pci_dev *nvmet_req_find_p2p_dev(struct nvmet_req *req)
1342 {
1343 	if (!IS_ENABLED(CONFIG_PCI_P2PDMA) ||
1344 	    !req->sq->ctrl || !req->sq->qid || !req->ns)
1345 		return NULL;
1346 	return radix_tree_lookup(&req->sq->ctrl->p2p_ns_map, req->ns->nsid);
1347 }
1348 
1349 int nvmet_req_alloc_sgls(struct nvmet_req *req)
1350 {
1351 	struct pci_dev *p2p_dev = nvmet_req_find_p2p_dev(req);
1352 
1353 	if (p2p_dev && !nvmet_req_alloc_p2pmem_sgls(p2p_dev, req))
1354 		return 0;
1355 
1356 	req->sg = sgl_alloc(nvmet_data_transfer_len(req), GFP_KERNEL,
1357 			    &req->sg_cnt);
1358 	if (unlikely(!req->sg))
1359 		goto out;
1360 
1361 	if (req->metadata_len) {
1362 		req->metadata_sg = sgl_alloc(req->metadata_len, GFP_KERNEL,
1363 					     &req->metadata_sg_cnt);
1364 		if (unlikely(!req->metadata_sg))
1365 			goto out_free;
1366 	}
1367 
1368 	return 0;
1369 out_free:
1370 	nvmet_req_free_sgls(req);
1371 out:
1372 	return -ENOMEM;
1373 }
1374 EXPORT_SYMBOL_GPL(nvmet_req_alloc_sgls);
1375 
1376 void nvmet_req_free_sgls(struct nvmet_req *req)
1377 {
1378 	if (req->p2p_dev) {
1379 		pci_p2pmem_free_sgl(req->p2p_dev, req->sg);
1380 		if (req->metadata_sg)
1381 			pci_p2pmem_free_sgl(req->p2p_dev, req->metadata_sg);
1382 		req->p2p_dev = NULL;
1383 	} else {
1384 		sgl_free(req->sg);
1385 		if (req->metadata_sg)
1386 			sgl_free(req->metadata_sg);
1387 	}
1388 
1389 	req->sg = NULL;
1390 	req->metadata_sg = NULL;
1391 	req->sg_cnt = 0;
1392 	req->metadata_sg_cnt = 0;
1393 }
1394 EXPORT_SYMBOL_GPL(nvmet_req_free_sgls);
1395 
1396 static inline bool nvmet_css_supported(u8 cc_css)
1397 {
1398 	switch (cc_css << NVME_CC_CSS_SHIFT) {
1399 	case NVME_CC_CSS_NVM:
1400 	case NVME_CC_CSS_CSI:
1401 		return true;
1402 	default:
1403 		return false;
1404 	}
1405 }
1406 
1407 static void nvmet_start_ctrl(struct nvmet_ctrl *ctrl)
1408 {
1409 	lockdep_assert_held(&ctrl->lock);
1410 
1411 	/*
1412 	 * Only I/O controllers should verify iosqes,iocqes.
1413 	 * Strictly speaking, the spec says a discovery controller
1414 	 * should verify iosqes,iocqes are zeroed, however that
1415 	 * would break backwards compatibility, so don't enforce it.
1416 	 */
1417 	if (!nvmet_is_disc_subsys(ctrl->subsys) &&
1418 	    (nvmet_cc_iosqes(ctrl->cc) != NVME_NVM_IOSQES ||
1419 	     nvmet_cc_iocqes(ctrl->cc) != NVME_NVM_IOCQES)) {
1420 		ctrl->csts = NVME_CSTS_CFS;
1421 		return;
1422 	}
1423 
1424 	if (nvmet_cc_mps(ctrl->cc) != 0 ||
1425 	    nvmet_cc_ams(ctrl->cc) != 0 ||
1426 	    !nvmet_css_supported(nvmet_cc_css(ctrl->cc))) {
1427 		ctrl->csts = NVME_CSTS_CFS;
1428 		return;
1429 	}
1430 
1431 	ctrl->csts = NVME_CSTS_RDY;
1432 
1433 	/*
1434 	 * Controllers that are not yet enabled should not really enforce the
1435 	 * keep alive timeout, but we still want to track a timeout and cleanup
1436 	 * in case a host died before it enabled the controller.  Hence, simply
1437 	 * reset the keep alive timer when the controller is enabled.
1438 	 */
1439 	if (ctrl->kato)
1440 		mod_delayed_work(nvmet_wq, &ctrl->ka_work, ctrl->kato * HZ);
1441 }
1442 
1443 static void nvmet_clear_ctrl(struct nvmet_ctrl *ctrl)
1444 {
1445 	lockdep_assert_held(&ctrl->lock);
1446 
1447 	/* XXX: tear down queues? */
1448 	ctrl->csts &= ~NVME_CSTS_RDY;
1449 	ctrl->cc = 0;
1450 }
1451 
1452 void nvmet_update_cc(struct nvmet_ctrl *ctrl, u32 new)
1453 {
1454 	u32 old;
1455 
1456 	mutex_lock(&ctrl->lock);
1457 	old = ctrl->cc;
1458 	ctrl->cc = new;
1459 
1460 	if (nvmet_cc_en(new) && !nvmet_cc_en(old))
1461 		nvmet_start_ctrl(ctrl);
1462 	if (!nvmet_cc_en(new) && nvmet_cc_en(old))
1463 		nvmet_clear_ctrl(ctrl);
1464 	if (nvmet_cc_shn(new) && !nvmet_cc_shn(old)) {
1465 		nvmet_clear_ctrl(ctrl);
1466 		ctrl->csts |= NVME_CSTS_SHST_CMPLT;
1467 	}
1468 	if (!nvmet_cc_shn(new) && nvmet_cc_shn(old))
1469 		ctrl->csts &= ~NVME_CSTS_SHST_CMPLT;
1470 	mutex_unlock(&ctrl->lock);
1471 }
1472 EXPORT_SYMBOL_GPL(nvmet_update_cc);
1473 
1474 static void nvmet_init_cap(struct nvmet_ctrl *ctrl)
1475 {
1476 	/* command sets supported: NVMe command set: */
1477 	ctrl->cap = (1ULL << 37);
1478 	/* Controller supports one or more I/O Command Sets */
1479 	ctrl->cap |= (1ULL << 43);
1480 	/* CC.EN timeout in 500msec units: */
1481 	ctrl->cap |= (15ULL << 24);
1482 	/* maximum queue entries supported: */
1483 	if (ctrl->ops->get_max_queue_size)
1484 		ctrl->cap |= min_t(u16, ctrl->ops->get_max_queue_size(ctrl),
1485 				   ctrl->port->max_queue_size) - 1;
1486 	else
1487 		ctrl->cap |= ctrl->port->max_queue_size - 1;
1488 
1489 	if (nvmet_is_passthru_subsys(ctrl->subsys))
1490 		nvmet_passthrough_override_cap(ctrl);
1491 }
1492 
1493 struct nvmet_ctrl *nvmet_ctrl_find_get(const char *subsysnqn,
1494 				       const char *hostnqn, u16 cntlid,
1495 				       struct nvmet_req *req)
1496 {
1497 	struct nvmet_ctrl *ctrl = NULL;
1498 	struct nvmet_subsys *subsys;
1499 
1500 	subsys = nvmet_find_get_subsys(req->port, subsysnqn);
1501 	if (!subsys) {
1502 		pr_warn("connect request for invalid subsystem %s!\n",
1503 			subsysnqn);
1504 		req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(subsysnqn);
1505 		goto out;
1506 	}
1507 
1508 	mutex_lock(&subsys->lock);
1509 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
1510 		if (ctrl->cntlid == cntlid) {
1511 			if (strncmp(hostnqn, ctrl->hostnqn, NVMF_NQN_SIZE)) {
1512 				pr_warn("hostnqn mismatch.\n");
1513 				continue;
1514 			}
1515 			if (!kref_get_unless_zero(&ctrl->ref))
1516 				continue;
1517 
1518 			/* ctrl found */
1519 			goto found;
1520 		}
1521 	}
1522 
1523 	ctrl = NULL; /* ctrl not found */
1524 	pr_warn("could not find controller %d for subsys %s / host %s\n",
1525 		cntlid, subsysnqn, hostnqn);
1526 	req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(cntlid);
1527 
1528 found:
1529 	mutex_unlock(&subsys->lock);
1530 	nvmet_subsys_put(subsys);
1531 out:
1532 	return ctrl;
1533 }
1534 
1535 u16 nvmet_check_ctrl_status(struct nvmet_req *req)
1536 {
1537 	if (unlikely(!(req->sq->ctrl->cc & NVME_CC_ENABLE))) {
1538 		pr_err("got cmd %d while CC.EN == 0 on qid = %d\n",
1539 		       req->cmd->common.opcode, req->sq->qid);
1540 		return NVME_SC_CMD_SEQ_ERROR | NVME_STATUS_DNR;
1541 	}
1542 
1543 	if (unlikely(!(req->sq->ctrl->csts & NVME_CSTS_RDY))) {
1544 		pr_err("got cmd %d while CSTS.RDY == 0 on qid = %d\n",
1545 		       req->cmd->common.opcode, req->sq->qid);
1546 		return NVME_SC_CMD_SEQ_ERROR | NVME_STATUS_DNR;
1547 	}
1548 
1549 	if (unlikely(!nvmet_check_auth_status(req))) {
1550 		pr_warn("qid %d not authenticated\n", req->sq->qid);
1551 		return NVME_SC_AUTH_REQUIRED | NVME_STATUS_DNR;
1552 	}
1553 	return 0;
1554 }
1555 
1556 bool nvmet_host_allowed(struct nvmet_subsys *subsys, const char *hostnqn)
1557 {
1558 	struct nvmet_host_link *p;
1559 
1560 	lockdep_assert_held(&nvmet_config_sem);
1561 
1562 	if (subsys->allow_any_host)
1563 		return true;
1564 
1565 	if (nvmet_is_disc_subsys(subsys)) /* allow all access to disc subsys */
1566 		return true;
1567 
1568 	list_for_each_entry(p, &subsys->hosts, entry) {
1569 		if (!strcmp(nvmet_host_name(p->host), hostnqn))
1570 			return true;
1571 	}
1572 
1573 	return false;
1574 }
1575 
1576 static void nvmet_setup_p2p_ns_map(struct nvmet_ctrl *ctrl,
1577 		struct device *p2p_client)
1578 {
1579 	struct nvmet_ns *ns;
1580 	unsigned long idx;
1581 
1582 	lockdep_assert_held(&ctrl->subsys->lock);
1583 
1584 	if (!p2p_client)
1585 		return;
1586 
1587 	ctrl->p2p_client = get_device(p2p_client);
1588 
1589 	nvmet_for_each_enabled_ns(&ctrl->subsys->namespaces, idx, ns)
1590 		nvmet_p2pmem_ns_add_p2p(ctrl, ns);
1591 }
1592 
1593 static void nvmet_release_p2p_ns_map(struct nvmet_ctrl *ctrl)
1594 {
1595 	struct radix_tree_iter iter;
1596 	void __rcu **slot;
1597 
1598 	lockdep_assert_held(&ctrl->subsys->lock);
1599 
1600 	radix_tree_for_each_slot(slot, &ctrl->p2p_ns_map, &iter, 0)
1601 		pci_dev_put(radix_tree_deref_slot(slot));
1602 
1603 	put_device(ctrl->p2p_client);
1604 }
1605 
1606 static void nvmet_fatal_error_handler(struct work_struct *work)
1607 {
1608 	struct nvmet_ctrl *ctrl =
1609 			container_of(work, struct nvmet_ctrl, fatal_err_work);
1610 
1611 	pr_err("ctrl %d fatal error occurred!\n", ctrl->cntlid);
1612 	ctrl->ops->delete_ctrl(ctrl);
1613 }
1614 
1615 struct nvmet_ctrl *nvmet_alloc_ctrl(struct nvmet_alloc_ctrl_args *args)
1616 {
1617 	struct nvmet_subsys *subsys;
1618 	struct nvmet_ctrl *ctrl;
1619 	u32 kato = args->kato;
1620 	u8 dhchap_status;
1621 	int ret;
1622 
1623 	args->status = NVME_SC_CONNECT_INVALID_PARAM | NVME_STATUS_DNR;
1624 	subsys = nvmet_find_get_subsys(args->port, args->subsysnqn);
1625 	if (!subsys) {
1626 		pr_warn("connect request for invalid subsystem %s!\n",
1627 			args->subsysnqn);
1628 		args->result = IPO_IATTR_CONNECT_DATA(subsysnqn);
1629 		args->error_loc = offsetof(struct nvme_common_command, dptr);
1630 		return NULL;
1631 	}
1632 
1633 	down_read(&nvmet_config_sem);
1634 	if (!nvmet_host_allowed(subsys, args->hostnqn)) {
1635 		pr_info("connect by host %s for subsystem %s not allowed\n",
1636 			args->hostnqn, args->subsysnqn);
1637 		args->result = IPO_IATTR_CONNECT_DATA(hostnqn);
1638 		up_read(&nvmet_config_sem);
1639 		args->status = NVME_SC_CONNECT_INVALID_HOST | NVME_STATUS_DNR;
1640 		args->error_loc = offsetof(struct nvme_common_command, dptr);
1641 		goto out_put_subsystem;
1642 	}
1643 	up_read(&nvmet_config_sem);
1644 
1645 	args->status = NVME_SC_INTERNAL;
1646 	ctrl = kzalloc_obj(*ctrl);
1647 	if (!ctrl)
1648 		goto out_put_subsystem;
1649 	mutex_init(&ctrl->lock);
1650 
1651 	ctrl->port = args->port;
1652 	ctrl->ops = args->ops;
1653 
1654 #ifdef CONFIG_NVME_TARGET_PASSTHRU
1655 	/* By default, set loop targets to clear IDS by default */
1656 	if (ctrl->port->disc_addr.trtype == NVMF_TRTYPE_LOOP) {
1657 		mutex_lock(&subsys->lock);
1658 		subsys->passthru = nvmet_subsys_passthru(subsys);
1659 		if (!subsys->passthru) {
1660 			mutex_unlock(&subsys->lock);
1661 			goto out_free_ctrl;
1662 		}
1663 		subsys->passthru->clear_ids = 1;
1664 		mutex_unlock(&subsys->lock);
1665 	}
1666 #endif
1667 
1668 	INIT_WORK(&ctrl->async_event_work, nvmet_async_event_work);
1669 	INIT_LIST_HEAD(&ctrl->async_events);
1670 	INIT_RADIX_TREE(&ctrl->p2p_ns_map, GFP_KERNEL);
1671 	INIT_WORK(&ctrl->fatal_err_work, nvmet_fatal_error_handler);
1672 	INIT_DELAYED_WORK(&ctrl->ka_work, nvmet_keep_alive_timer);
1673 
1674 	memcpy(ctrl->hostnqn, args->hostnqn, NVMF_NQN_SIZE);
1675 	if (args->hostid)
1676 		uuid_copy(&ctrl->hostid, args->hostid);
1677 
1678 	kref_init(&ctrl->ref);
1679 	ctrl->subsys = subsys;
1680 	ctrl->pi_support = ctrl->port->pi_enable && ctrl->subsys->pi_support;
1681 	nvmet_init_cap(ctrl);
1682 	WRITE_ONCE(ctrl->aen_enabled, NVMET_AEN_CFG_OPTIONAL);
1683 
1684 	ctrl->changed_ns_list = kmalloc_array(NVME_MAX_CHANGED_NAMESPACES,
1685 			sizeof(__le32), GFP_KERNEL);
1686 	if (!ctrl->changed_ns_list)
1687 		goto out_free_ctrl;
1688 
1689 	/*
1690 	 * Discovery controllers may use some arbitrary high value
1691 	 * in order to cleanup stale discovery sessions
1692 	 */
1693 	if (nvmet_is_disc_subsys(ctrl->subsys) && !kato)
1694 		kato = NVMET_DISC_KATO_MS;
1695 
1696 	/* keep-alive timeout in seconds */
1697 	ctrl->kato = DIV_ROUND_UP(kato, 1000);
1698 
1699 	ctrl->err_counter = 0;
1700 	spin_lock_init(&ctrl->error_lock);
1701 
1702 	down_read(&nvmet_config_sem);
1703 	mutex_lock(&subsys->lock);
1704 
1705 	ctrl->max_qid = subsys->max_qid;
1706 	ctrl->tbkas = subsys->tbkas;
1707 
1708 	ctrl->sqs = kzalloc_objs(struct nvmet_sq *, ctrl->max_qid + 1);
1709 	if (!ctrl->sqs)
1710 		goto out_free_changed_ns_list;
1711 
1712 	ctrl->cqs = kzalloc_objs(struct nvmet_cq *, ctrl->max_qid + 1);
1713 	if (!ctrl->cqs)
1714 		goto out_free_sqs;
1715 
1716 	ret = ida_alloc_range(&cntlid_ida,
1717 			     subsys->cntlid_min, subsys->cntlid_max,
1718 			     GFP_KERNEL);
1719 	if (ret < 0) {
1720 		args->status = NVME_SC_CONNECT_CTRL_BUSY | NVME_STATUS_DNR;
1721 		goto out_free_cqs;
1722 	}
1723 	ctrl->cntlid = ret;
1724 
1725 	ret = nvmet_ctrl_init_pr(ctrl);
1726 	if (ret)
1727 		goto init_pr_fail;
1728 	list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
1729 	nvmet_setup_p2p_ns_map(ctrl, args->p2p_client);
1730 	nvmet_debugfs_ctrl_setup(ctrl);
1731 	mutex_unlock(&subsys->lock);
1732 	up_read(&nvmet_config_sem);
1733 
1734 	nvmet_start_keep_alive_timer(ctrl);
1735 
1736 	dhchap_status = nvmet_setup_auth(ctrl, args->sq, false);
1737 	if (dhchap_status) {
1738 		pr_err("Failed to setup authentication, dhchap status %u\n",
1739 		       dhchap_status);
1740 		nvmet_ctrl_put(ctrl);
1741 		if (dhchap_status == NVME_AUTH_DHCHAP_FAILURE_FAILED)
1742 			args->status =
1743 				NVME_SC_CONNECT_INVALID_HOST | NVME_STATUS_DNR;
1744 		else
1745 			args->status = NVME_SC_INTERNAL;
1746 		return NULL;
1747 	}
1748 
1749 	args->status = NVME_SC_SUCCESS;
1750 
1751 	pr_info("Created %s controller %d for subsystem %s for NQN %s%s%s%s.\n",
1752 		nvmet_is_disc_subsys(ctrl->subsys) ? "discovery" : "nvm",
1753 		ctrl->cntlid, ctrl->subsys->subsysnqn, ctrl->hostnqn,
1754 		ctrl->pi_support ? " T10-PI is enabled" : "",
1755 		nvmet_has_auth(ctrl, args->sq) ? " with DH-HMAC-CHAP" : "",
1756 		nvmet_queue_tls_keyid(args->sq) ? ", TLS" : "");
1757 
1758 	return ctrl;
1759 
1760 init_pr_fail:
1761 	ida_free(&cntlid_ida, ctrl->cntlid);
1762 out_free_cqs:
1763 	kfree(ctrl->cqs);
1764 out_free_sqs:
1765 	kfree(ctrl->sqs);
1766 out_free_changed_ns_list:
1767 	mutex_unlock(&subsys->lock);
1768 	up_read(&nvmet_config_sem);
1769 	kfree(ctrl->changed_ns_list);
1770 out_free_ctrl:
1771 	kfree(ctrl);
1772 out_put_subsystem:
1773 	nvmet_subsys_put(subsys);
1774 	return NULL;
1775 }
1776 EXPORT_SYMBOL_GPL(nvmet_alloc_ctrl);
1777 
1778 static void nvmet_ctrl_free(struct kref *ref)
1779 {
1780 	struct nvmet_ctrl *ctrl = container_of(ref, struct nvmet_ctrl, ref);
1781 	struct nvmet_subsys *subsys = ctrl->subsys;
1782 
1783 	mutex_lock(&subsys->lock);
1784 	nvmet_ctrl_destroy_pr(ctrl);
1785 	nvmet_release_p2p_ns_map(ctrl);
1786 	list_del(&ctrl->subsys_entry);
1787 	mutex_unlock(&subsys->lock);
1788 
1789 	nvmet_stop_keep_alive_timer(ctrl);
1790 
1791 	cancel_work_sync(&ctrl->async_event_work);
1792 	cancel_work_sync(&ctrl->fatal_err_work);
1793 
1794 	nvmet_destroy_auth(ctrl);
1795 
1796 	nvmet_debugfs_ctrl_free(ctrl);
1797 
1798 	ida_free(&cntlid_ida, ctrl->cntlid);
1799 
1800 	nvmet_async_events_free(ctrl);
1801 	kfree(ctrl->sqs);
1802 	kfree(ctrl->cqs);
1803 	kfree(ctrl->changed_ns_list);
1804 	kfree(ctrl);
1805 
1806 	nvmet_subsys_put(subsys);
1807 }
1808 
1809 void nvmet_ctrl_put(struct nvmet_ctrl *ctrl)
1810 {
1811 	kref_put(&ctrl->ref, nvmet_ctrl_free);
1812 }
1813 EXPORT_SYMBOL_GPL(nvmet_ctrl_put);
1814 
1815 void nvmet_ctrl_fatal_error(struct nvmet_ctrl *ctrl)
1816 {
1817 	mutex_lock(&ctrl->lock);
1818 	if (!(ctrl->csts & NVME_CSTS_CFS)) {
1819 		ctrl->csts |= NVME_CSTS_CFS;
1820 		queue_work(nvmet_wq, &ctrl->fatal_err_work);
1821 	}
1822 	mutex_unlock(&ctrl->lock);
1823 }
1824 EXPORT_SYMBOL_GPL(nvmet_ctrl_fatal_error);
1825 
1826 ssize_t nvmet_ctrl_host_traddr(struct nvmet_ctrl *ctrl,
1827 		char *traddr, size_t traddr_len)
1828 {
1829 	if (!ctrl->ops->host_traddr)
1830 		return -EOPNOTSUPP;
1831 	/* They all take the address from the admin queue */
1832 	if (!ctrl->sqs[0])
1833 		return -ENOTCONN;
1834 	return ctrl->ops->host_traddr(ctrl, traddr, traddr_len);
1835 }
1836 
1837 static struct nvmet_subsys *nvmet_find_get_subsys(struct nvmet_port *port,
1838 		const char *subsysnqn)
1839 {
1840 	struct nvmet_subsys_link *p;
1841 
1842 	if (!port)
1843 		return NULL;
1844 
1845 	if (!strcmp(NVME_DISC_SUBSYS_NAME, subsysnqn)) {
1846 		if (!kref_get_unless_zero(&nvmet_disc_subsys->ref))
1847 			return NULL;
1848 		return nvmet_disc_subsys;
1849 	}
1850 
1851 	down_read(&nvmet_config_sem);
1852 	if (!strncmp(nvmet_disc_subsys->subsysnqn, subsysnqn,
1853 				NVMF_NQN_SIZE)) {
1854 		if (kref_get_unless_zero(&nvmet_disc_subsys->ref)) {
1855 			up_read(&nvmet_config_sem);
1856 			return nvmet_disc_subsys;
1857 		}
1858 	}
1859 	list_for_each_entry(p, &port->subsystems, entry) {
1860 		if (!strncmp(p->subsys->subsysnqn, subsysnqn,
1861 				NVMF_NQN_SIZE)) {
1862 			if (!kref_get_unless_zero(&p->subsys->ref))
1863 				break;
1864 			up_read(&nvmet_config_sem);
1865 			return p->subsys;
1866 		}
1867 	}
1868 	up_read(&nvmet_config_sem);
1869 	return NULL;
1870 }
1871 
1872 struct nvmet_subsys *nvmet_subsys_alloc(const char *subsysnqn,
1873 		enum nvme_subsys_type type)
1874 {
1875 	struct nvmet_subsys *subsys;
1876 	char serial[NVMET_SN_MAX_SIZE / 2];
1877 	int ret;
1878 
1879 	subsys = kzalloc_obj(*subsys);
1880 	if (!subsys)
1881 		return ERR_PTR(-ENOMEM);
1882 
1883 	subsys->ver = NVMET_DEFAULT_VS;
1884 	/* generate a random serial number as our controllers are ephemeral: */
1885 	get_random_bytes(&serial, sizeof(serial));
1886 	bin2hex(subsys->serial, &serial, sizeof(serial));
1887 
1888 	subsys->model_number = kstrdup(NVMET_DEFAULT_CTRL_MODEL, GFP_KERNEL);
1889 	if (!subsys->model_number) {
1890 		ret = -ENOMEM;
1891 		goto free_subsys;
1892 	}
1893 
1894 	subsys->ieee_oui = 0;
1895 	subsys->tbkas = true;
1896 
1897 	subsys->firmware_rev = kstrndup(UTS_RELEASE, NVMET_FR_MAX_SIZE, GFP_KERNEL);
1898 	if (!subsys->firmware_rev) {
1899 		ret = -ENOMEM;
1900 		goto free_mn;
1901 	}
1902 
1903 	switch (type) {
1904 	case NVME_NQN_NVME:
1905 		subsys->max_qid = NVMET_NR_QUEUES;
1906 		break;
1907 	case NVME_NQN_DISC:
1908 	case NVME_NQN_CURR:
1909 		subsys->max_qid = 0;
1910 		break;
1911 	default:
1912 		pr_err("%s: Unknown Subsystem type - %d\n", __func__, type);
1913 		ret = -EINVAL;
1914 		goto free_fr;
1915 	}
1916 	subsys->type = type;
1917 	subsys->subsysnqn = kstrndup(subsysnqn, NVMF_NQN_SIZE,
1918 			GFP_KERNEL);
1919 	if (!subsys->subsysnqn) {
1920 		ret = -ENOMEM;
1921 		goto free_fr;
1922 	}
1923 	subsys->cntlid_min = NVME_CNTLID_MIN;
1924 	subsys->cntlid_max = NVME_CNTLID_MAX;
1925 	kref_init(&subsys->ref);
1926 
1927 	mutex_init(&subsys->lock);
1928 	xa_init(&subsys->namespaces);
1929 	INIT_LIST_HEAD(&subsys->ctrls);
1930 	INIT_LIST_HEAD(&subsys->hosts);
1931 
1932 	ret = nvmet_debugfs_subsys_setup(subsys);
1933 	if (ret)
1934 		goto free_subsysnqn;
1935 
1936 	return subsys;
1937 
1938 free_subsysnqn:
1939 	kfree(subsys->subsysnqn);
1940 free_fr:
1941 	kfree(subsys->firmware_rev);
1942 free_mn:
1943 	kfree(subsys->model_number);
1944 free_subsys:
1945 	kfree(subsys);
1946 	return ERR_PTR(ret);
1947 }
1948 
1949 static void nvmet_subsys_free(struct kref *ref)
1950 {
1951 	struct nvmet_subsys *subsys =
1952 		container_of(ref, struct nvmet_subsys, ref);
1953 
1954 	WARN_ON_ONCE(!list_empty(&subsys->ctrls));
1955 	WARN_ON_ONCE(!list_empty(&subsys->hosts));
1956 	WARN_ON_ONCE(!xa_empty(&subsys->namespaces));
1957 
1958 	nvmet_debugfs_subsys_free(subsys);
1959 
1960 	xa_destroy(&subsys->namespaces);
1961 	nvmet_passthru_subsys_free(subsys);
1962 
1963 	kfree(subsys->subsysnqn);
1964 	kfree(subsys->model_number);
1965 	kfree(subsys->firmware_rev);
1966 	kfree(subsys);
1967 }
1968 
1969 void nvmet_subsys_del_ctrls(struct nvmet_subsys *subsys)
1970 {
1971 	struct nvmet_ctrl *ctrl;
1972 
1973 	mutex_lock(&subsys->lock);
1974 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
1975 		ctrl->ops->delete_ctrl(ctrl);
1976 	mutex_unlock(&subsys->lock);
1977 }
1978 
1979 void nvmet_subsys_put(struct nvmet_subsys *subsys)
1980 {
1981 	kref_put(&subsys->ref, nvmet_subsys_free);
1982 }
1983 
1984 static int __init nvmet_init(void)
1985 {
1986 	int error = -ENOMEM;
1987 
1988 	nvmet_ana_group_enabled[NVMET_DEFAULT_ANA_GRPID] = 1;
1989 
1990 	nvmet_bvec_cache = kmem_cache_create("nvmet-bvec",
1991 			NVMET_MAX_MPOOL_BVEC * sizeof(struct bio_vec), 0,
1992 			SLAB_HWCACHE_ALIGN, NULL);
1993 	if (!nvmet_bvec_cache)
1994 		return -ENOMEM;
1995 
1996 	zbd_wq = alloc_workqueue("nvmet-zbd-wq", WQ_MEM_RECLAIM | WQ_PERCPU,
1997 				 0);
1998 	if (!zbd_wq)
1999 		goto out_destroy_bvec_cache;
2000 
2001 	buffered_io_wq = alloc_workqueue("nvmet-buffered-io-wq",
2002 			WQ_MEM_RECLAIM | WQ_PERCPU, 0);
2003 	if (!buffered_io_wq)
2004 		goto out_free_zbd_work_queue;
2005 
2006 	nvmet_wq = alloc_workqueue("nvmet-wq",
2007 			WQ_MEM_RECLAIM | WQ_UNBOUND | WQ_SYSFS, 0);
2008 	if (!nvmet_wq)
2009 		goto out_free_buffered_work_queue;
2010 
2011 	nvmet_aen_wq = alloc_workqueue("nvmet-aen-wq",
2012 			WQ_MEM_RECLAIM | WQ_UNBOUND, 0);
2013 	if (!nvmet_aen_wq)
2014 		goto out_free_nvmet_work_queue;
2015 
2016 	error = nvmet_init_debugfs();
2017 	if (error)
2018 		goto out_free_nvmet_aen_work_queue;
2019 
2020 	error = nvmet_init_discovery();
2021 	if (error)
2022 		goto out_exit_debugfs;
2023 
2024 	error = nvmet_init_configfs();
2025 	if (error)
2026 		goto out_exit_discovery;
2027 
2028 	return 0;
2029 
2030 out_exit_discovery:
2031 	nvmet_exit_discovery();
2032 out_exit_debugfs:
2033 	nvmet_exit_debugfs();
2034 out_free_nvmet_aen_work_queue:
2035 	destroy_workqueue(nvmet_aen_wq);
2036 out_free_nvmet_work_queue:
2037 	destroy_workqueue(nvmet_wq);
2038 out_free_buffered_work_queue:
2039 	destroy_workqueue(buffered_io_wq);
2040 out_free_zbd_work_queue:
2041 	destroy_workqueue(zbd_wq);
2042 out_destroy_bvec_cache:
2043 	kmem_cache_destroy(nvmet_bvec_cache);
2044 	return error;
2045 }
2046 
2047 static void __exit nvmet_exit(void)
2048 {
2049 	nvmet_exit_configfs();
2050 	nvmet_exit_discovery();
2051 	nvmet_exit_debugfs();
2052 	ida_destroy(&cntlid_ida);
2053 	destroy_workqueue(nvmet_aen_wq);
2054 	destroy_workqueue(nvmet_wq);
2055 	destroy_workqueue(buffered_io_wq);
2056 	destroy_workqueue(zbd_wq);
2057 	kmem_cache_destroy(nvmet_bvec_cache);
2058 
2059 	BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_entry) != 1024);
2060 	BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_hdr) != 1024);
2061 }
2062 
2063 module_init(nvmet_init);
2064 module_exit(nvmet_exit);
2065 
2066 MODULE_DESCRIPTION("NVMe target core framework");
2067 MODULE_LICENSE("GPL v2");
2068