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