xref: /linux/drivers/nvme/target/core.c (revision 001821b0e79716c4e17c71d8e053a23599a7a508)
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 	if (ctrl) {
822 		/*
823 		 * The teardown flow may take some time, and the host may not
824 		 * send us keep-alive during this period, hence reset the
825 		 * traffic based keep-alive timer so we don't trigger a
826 		 * controller teardown as a result of a keep-alive expiration.
827 		 */
828 		ctrl->reset_tbkas = true;
829 		sq->ctrl->sqs[sq->qid] = NULL;
830 		nvmet_ctrl_put(ctrl);
831 		sq->ctrl = NULL; /* allows reusing the queue later */
832 	}
833 }
834 EXPORT_SYMBOL_GPL(nvmet_sq_destroy);
835 
836 static void nvmet_sq_free(struct percpu_ref *ref)
837 {
838 	struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref);
839 
840 	complete(&sq->free_done);
841 }
842 
843 int nvmet_sq_init(struct nvmet_sq *sq)
844 {
845 	int ret;
846 
847 	ret = percpu_ref_init(&sq->ref, nvmet_sq_free, 0, GFP_KERNEL);
848 	if (ret) {
849 		pr_err("percpu_ref init failed!\n");
850 		return ret;
851 	}
852 	init_completion(&sq->free_done);
853 	init_completion(&sq->confirm_done);
854 	nvmet_auth_sq_init(sq);
855 
856 	return 0;
857 }
858 EXPORT_SYMBOL_GPL(nvmet_sq_init);
859 
860 static inline u16 nvmet_check_ana_state(struct nvmet_port *port,
861 		struct nvmet_ns *ns)
862 {
863 	enum nvme_ana_state state = port->ana_state[ns->anagrpid];
864 
865 	if (unlikely(state == NVME_ANA_INACCESSIBLE))
866 		return NVME_SC_ANA_INACCESSIBLE;
867 	if (unlikely(state == NVME_ANA_PERSISTENT_LOSS))
868 		return NVME_SC_ANA_PERSISTENT_LOSS;
869 	if (unlikely(state == NVME_ANA_CHANGE))
870 		return NVME_SC_ANA_TRANSITION;
871 	return 0;
872 }
873 
874 static inline u16 nvmet_io_cmd_check_access(struct nvmet_req *req)
875 {
876 	if (unlikely(req->ns->readonly)) {
877 		switch (req->cmd->common.opcode) {
878 		case nvme_cmd_read:
879 		case nvme_cmd_flush:
880 			break;
881 		default:
882 			return NVME_SC_NS_WRITE_PROTECTED;
883 		}
884 	}
885 
886 	return 0;
887 }
888 
889 static u16 nvmet_parse_io_cmd(struct nvmet_req *req)
890 {
891 	struct nvme_command *cmd = req->cmd;
892 	u16 ret;
893 
894 	if (nvme_is_fabrics(cmd))
895 		return nvmet_parse_fabrics_io_cmd(req);
896 
897 	if (unlikely(!nvmet_check_auth_status(req)))
898 		return NVME_SC_AUTH_REQUIRED | NVME_SC_DNR;
899 
900 	ret = nvmet_check_ctrl_status(req);
901 	if (unlikely(ret))
902 		return ret;
903 
904 	if (nvmet_is_passthru_req(req))
905 		return nvmet_parse_passthru_io_cmd(req);
906 
907 	ret = nvmet_req_find_ns(req);
908 	if (unlikely(ret))
909 		return ret;
910 
911 	ret = nvmet_check_ana_state(req->port, req->ns);
912 	if (unlikely(ret)) {
913 		req->error_loc = offsetof(struct nvme_common_command, nsid);
914 		return ret;
915 	}
916 	ret = nvmet_io_cmd_check_access(req);
917 	if (unlikely(ret)) {
918 		req->error_loc = offsetof(struct nvme_common_command, nsid);
919 		return ret;
920 	}
921 
922 	switch (req->ns->csi) {
923 	case NVME_CSI_NVM:
924 		if (req->ns->file)
925 			return nvmet_file_parse_io_cmd(req);
926 		return nvmet_bdev_parse_io_cmd(req);
927 	case NVME_CSI_ZNS:
928 		if (IS_ENABLED(CONFIG_BLK_DEV_ZONED))
929 			return nvmet_bdev_zns_parse_io_cmd(req);
930 		return NVME_SC_INVALID_IO_CMD_SET;
931 	default:
932 		return NVME_SC_INVALID_IO_CMD_SET;
933 	}
934 }
935 
936 bool nvmet_req_init(struct nvmet_req *req, struct nvmet_cq *cq,
937 		struct nvmet_sq *sq, const struct nvmet_fabrics_ops *ops)
938 {
939 	u8 flags = req->cmd->common.flags;
940 	u16 status;
941 
942 	req->cq = cq;
943 	req->sq = sq;
944 	req->ops = ops;
945 	req->sg = NULL;
946 	req->metadata_sg = NULL;
947 	req->sg_cnt = 0;
948 	req->metadata_sg_cnt = 0;
949 	req->transfer_len = 0;
950 	req->metadata_len = 0;
951 	req->cqe->status = 0;
952 	req->cqe->sq_head = 0;
953 	req->ns = NULL;
954 	req->error_loc = NVMET_NO_ERROR_LOC;
955 	req->error_slba = 0;
956 
957 	/* no support for fused commands yet */
958 	if (unlikely(flags & (NVME_CMD_FUSE_FIRST | NVME_CMD_FUSE_SECOND))) {
959 		req->error_loc = offsetof(struct nvme_common_command, flags);
960 		status = NVME_SC_INVALID_FIELD | NVME_SC_DNR;
961 		goto fail;
962 	}
963 
964 	/*
965 	 * For fabrics, PSDT field shall describe metadata pointer (MPTR) that
966 	 * contains an address of a single contiguous physical buffer that is
967 	 * byte aligned.
968 	 */
969 	if (unlikely((flags & NVME_CMD_SGL_ALL) != NVME_CMD_SGL_METABUF)) {
970 		req->error_loc = offsetof(struct nvme_common_command, flags);
971 		status = NVME_SC_INVALID_FIELD | NVME_SC_DNR;
972 		goto fail;
973 	}
974 
975 	if (unlikely(!req->sq->ctrl))
976 		/* will return an error for any non-connect command: */
977 		status = nvmet_parse_connect_cmd(req);
978 	else if (likely(req->sq->qid != 0))
979 		status = nvmet_parse_io_cmd(req);
980 	else
981 		status = nvmet_parse_admin_cmd(req);
982 
983 	if (status)
984 		goto fail;
985 
986 	trace_nvmet_req_init(req, req->cmd);
987 
988 	if (unlikely(!percpu_ref_tryget_live(&sq->ref))) {
989 		status = NVME_SC_INVALID_FIELD | NVME_SC_DNR;
990 		goto fail;
991 	}
992 
993 	if (sq->ctrl)
994 		sq->ctrl->reset_tbkas = true;
995 
996 	return true;
997 
998 fail:
999 	__nvmet_req_complete(req, status);
1000 	return false;
1001 }
1002 EXPORT_SYMBOL_GPL(nvmet_req_init);
1003 
1004 void nvmet_req_uninit(struct nvmet_req *req)
1005 {
1006 	percpu_ref_put(&req->sq->ref);
1007 	if (req->ns)
1008 		nvmet_put_namespace(req->ns);
1009 }
1010 EXPORT_SYMBOL_GPL(nvmet_req_uninit);
1011 
1012 bool nvmet_check_transfer_len(struct nvmet_req *req, size_t len)
1013 {
1014 	if (unlikely(len != req->transfer_len)) {
1015 		req->error_loc = offsetof(struct nvme_common_command, dptr);
1016 		nvmet_req_complete(req, NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR);
1017 		return false;
1018 	}
1019 
1020 	return true;
1021 }
1022 EXPORT_SYMBOL_GPL(nvmet_check_transfer_len);
1023 
1024 bool nvmet_check_data_len_lte(struct nvmet_req *req, size_t data_len)
1025 {
1026 	if (unlikely(data_len > req->transfer_len)) {
1027 		req->error_loc = offsetof(struct nvme_common_command, dptr);
1028 		nvmet_req_complete(req, NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR);
1029 		return false;
1030 	}
1031 
1032 	return true;
1033 }
1034 
1035 static unsigned int nvmet_data_transfer_len(struct nvmet_req *req)
1036 {
1037 	return req->transfer_len - req->metadata_len;
1038 }
1039 
1040 static int nvmet_req_alloc_p2pmem_sgls(struct pci_dev *p2p_dev,
1041 		struct nvmet_req *req)
1042 {
1043 	req->sg = pci_p2pmem_alloc_sgl(p2p_dev, &req->sg_cnt,
1044 			nvmet_data_transfer_len(req));
1045 	if (!req->sg)
1046 		goto out_err;
1047 
1048 	if (req->metadata_len) {
1049 		req->metadata_sg = pci_p2pmem_alloc_sgl(p2p_dev,
1050 				&req->metadata_sg_cnt, req->metadata_len);
1051 		if (!req->metadata_sg)
1052 			goto out_free_sg;
1053 	}
1054 
1055 	req->p2p_dev = p2p_dev;
1056 
1057 	return 0;
1058 out_free_sg:
1059 	pci_p2pmem_free_sgl(req->p2p_dev, req->sg);
1060 out_err:
1061 	return -ENOMEM;
1062 }
1063 
1064 static struct pci_dev *nvmet_req_find_p2p_dev(struct nvmet_req *req)
1065 {
1066 	if (!IS_ENABLED(CONFIG_PCI_P2PDMA) ||
1067 	    !req->sq->ctrl || !req->sq->qid || !req->ns)
1068 		return NULL;
1069 	return radix_tree_lookup(&req->sq->ctrl->p2p_ns_map, req->ns->nsid);
1070 }
1071 
1072 int nvmet_req_alloc_sgls(struct nvmet_req *req)
1073 {
1074 	struct pci_dev *p2p_dev = nvmet_req_find_p2p_dev(req);
1075 
1076 	if (p2p_dev && !nvmet_req_alloc_p2pmem_sgls(p2p_dev, req))
1077 		return 0;
1078 
1079 	req->sg = sgl_alloc(nvmet_data_transfer_len(req), GFP_KERNEL,
1080 			    &req->sg_cnt);
1081 	if (unlikely(!req->sg))
1082 		goto out;
1083 
1084 	if (req->metadata_len) {
1085 		req->metadata_sg = sgl_alloc(req->metadata_len, GFP_KERNEL,
1086 					     &req->metadata_sg_cnt);
1087 		if (unlikely(!req->metadata_sg))
1088 			goto out_free;
1089 	}
1090 
1091 	return 0;
1092 out_free:
1093 	sgl_free(req->sg);
1094 out:
1095 	return -ENOMEM;
1096 }
1097 EXPORT_SYMBOL_GPL(nvmet_req_alloc_sgls);
1098 
1099 void nvmet_req_free_sgls(struct nvmet_req *req)
1100 {
1101 	if (req->p2p_dev) {
1102 		pci_p2pmem_free_sgl(req->p2p_dev, req->sg);
1103 		if (req->metadata_sg)
1104 			pci_p2pmem_free_sgl(req->p2p_dev, req->metadata_sg);
1105 		req->p2p_dev = NULL;
1106 	} else {
1107 		sgl_free(req->sg);
1108 		if (req->metadata_sg)
1109 			sgl_free(req->metadata_sg);
1110 	}
1111 
1112 	req->sg = NULL;
1113 	req->metadata_sg = NULL;
1114 	req->sg_cnt = 0;
1115 	req->metadata_sg_cnt = 0;
1116 }
1117 EXPORT_SYMBOL_GPL(nvmet_req_free_sgls);
1118 
1119 static inline bool nvmet_cc_en(u32 cc)
1120 {
1121 	return (cc >> NVME_CC_EN_SHIFT) & 0x1;
1122 }
1123 
1124 static inline u8 nvmet_cc_css(u32 cc)
1125 {
1126 	return (cc >> NVME_CC_CSS_SHIFT) & 0x7;
1127 }
1128 
1129 static inline u8 nvmet_cc_mps(u32 cc)
1130 {
1131 	return (cc >> NVME_CC_MPS_SHIFT) & 0xf;
1132 }
1133 
1134 static inline u8 nvmet_cc_ams(u32 cc)
1135 {
1136 	return (cc >> NVME_CC_AMS_SHIFT) & 0x7;
1137 }
1138 
1139 static inline u8 nvmet_cc_shn(u32 cc)
1140 {
1141 	return (cc >> NVME_CC_SHN_SHIFT) & 0x3;
1142 }
1143 
1144 static inline u8 nvmet_cc_iosqes(u32 cc)
1145 {
1146 	return (cc >> NVME_CC_IOSQES_SHIFT) & 0xf;
1147 }
1148 
1149 static inline u8 nvmet_cc_iocqes(u32 cc)
1150 {
1151 	return (cc >> NVME_CC_IOCQES_SHIFT) & 0xf;
1152 }
1153 
1154 static inline bool nvmet_css_supported(u8 cc_css)
1155 {
1156 	switch (cc_css << NVME_CC_CSS_SHIFT) {
1157 	case NVME_CC_CSS_NVM:
1158 	case NVME_CC_CSS_CSI:
1159 		return true;
1160 	default:
1161 		return false;
1162 	}
1163 }
1164 
1165 static void nvmet_start_ctrl(struct nvmet_ctrl *ctrl)
1166 {
1167 	lockdep_assert_held(&ctrl->lock);
1168 
1169 	/*
1170 	 * Only I/O controllers should verify iosqes,iocqes.
1171 	 * Strictly speaking, the spec says a discovery controller
1172 	 * should verify iosqes,iocqes are zeroed, however that
1173 	 * would break backwards compatibility, so don't enforce it.
1174 	 */
1175 	if (!nvmet_is_disc_subsys(ctrl->subsys) &&
1176 	    (nvmet_cc_iosqes(ctrl->cc) != NVME_NVM_IOSQES ||
1177 	     nvmet_cc_iocqes(ctrl->cc) != NVME_NVM_IOCQES)) {
1178 		ctrl->csts = NVME_CSTS_CFS;
1179 		return;
1180 	}
1181 
1182 	if (nvmet_cc_mps(ctrl->cc) != 0 ||
1183 	    nvmet_cc_ams(ctrl->cc) != 0 ||
1184 	    !nvmet_css_supported(nvmet_cc_css(ctrl->cc))) {
1185 		ctrl->csts = NVME_CSTS_CFS;
1186 		return;
1187 	}
1188 
1189 	ctrl->csts = NVME_CSTS_RDY;
1190 
1191 	/*
1192 	 * Controllers that are not yet enabled should not really enforce the
1193 	 * keep alive timeout, but we still want to track a timeout and cleanup
1194 	 * in case a host died before it enabled the controller.  Hence, simply
1195 	 * reset the keep alive timer when the controller is enabled.
1196 	 */
1197 	if (ctrl->kato)
1198 		mod_delayed_work(nvmet_wq, &ctrl->ka_work, ctrl->kato * HZ);
1199 }
1200 
1201 static void nvmet_clear_ctrl(struct nvmet_ctrl *ctrl)
1202 {
1203 	lockdep_assert_held(&ctrl->lock);
1204 
1205 	/* XXX: tear down queues? */
1206 	ctrl->csts &= ~NVME_CSTS_RDY;
1207 	ctrl->cc = 0;
1208 }
1209 
1210 void nvmet_update_cc(struct nvmet_ctrl *ctrl, u32 new)
1211 {
1212 	u32 old;
1213 
1214 	mutex_lock(&ctrl->lock);
1215 	old = ctrl->cc;
1216 	ctrl->cc = new;
1217 
1218 	if (nvmet_cc_en(new) && !nvmet_cc_en(old))
1219 		nvmet_start_ctrl(ctrl);
1220 	if (!nvmet_cc_en(new) && nvmet_cc_en(old))
1221 		nvmet_clear_ctrl(ctrl);
1222 	if (nvmet_cc_shn(new) && !nvmet_cc_shn(old)) {
1223 		nvmet_clear_ctrl(ctrl);
1224 		ctrl->csts |= NVME_CSTS_SHST_CMPLT;
1225 	}
1226 	if (!nvmet_cc_shn(new) && nvmet_cc_shn(old))
1227 		ctrl->csts &= ~NVME_CSTS_SHST_CMPLT;
1228 	mutex_unlock(&ctrl->lock);
1229 }
1230 
1231 static void nvmet_init_cap(struct nvmet_ctrl *ctrl)
1232 {
1233 	/* command sets supported: NVMe command set: */
1234 	ctrl->cap = (1ULL << 37);
1235 	/* Controller supports one or more I/O Command Sets */
1236 	ctrl->cap |= (1ULL << 43);
1237 	/* CC.EN timeout in 500msec units: */
1238 	ctrl->cap |= (15ULL << 24);
1239 	/* maximum queue entries supported: */
1240 	if (ctrl->ops->get_max_queue_size)
1241 		ctrl->cap |= min_t(u16, ctrl->ops->get_max_queue_size(ctrl),
1242 				   ctrl->port->max_queue_size) - 1;
1243 	else
1244 		ctrl->cap |= ctrl->port->max_queue_size - 1;
1245 
1246 	if (nvmet_is_passthru_subsys(ctrl->subsys))
1247 		nvmet_passthrough_override_cap(ctrl);
1248 }
1249 
1250 struct nvmet_ctrl *nvmet_ctrl_find_get(const char *subsysnqn,
1251 				       const char *hostnqn, u16 cntlid,
1252 				       struct nvmet_req *req)
1253 {
1254 	struct nvmet_ctrl *ctrl = NULL;
1255 	struct nvmet_subsys *subsys;
1256 
1257 	subsys = nvmet_find_get_subsys(req->port, subsysnqn);
1258 	if (!subsys) {
1259 		pr_warn("connect request for invalid subsystem %s!\n",
1260 			subsysnqn);
1261 		req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(subsysnqn);
1262 		goto out;
1263 	}
1264 
1265 	mutex_lock(&subsys->lock);
1266 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
1267 		if (ctrl->cntlid == cntlid) {
1268 			if (strncmp(hostnqn, ctrl->hostnqn, NVMF_NQN_SIZE)) {
1269 				pr_warn("hostnqn mismatch.\n");
1270 				continue;
1271 			}
1272 			if (!kref_get_unless_zero(&ctrl->ref))
1273 				continue;
1274 
1275 			/* ctrl found */
1276 			goto found;
1277 		}
1278 	}
1279 
1280 	ctrl = NULL; /* ctrl not found */
1281 	pr_warn("could not find controller %d for subsys %s / host %s\n",
1282 		cntlid, subsysnqn, hostnqn);
1283 	req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(cntlid);
1284 
1285 found:
1286 	mutex_unlock(&subsys->lock);
1287 	nvmet_subsys_put(subsys);
1288 out:
1289 	return ctrl;
1290 }
1291 
1292 u16 nvmet_check_ctrl_status(struct nvmet_req *req)
1293 {
1294 	if (unlikely(!(req->sq->ctrl->cc & NVME_CC_ENABLE))) {
1295 		pr_err("got cmd %d while CC.EN == 0 on qid = %d\n",
1296 		       req->cmd->common.opcode, req->sq->qid);
1297 		return NVME_SC_CMD_SEQ_ERROR | NVME_SC_DNR;
1298 	}
1299 
1300 	if (unlikely(!(req->sq->ctrl->csts & NVME_CSTS_RDY))) {
1301 		pr_err("got cmd %d while CSTS.RDY == 0 on qid = %d\n",
1302 		       req->cmd->common.opcode, req->sq->qid);
1303 		return NVME_SC_CMD_SEQ_ERROR | NVME_SC_DNR;
1304 	}
1305 
1306 	if (unlikely(!nvmet_check_auth_status(req))) {
1307 		pr_warn("qid %d not authenticated\n", req->sq->qid);
1308 		return NVME_SC_AUTH_REQUIRED | NVME_SC_DNR;
1309 	}
1310 	return 0;
1311 }
1312 
1313 bool nvmet_host_allowed(struct nvmet_subsys *subsys, const char *hostnqn)
1314 {
1315 	struct nvmet_host_link *p;
1316 
1317 	lockdep_assert_held(&nvmet_config_sem);
1318 
1319 	if (subsys->allow_any_host)
1320 		return true;
1321 
1322 	if (nvmet_is_disc_subsys(subsys)) /* allow all access to disc subsys */
1323 		return true;
1324 
1325 	list_for_each_entry(p, &subsys->hosts, entry) {
1326 		if (!strcmp(nvmet_host_name(p->host), hostnqn))
1327 			return true;
1328 	}
1329 
1330 	return false;
1331 }
1332 
1333 /*
1334  * Note: ctrl->subsys->lock should be held when calling this function
1335  */
1336 static void nvmet_setup_p2p_ns_map(struct nvmet_ctrl *ctrl,
1337 		struct nvmet_req *req)
1338 {
1339 	struct nvmet_ns *ns;
1340 	unsigned long idx;
1341 
1342 	if (!req->p2p_client)
1343 		return;
1344 
1345 	ctrl->p2p_client = get_device(req->p2p_client);
1346 
1347 	xa_for_each(&ctrl->subsys->namespaces, idx, ns)
1348 		nvmet_p2pmem_ns_add_p2p(ctrl, ns);
1349 }
1350 
1351 /*
1352  * Note: ctrl->subsys->lock should be held when calling this function
1353  */
1354 static void nvmet_release_p2p_ns_map(struct nvmet_ctrl *ctrl)
1355 {
1356 	struct radix_tree_iter iter;
1357 	void __rcu **slot;
1358 
1359 	radix_tree_for_each_slot(slot, &ctrl->p2p_ns_map, &iter, 0)
1360 		pci_dev_put(radix_tree_deref_slot(slot));
1361 
1362 	put_device(ctrl->p2p_client);
1363 }
1364 
1365 static void nvmet_fatal_error_handler(struct work_struct *work)
1366 {
1367 	struct nvmet_ctrl *ctrl =
1368 			container_of(work, struct nvmet_ctrl, fatal_err_work);
1369 
1370 	pr_err("ctrl %d fatal error occurred!\n", ctrl->cntlid);
1371 	ctrl->ops->delete_ctrl(ctrl);
1372 }
1373 
1374 u16 nvmet_alloc_ctrl(const char *subsysnqn, const char *hostnqn,
1375 		struct nvmet_req *req, u32 kato, struct nvmet_ctrl **ctrlp)
1376 {
1377 	struct nvmet_subsys *subsys;
1378 	struct nvmet_ctrl *ctrl;
1379 	int ret;
1380 	u16 status;
1381 
1382 	status = NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR;
1383 	subsys = nvmet_find_get_subsys(req->port, subsysnqn);
1384 	if (!subsys) {
1385 		pr_warn("connect request for invalid subsystem %s!\n",
1386 			subsysnqn);
1387 		req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(subsysnqn);
1388 		req->error_loc = offsetof(struct nvme_common_command, dptr);
1389 		goto out;
1390 	}
1391 
1392 	down_read(&nvmet_config_sem);
1393 	if (!nvmet_host_allowed(subsys, hostnqn)) {
1394 		pr_info("connect by host %s for subsystem %s not allowed\n",
1395 			hostnqn, subsysnqn);
1396 		req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(hostnqn);
1397 		up_read(&nvmet_config_sem);
1398 		status = NVME_SC_CONNECT_INVALID_HOST | NVME_SC_DNR;
1399 		req->error_loc = offsetof(struct nvme_common_command, dptr);
1400 		goto out_put_subsystem;
1401 	}
1402 	up_read(&nvmet_config_sem);
1403 
1404 	status = NVME_SC_INTERNAL;
1405 	ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
1406 	if (!ctrl)
1407 		goto out_put_subsystem;
1408 	mutex_init(&ctrl->lock);
1409 
1410 	ctrl->port = req->port;
1411 	ctrl->ops = req->ops;
1412 
1413 #ifdef CONFIG_NVME_TARGET_PASSTHRU
1414 	/* By default, set loop targets to clear IDS by default */
1415 	if (ctrl->port->disc_addr.trtype == NVMF_TRTYPE_LOOP)
1416 		subsys->clear_ids = 1;
1417 #endif
1418 
1419 	INIT_WORK(&ctrl->async_event_work, nvmet_async_event_work);
1420 	INIT_LIST_HEAD(&ctrl->async_events);
1421 	INIT_RADIX_TREE(&ctrl->p2p_ns_map, GFP_KERNEL);
1422 	INIT_WORK(&ctrl->fatal_err_work, nvmet_fatal_error_handler);
1423 	INIT_DELAYED_WORK(&ctrl->ka_work, nvmet_keep_alive_timer);
1424 
1425 	memcpy(ctrl->subsysnqn, subsysnqn, NVMF_NQN_SIZE);
1426 	memcpy(ctrl->hostnqn, hostnqn, NVMF_NQN_SIZE);
1427 
1428 	kref_init(&ctrl->ref);
1429 	ctrl->subsys = subsys;
1430 	ctrl->pi_support = ctrl->port->pi_enable && ctrl->subsys->pi_support;
1431 	nvmet_init_cap(ctrl);
1432 	WRITE_ONCE(ctrl->aen_enabled, NVMET_AEN_CFG_OPTIONAL);
1433 
1434 	ctrl->changed_ns_list = kmalloc_array(NVME_MAX_CHANGED_NAMESPACES,
1435 			sizeof(__le32), GFP_KERNEL);
1436 	if (!ctrl->changed_ns_list)
1437 		goto out_free_ctrl;
1438 
1439 	ctrl->sqs = kcalloc(subsys->max_qid + 1,
1440 			sizeof(struct nvmet_sq *),
1441 			GFP_KERNEL);
1442 	if (!ctrl->sqs)
1443 		goto out_free_changed_ns_list;
1444 
1445 	ret = ida_alloc_range(&cntlid_ida,
1446 			     subsys->cntlid_min, subsys->cntlid_max,
1447 			     GFP_KERNEL);
1448 	if (ret < 0) {
1449 		status = NVME_SC_CONNECT_CTRL_BUSY | NVME_SC_DNR;
1450 		goto out_free_sqs;
1451 	}
1452 	ctrl->cntlid = ret;
1453 
1454 	/*
1455 	 * Discovery controllers may use some arbitrary high value
1456 	 * in order to cleanup stale discovery sessions
1457 	 */
1458 	if (nvmet_is_disc_subsys(ctrl->subsys) && !kato)
1459 		kato = NVMET_DISC_KATO_MS;
1460 
1461 	/* keep-alive timeout in seconds */
1462 	ctrl->kato = DIV_ROUND_UP(kato, 1000);
1463 
1464 	ctrl->err_counter = 0;
1465 	spin_lock_init(&ctrl->error_lock);
1466 
1467 	nvmet_start_keep_alive_timer(ctrl);
1468 
1469 	mutex_lock(&subsys->lock);
1470 	list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
1471 	nvmet_setup_p2p_ns_map(ctrl, req);
1472 	mutex_unlock(&subsys->lock);
1473 
1474 	*ctrlp = ctrl;
1475 	return 0;
1476 
1477 out_free_sqs:
1478 	kfree(ctrl->sqs);
1479 out_free_changed_ns_list:
1480 	kfree(ctrl->changed_ns_list);
1481 out_free_ctrl:
1482 	kfree(ctrl);
1483 out_put_subsystem:
1484 	nvmet_subsys_put(subsys);
1485 out:
1486 	return status;
1487 }
1488 
1489 static void nvmet_ctrl_free(struct kref *ref)
1490 {
1491 	struct nvmet_ctrl *ctrl = container_of(ref, struct nvmet_ctrl, ref);
1492 	struct nvmet_subsys *subsys = ctrl->subsys;
1493 
1494 	mutex_lock(&subsys->lock);
1495 	nvmet_release_p2p_ns_map(ctrl);
1496 	list_del(&ctrl->subsys_entry);
1497 	mutex_unlock(&subsys->lock);
1498 
1499 	nvmet_stop_keep_alive_timer(ctrl);
1500 
1501 	flush_work(&ctrl->async_event_work);
1502 	cancel_work_sync(&ctrl->fatal_err_work);
1503 
1504 	nvmet_destroy_auth(ctrl);
1505 
1506 	ida_free(&cntlid_ida, ctrl->cntlid);
1507 
1508 	nvmet_async_events_free(ctrl);
1509 	kfree(ctrl->sqs);
1510 	kfree(ctrl->changed_ns_list);
1511 	kfree(ctrl);
1512 
1513 	nvmet_subsys_put(subsys);
1514 }
1515 
1516 void nvmet_ctrl_put(struct nvmet_ctrl *ctrl)
1517 {
1518 	kref_put(&ctrl->ref, nvmet_ctrl_free);
1519 }
1520 
1521 void nvmet_ctrl_fatal_error(struct nvmet_ctrl *ctrl)
1522 {
1523 	mutex_lock(&ctrl->lock);
1524 	if (!(ctrl->csts & NVME_CSTS_CFS)) {
1525 		ctrl->csts |= NVME_CSTS_CFS;
1526 		queue_work(nvmet_wq, &ctrl->fatal_err_work);
1527 	}
1528 	mutex_unlock(&ctrl->lock);
1529 }
1530 EXPORT_SYMBOL_GPL(nvmet_ctrl_fatal_error);
1531 
1532 static struct nvmet_subsys *nvmet_find_get_subsys(struct nvmet_port *port,
1533 		const char *subsysnqn)
1534 {
1535 	struct nvmet_subsys_link *p;
1536 
1537 	if (!port)
1538 		return NULL;
1539 
1540 	if (!strcmp(NVME_DISC_SUBSYS_NAME, subsysnqn)) {
1541 		if (!kref_get_unless_zero(&nvmet_disc_subsys->ref))
1542 			return NULL;
1543 		return nvmet_disc_subsys;
1544 	}
1545 
1546 	down_read(&nvmet_config_sem);
1547 	if (!strncmp(nvmet_disc_subsys->subsysnqn, subsysnqn,
1548 				NVMF_NQN_SIZE)) {
1549 		if (kref_get_unless_zero(&nvmet_disc_subsys->ref)) {
1550 			up_read(&nvmet_config_sem);
1551 			return nvmet_disc_subsys;
1552 		}
1553 	}
1554 	list_for_each_entry(p, &port->subsystems, entry) {
1555 		if (!strncmp(p->subsys->subsysnqn, subsysnqn,
1556 				NVMF_NQN_SIZE)) {
1557 			if (!kref_get_unless_zero(&p->subsys->ref))
1558 				break;
1559 			up_read(&nvmet_config_sem);
1560 			return p->subsys;
1561 		}
1562 	}
1563 	up_read(&nvmet_config_sem);
1564 	return NULL;
1565 }
1566 
1567 struct nvmet_subsys *nvmet_subsys_alloc(const char *subsysnqn,
1568 		enum nvme_subsys_type type)
1569 {
1570 	struct nvmet_subsys *subsys;
1571 	char serial[NVMET_SN_MAX_SIZE / 2];
1572 	int ret;
1573 
1574 	subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
1575 	if (!subsys)
1576 		return ERR_PTR(-ENOMEM);
1577 
1578 	subsys->ver = NVMET_DEFAULT_VS;
1579 	/* generate a random serial number as our controllers are ephemeral: */
1580 	get_random_bytes(&serial, sizeof(serial));
1581 	bin2hex(subsys->serial, &serial, sizeof(serial));
1582 
1583 	subsys->model_number = kstrdup(NVMET_DEFAULT_CTRL_MODEL, GFP_KERNEL);
1584 	if (!subsys->model_number) {
1585 		ret = -ENOMEM;
1586 		goto free_subsys;
1587 	}
1588 
1589 	subsys->ieee_oui = 0;
1590 
1591 	subsys->firmware_rev = kstrndup(UTS_RELEASE, NVMET_FR_MAX_SIZE, GFP_KERNEL);
1592 	if (!subsys->firmware_rev) {
1593 		ret = -ENOMEM;
1594 		goto free_mn;
1595 	}
1596 
1597 	switch (type) {
1598 	case NVME_NQN_NVME:
1599 		subsys->max_qid = NVMET_NR_QUEUES;
1600 		break;
1601 	case NVME_NQN_DISC:
1602 	case NVME_NQN_CURR:
1603 		subsys->max_qid = 0;
1604 		break;
1605 	default:
1606 		pr_err("%s: Unknown Subsystem type - %d\n", __func__, type);
1607 		ret = -EINVAL;
1608 		goto free_fr;
1609 	}
1610 	subsys->type = type;
1611 	subsys->subsysnqn = kstrndup(subsysnqn, NVMF_NQN_SIZE,
1612 			GFP_KERNEL);
1613 	if (!subsys->subsysnqn) {
1614 		ret = -ENOMEM;
1615 		goto free_fr;
1616 	}
1617 	subsys->cntlid_min = NVME_CNTLID_MIN;
1618 	subsys->cntlid_max = NVME_CNTLID_MAX;
1619 	kref_init(&subsys->ref);
1620 
1621 	mutex_init(&subsys->lock);
1622 	xa_init(&subsys->namespaces);
1623 	INIT_LIST_HEAD(&subsys->ctrls);
1624 	INIT_LIST_HEAD(&subsys->hosts);
1625 
1626 	return subsys;
1627 
1628 free_fr:
1629 	kfree(subsys->firmware_rev);
1630 free_mn:
1631 	kfree(subsys->model_number);
1632 free_subsys:
1633 	kfree(subsys);
1634 	return ERR_PTR(ret);
1635 }
1636 
1637 static void nvmet_subsys_free(struct kref *ref)
1638 {
1639 	struct nvmet_subsys *subsys =
1640 		container_of(ref, struct nvmet_subsys, ref);
1641 
1642 	WARN_ON_ONCE(!xa_empty(&subsys->namespaces));
1643 
1644 	xa_destroy(&subsys->namespaces);
1645 	nvmet_passthru_subsys_free(subsys);
1646 
1647 	kfree(subsys->subsysnqn);
1648 	kfree(subsys->model_number);
1649 	kfree(subsys->firmware_rev);
1650 	kfree(subsys);
1651 }
1652 
1653 void nvmet_subsys_del_ctrls(struct nvmet_subsys *subsys)
1654 {
1655 	struct nvmet_ctrl *ctrl;
1656 
1657 	mutex_lock(&subsys->lock);
1658 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
1659 		ctrl->ops->delete_ctrl(ctrl);
1660 	mutex_unlock(&subsys->lock);
1661 }
1662 
1663 void nvmet_subsys_put(struct nvmet_subsys *subsys)
1664 {
1665 	kref_put(&subsys->ref, nvmet_subsys_free);
1666 }
1667 
1668 static int __init nvmet_init(void)
1669 {
1670 	int error = -ENOMEM;
1671 
1672 	nvmet_ana_group_enabled[NVMET_DEFAULT_ANA_GRPID] = 1;
1673 
1674 	nvmet_bvec_cache = kmem_cache_create("nvmet-bvec",
1675 			NVMET_MAX_MPOOL_BVEC * sizeof(struct bio_vec), 0,
1676 			SLAB_HWCACHE_ALIGN, NULL);
1677 	if (!nvmet_bvec_cache)
1678 		return -ENOMEM;
1679 
1680 	zbd_wq = alloc_workqueue("nvmet-zbd-wq", WQ_MEM_RECLAIM, 0);
1681 	if (!zbd_wq)
1682 		goto out_destroy_bvec_cache;
1683 
1684 	buffered_io_wq = alloc_workqueue("nvmet-buffered-io-wq",
1685 			WQ_MEM_RECLAIM, 0);
1686 	if (!buffered_io_wq)
1687 		goto out_free_zbd_work_queue;
1688 
1689 	nvmet_wq = alloc_workqueue("nvmet-wq",
1690 			WQ_MEM_RECLAIM | WQ_UNBOUND, 0);
1691 	if (!nvmet_wq)
1692 		goto out_free_buffered_work_queue;
1693 
1694 	error = nvmet_init_discovery();
1695 	if (error)
1696 		goto out_free_nvmet_work_queue;
1697 
1698 	error = nvmet_init_configfs();
1699 	if (error)
1700 		goto out_exit_discovery;
1701 	return 0;
1702 
1703 out_exit_discovery:
1704 	nvmet_exit_discovery();
1705 out_free_nvmet_work_queue:
1706 	destroy_workqueue(nvmet_wq);
1707 out_free_buffered_work_queue:
1708 	destroy_workqueue(buffered_io_wq);
1709 out_free_zbd_work_queue:
1710 	destroy_workqueue(zbd_wq);
1711 out_destroy_bvec_cache:
1712 	kmem_cache_destroy(nvmet_bvec_cache);
1713 	return error;
1714 }
1715 
1716 static void __exit nvmet_exit(void)
1717 {
1718 	nvmet_exit_configfs();
1719 	nvmet_exit_discovery();
1720 	ida_destroy(&cntlid_ida);
1721 	destroy_workqueue(nvmet_wq);
1722 	destroy_workqueue(buffered_io_wq);
1723 	destroy_workqueue(zbd_wq);
1724 	kmem_cache_destroy(nvmet_bvec_cache);
1725 
1726 	BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_entry) != 1024);
1727 	BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_hdr) != 1024);
1728 }
1729 
1730 module_init(nvmet_init);
1731 module_exit(nvmet_exit);
1732 
1733 MODULE_DESCRIPTION("NVMe target core framework");
1734 MODULE_LICENSE("GPL v2");
1735