xref: /openbmc/linux/drivers/nvme/host/fabrics.c (revision 657c45b3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVMe over Fabrics common host code.
4  * Copyright (c) 2015-2016 HGST, a Western Digital Company.
5  */
6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
7 #include <linux/init.h>
8 #include <linux/miscdevice.h>
9 #include <linux/module.h>
10 #include <linux/mutex.h>
11 #include <linux/parser.h>
12 #include <linux/seq_file.h>
13 #include "nvme.h"
14 #include "fabrics.h"
15 
16 static LIST_HEAD(nvmf_transports);
17 static DECLARE_RWSEM(nvmf_transports_rwsem);
18 
19 static LIST_HEAD(nvmf_hosts);
20 static DEFINE_MUTEX(nvmf_hosts_mutex);
21 
22 static struct nvmf_host *nvmf_default_host;
23 
24 static struct nvmf_host *nvmf_host_alloc(const char *hostnqn, uuid_t *id)
25 {
26 	struct nvmf_host *host;
27 
28 	host = kmalloc(sizeof(*host), GFP_KERNEL);
29 	if (!host)
30 		return NULL;
31 
32 	kref_init(&host->ref);
33 	uuid_copy(&host->id, id);
34 	strscpy(host->nqn, hostnqn, NVMF_NQN_SIZE);
35 
36 	return host;
37 }
38 
39 static struct nvmf_host *nvmf_host_add(const char *hostnqn, uuid_t *id)
40 {
41 	struct nvmf_host *host;
42 
43 	mutex_lock(&nvmf_hosts_mutex);
44 
45 	/*
46 	 * We have defined a host as how it is perceived by the target.
47 	 * Therefore, we don't allow different Host NQNs with the same Host ID.
48 	 * Similarly, we do not allow the usage of the same Host NQN with
49 	 * different Host IDs. This'll maintain unambiguous host identification.
50 	 */
51 	list_for_each_entry(host, &nvmf_hosts, list) {
52 		bool same_hostnqn = !strcmp(host->nqn, hostnqn);
53 		bool same_hostid = uuid_equal(&host->id, id);
54 
55 		if (same_hostnqn && same_hostid) {
56 			kref_get(&host->ref);
57 			goto out_unlock;
58 		}
59 		if (same_hostnqn) {
60 			pr_err("found same hostnqn %s but different hostid %pUb\n",
61 			       hostnqn, id);
62 			host = ERR_PTR(-EINVAL);
63 			goto out_unlock;
64 		}
65 		if (same_hostid) {
66 			pr_err("found same hostid %pUb but different hostnqn %s\n",
67 			       id, hostnqn);
68 			host = ERR_PTR(-EINVAL);
69 			goto out_unlock;
70 		}
71 	}
72 
73 	host = nvmf_host_alloc(hostnqn, id);
74 	if (!host) {
75 		host = ERR_PTR(-ENOMEM);
76 		goto out_unlock;
77 	}
78 
79 	list_add_tail(&host->list, &nvmf_hosts);
80 out_unlock:
81 	mutex_unlock(&nvmf_hosts_mutex);
82 	return host;
83 }
84 
85 static struct nvmf_host *nvmf_host_default(void)
86 {
87 	struct nvmf_host *host;
88 	char nqn[NVMF_NQN_SIZE];
89 	uuid_t id;
90 
91 	uuid_gen(&id);
92 	snprintf(nqn, NVMF_NQN_SIZE,
93 		"nqn.2014-08.org.nvmexpress:uuid:%pUb", &id);
94 
95 	host = nvmf_host_alloc(nqn, &id);
96 	if (!host)
97 		return NULL;
98 
99 	mutex_lock(&nvmf_hosts_mutex);
100 	list_add_tail(&host->list, &nvmf_hosts);
101 	mutex_unlock(&nvmf_hosts_mutex);
102 
103 	return host;
104 }
105 
106 static void nvmf_host_destroy(struct kref *ref)
107 {
108 	struct nvmf_host *host = container_of(ref, struct nvmf_host, ref);
109 
110 	mutex_lock(&nvmf_hosts_mutex);
111 	list_del(&host->list);
112 	mutex_unlock(&nvmf_hosts_mutex);
113 
114 	kfree(host);
115 }
116 
117 static void nvmf_host_put(struct nvmf_host *host)
118 {
119 	if (host)
120 		kref_put(&host->ref, nvmf_host_destroy);
121 }
122 
123 /**
124  * nvmf_get_address() -  Get address/port
125  * @ctrl:	Host NVMe controller instance which we got the address
126  * @buf:	OUTPUT parameter that will contain the address/port
127  * @size:	buffer size
128  */
129 int nvmf_get_address(struct nvme_ctrl *ctrl, char *buf, int size)
130 {
131 	int len = 0;
132 
133 	if (ctrl->opts->mask & NVMF_OPT_TRADDR)
134 		len += scnprintf(buf, size, "traddr=%s", ctrl->opts->traddr);
135 	if (ctrl->opts->mask & NVMF_OPT_TRSVCID)
136 		len += scnprintf(buf + len, size - len, "%strsvcid=%s",
137 				(len) ? "," : "", ctrl->opts->trsvcid);
138 	if (ctrl->opts->mask & NVMF_OPT_HOST_TRADDR)
139 		len += scnprintf(buf + len, size - len, "%shost_traddr=%s",
140 				(len) ? "," : "", ctrl->opts->host_traddr);
141 	if (ctrl->opts->mask & NVMF_OPT_HOST_IFACE)
142 		len += scnprintf(buf + len, size - len, "%shost_iface=%s",
143 				(len) ? "," : "", ctrl->opts->host_iface);
144 	len += scnprintf(buf + len, size - len, "\n");
145 
146 	return len;
147 }
148 EXPORT_SYMBOL_GPL(nvmf_get_address);
149 
150 /**
151  * nvmf_reg_read32() -  NVMe Fabrics "Property Get" API function.
152  * @ctrl:	Host NVMe controller instance maintaining the admin
153  *		queue used to submit the property read command to
154  *		the allocated NVMe controller resource on the target system.
155  * @off:	Starting offset value of the targeted property
156  *		register (see the fabrics section of the NVMe standard).
157  * @val:	OUTPUT parameter that will contain the value of
158  *		the property after a successful read.
159  *
160  * Used by the host system to retrieve a 32-bit capsule property value
161  * from an NVMe controller on the target system.
162  *
163  * ("Capsule property" is an "PCIe register concept" applied to the
164  * NVMe fabrics space.)
165  *
166  * Return:
167  *	0: successful read
168  *	> 0: NVMe error status code
169  *	< 0: Linux errno error code
170  */
171 int nvmf_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val)
172 {
173 	struct nvme_command cmd = { };
174 	union nvme_result res;
175 	int ret;
176 
177 	cmd.prop_get.opcode = nvme_fabrics_command;
178 	cmd.prop_get.fctype = nvme_fabrics_type_property_get;
179 	cmd.prop_get.offset = cpu_to_le32(off);
180 
181 	ret = __nvme_submit_sync_cmd(ctrl->fabrics_q, &cmd, &res, NULL, 0,
182 			NVME_QID_ANY, 0, 0);
183 
184 	if (ret >= 0)
185 		*val = le64_to_cpu(res.u64);
186 	if (unlikely(ret != 0))
187 		dev_err(ctrl->device,
188 			"Property Get error: %d, offset %#x\n",
189 			ret > 0 ? ret & ~NVME_SC_DNR : ret, off);
190 
191 	return ret;
192 }
193 EXPORT_SYMBOL_GPL(nvmf_reg_read32);
194 
195 /**
196  * nvmf_reg_read64() -  NVMe Fabrics "Property Get" API function.
197  * @ctrl:	Host NVMe controller instance maintaining the admin
198  *		queue used to submit the property read command to
199  *		the allocated controller resource on the target system.
200  * @off:	Starting offset value of the targeted property
201  *		register (see the fabrics section of the NVMe standard).
202  * @val:	OUTPUT parameter that will contain the value of
203  *		the property after a successful read.
204  *
205  * Used by the host system to retrieve a 64-bit capsule property value
206  * from an NVMe controller on the target system.
207  *
208  * ("Capsule property" is an "PCIe register concept" applied to the
209  * NVMe fabrics space.)
210  *
211  * Return:
212  *	0: successful read
213  *	> 0: NVMe error status code
214  *	< 0: Linux errno error code
215  */
216 int nvmf_reg_read64(struct nvme_ctrl *ctrl, u32 off, u64 *val)
217 {
218 	struct nvme_command cmd = { };
219 	union nvme_result res;
220 	int ret;
221 
222 	cmd.prop_get.opcode = nvme_fabrics_command;
223 	cmd.prop_get.fctype = nvme_fabrics_type_property_get;
224 	cmd.prop_get.attrib = 1;
225 	cmd.prop_get.offset = cpu_to_le32(off);
226 
227 	ret = __nvme_submit_sync_cmd(ctrl->fabrics_q, &cmd, &res, NULL, 0,
228 			NVME_QID_ANY, 0, 0);
229 
230 	if (ret >= 0)
231 		*val = le64_to_cpu(res.u64);
232 	if (unlikely(ret != 0))
233 		dev_err(ctrl->device,
234 			"Property Get error: %d, offset %#x\n",
235 			ret > 0 ? ret & ~NVME_SC_DNR : ret, off);
236 	return ret;
237 }
238 EXPORT_SYMBOL_GPL(nvmf_reg_read64);
239 
240 /**
241  * nvmf_reg_write32() -  NVMe Fabrics "Property Write" API function.
242  * @ctrl:	Host NVMe controller instance maintaining the admin
243  *		queue used to submit the property read command to
244  *		the allocated NVMe controller resource on the target system.
245  * @off:	Starting offset value of the targeted property
246  *		register (see the fabrics section of the NVMe standard).
247  * @val:	Input parameter that contains the value to be
248  *		written to the property.
249  *
250  * Used by the NVMe host system to write a 32-bit capsule property value
251  * to an NVMe controller on the target system.
252  *
253  * ("Capsule property" is an "PCIe register concept" applied to the
254  * NVMe fabrics space.)
255  *
256  * Return:
257  *	0: successful write
258  *	> 0: NVMe error status code
259  *	< 0: Linux errno error code
260  */
261 int nvmf_reg_write32(struct nvme_ctrl *ctrl, u32 off, u32 val)
262 {
263 	struct nvme_command cmd = { };
264 	int ret;
265 
266 	cmd.prop_set.opcode = nvme_fabrics_command;
267 	cmd.prop_set.fctype = nvme_fabrics_type_property_set;
268 	cmd.prop_set.attrib = 0;
269 	cmd.prop_set.offset = cpu_to_le32(off);
270 	cmd.prop_set.value = cpu_to_le64(val);
271 
272 	ret = __nvme_submit_sync_cmd(ctrl->fabrics_q, &cmd, NULL, NULL, 0,
273 			NVME_QID_ANY, 0, 0);
274 	if (unlikely(ret))
275 		dev_err(ctrl->device,
276 			"Property Set error: %d, offset %#x\n",
277 			ret > 0 ? ret & ~NVME_SC_DNR : ret, off);
278 	return ret;
279 }
280 EXPORT_SYMBOL_GPL(nvmf_reg_write32);
281 
282 /**
283  * nvmf_log_connect_error() - Error-parsing-diagnostic print out function for
284  * 				connect() errors.
285  * @ctrl:	The specific /dev/nvmeX device that had the error.
286  * @errval:	Error code to be decoded in a more human-friendly
287  * 		printout.
288  * @offset:	For use with the NVMe error code
289  * 		NVME_SC_CONNECT_INVALID_PARAM.
290  * @cmd:	This is the SQE portion of a submission capsule.
291  * @data:	This is the "Data" portion of a submission capsule.
292  */
293 static void nvmf_log_connect_error(struct nvme_ctrl *ctrl,
294 		int errval, int offset, struct nvme_command *cmd,
295 		struct nvmf_connect_data *data)
296 {
297 	int err_sctype = errval & ~NVME_SC_DNR;
298 
299 	if (errval < 0) {
300 		dev_err(ctrl->device,
301 			"Connect command failed, errno: %d\n", errval);
302 		return;
303 	}
304 
305 	switch (err_sctype) {
306 	case NVME_SC_CONNECT_INVALID_PARAM:
307 		if (offset >> 16) {
308 			char *inv_data = "Connect Invalid Data Parameter";
309 
310 			switch (offset & 0xffff) {
311 			case (offsetof(struct nvmf_connect_data, cntlid)):
312 				dev_err(ctrl->device,
313 					"%s, cntlid: %d\n",
314 					inv_data, data->cntlid);
315 				break;
316 			case (offsetof(struct nvmf_connect_data, hostnqn)):
317 				dev_err(ctrl->device,
318 					"%s, hostnqn \"%s\"\n",
319 					inv_data, data->hostnqn);
320 				break;
321 			case (offsetof(struct nvmf_connect_data, subsysnqn)):
322 				dev_err(ctrl->device,
323 					"%s, subsysnqn \"%s\"\n",
324 					inv_data, data->subsysnqn);
325 				break;
326 			default:
327 				dev_err(ctrl->device,
328 					"%s, starting byte offset: %d\n",
329 				       inv_data, offset & 0xffff);
330 				break;
331 			}
332 		} else {
333 			char *inv_sqe = "Connect Invalid SQE Parameter";
334 
335 			switch (offset) {
336 			case (offsetof(struct nvmf_connect_command, qid)):
337 				dev_err(ctrl->device,
338 				       "%s, qid %d\n",
339 					inv_sqe, cmd->connect.qid);
340 				break;
341 			default:
342 				dev_err(ctrl->device,
343 					"%s, starting byte offset: %d\n",
344 					inv_sqe, offset);
345 			}
346 		}
347 		break;
348 	case NVME_SC_CONNECT_INVALID_HOST:
349 		dev_err(ctrl->device,
350 			"Connect for subsystem %s is not allowed, hostnqn: %s\n",
351 			data->subsysnqn, data->hostnqn);
352 		break;
353 	case NVME_SC_CONNECT_CTRL_BUSY:
354 		dev_err(ctrl->device,
355 			"Connect command failed: controller is busy or not available\n");
356 		break;
357 	case NVME_SC_CONNECT_FORMAT:
358 		dev_err(ctrl->device,
359 			"Connect incompatible format: %d",
360 			cmd->connect.recfmt);
361 		break;
362 	case NVME_SC_HOST_PATH_ERROR:
363 		dev_err(ctrl->device,
364 			"Connect command failed: host path error\n");
365 		break;
366 	case NVME_SC_AUTH_REQUIRED:
367 		dev_err(ctrl->device,
368 			"Connect command failed: authentication required\n");
369 		break;
370 	default:
371 		dev_err(ctrl->device,
372 			"Connect command failed, error wo/DNR bit: %d\n",
373 			err_sctype);
374 		break;
375 	}
376 }
377 
378 static struct nvmf_connect_data *nvmf_connect_data_prep(struct nvme_ctrl *ctrl,
379 		u16 cntlid)
380 {
381 	struct nvmf_connect_data *data;
382 
383 	data = kzalloc(sizeof(*data), GFP_KERNEL);
384 	if (!data)
385 		return NULL;
386 
387 	uuid_copy(&data->hostid, &ctrl->opts->host->id);
388 	data->cntlid = cpu_to_le16(cntlid);
389 	strncpy(data->subsysnqn, ctrl->opts->subsysnqn, NVMF_NQN_SIZE);
390 	strncpy(data->hostnqn, ctrl->opts->host->nqn, NVMF_NQN_SIZE);
391 
392 	return data;
393 }
394 
395 static void nvmf_connect_cmd_prep(struct nvme_ctrl *ctrl, u16 qid,
396 		struct nvme_command *cmd)
397 {
398 	cmd->connect.opcode = nvme_fabrics_command;
399 	cmd->connect.fctype = nvme_fabrics_type_connect;
400 	cmd->connect.qid = cpu_to_le16(qid);
401 
402 	if (qid) {
403 		cmd->connect.sqsize = cpu_to_le16(ctrl->sqsize);
404 	} else {
405 		cmd->connect.sqsize = cpu_to_le16(NVME_AQ_DEPTH - 1);
406 
407 		/*
408 		 * set keep-alive timeout in seconds granularity (ms * 1000)
409 		 */
410 		cmd->connect.kato = cpu_to_le32(ctrl->kato * 1000);
411 	}
412 
413 	if (ctrl->opts->disable_sqflow)
414 		cmd->connect.cattr |= NVME_CONNECT_DISABLE_SQFLOW;
415 }
416 
417 /**
418  * nvmf_connect_admin_queue() - NVMe Fabrics Admin Queue "Connect"
419  *				API function.
420  * @ctrl:	Host nvme controller instance used to request
421  *              a new NVMe controller allocation on the target
422  *              system and  establish an NVMe Admin connection to
423  *              that controller.
424  *
425  * This function enables an NVMe host device to request a new allocation of
426  * an NVMe controller resource on a target system as well establish a
427  * fabrics-protocol connection of the NVMe Admin queue between the
428  * host system device and the allocated NVMe controller on the
429  * target system via a NVMe Fabrics "Connect" command.
430  *
431  * Return:
432  *	0: success
433  *	> 0: NVMe error status code
434  *	< 0: Linux errno error code
435  *
436  */
437 int nvmf_connect_admin_queue(struct nvme_ctrl *ctrl)
438 {
439 	struct nvme_command cmd = { };
440 	union nvme_result res;
441 	struct nvmf_connect_data *data;
442 	int ret;
443 	u32 result;
444 
445 	nvmf_connect_cmd_prep(ctrl, 0, &cmd);
446 
447 	data = nvmf_connect_data_prep(ctrl, 0xffff);
448 	if (!data)
449 		return -ENOMEM;
450 
451 	ret = __nvme_submit_sync_cmd(ctrl->fabrics_q, &cmd, &res,
452 			data, sizeof(*data), NVME_QID_ANY, 1,
453 			BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
454 	if (ret) {
455 		nvmf_log_connect_error(ctrl, ret, le32_to_cpu(res.u32),
456 				       &cmd, data);
457 		goto out_free_data;
458 	}
459 
460 	result = le32_to_cpu(res.u32);
461 	ctrl->cntlid = result & 0xFFFF;
462 	if (result & (NVME_CONNECT_AUTHREQ_ATR | NVME_CONNECT_AUTHREQ_ASCR)) {
463 		/* Secure concatenation is not implemented */
464 		if (result & NVME_CONNECT_AUTHREQ_ASCR) {
465 			dev_warn(ctrl->device,
466 				 "qid 0: secure concatenation is not supported\n");
467 			ret = NVME_SC_AUTH_REQUIRED;
468 			goto out_free_data;
469 		}
470 		/* Authentication required */
471 		ret = nvme_auth_negotiate(ctrl, 0);
472 		if (ret) {
473 			dev_warn(ctrl->device,
474 				 "qid 0: authentication setup failed\n");
475 			ret = NVME_SC_AUTH_REQUIRED;
476 			goto out_free_data;
477 		}
478 		ret = nvme_auth_wait(ctrl, 0);
479 		if (ret)
480 			dev_warn(ctrl->device,
481 				 "qid 0: authentication failed\n");
482 		else
483 			dev_info(ctrl->device,
484 				 "qid 0: authenticated\n");
485 	}
486 out_free_data:
487 	kfree(data);
488 	return ret;
489 }
490 EXPORT_SYMBOL_GPL(nvmf_connect_admin_queue);
491 
492 /**
493  * nvmf_connect_io_queue() - NVMe Fabrics I/O Queue "Connect"
494  *			     API function.
495  * @ctrl:	Host nvme controller instance used to establish an
496  *		NVMe I/O queue connection to the already allocated NVMe
497  *		controller on the target system.
498  * @qid:	NVMe I/O queue number for the new I/O connection between
499  *		host and target (note qid == 0 is illegal as this is
500  *		the Admin queue, per NVMe standard).
501  *
502  * This function issues a fabrics-protocol connection
503  * of a NVMe I/O queue (via NVMe Fabrics "Connect" command)
504  * between the host system device and the allocated NVMe controller
505  * on the target system.
506  *
507  * Return:
508  *	0: success
509  *	> 0: NVMe error status code
510  *	< 0: Linux errno error code
511  */
512 int nvmf_connect_io_queue(struct nvme_ctrl *ctrl, u16 qid)
513 {
514 	struct nvme_command cmd = { };
515 	struct nvmf_connect_data *data;
516 	union nvme_result res;
517 	int ret;
518 	u32 result;
519 
520 	nvmf_connect_cmd_prep(ctrl, qid, &cmd);
521 
522 	data = nvmf_connect_data_prep(ctrl, ctrl->cntlid);
523 	if (!data)
524 		return -ENOMEM;
525 
526 	ret = __nvme_submit_sync_cmd(ctrl->connect_q, &cmd, &res,
527 			data, sizeof(*data), qid, 1,
528 			BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
529 	if (ret) {
530 		nvmf_log_connect_error(ctrl, ret, le32_to_cpu(res.u32),
531 				       &cmd, data);
532 	}
533 	result = le32_to_cpu(res.u32);
534 	if (result & (NVME_CONNECT_AUTHREQ_ATR | NVME_CONNECT_AUTHREQ_ASCR)) {
535 		/* Secure concatenation is not implemented */
536 		if (result & NVME_CONNECT_AUTHREQ_ASCR) {
537 			dev_warn(ctrl->device,
538 				 "qid 0: secure concatenation is not supported\n");
539 			ret = NVME_SC_AUTH_REQUIRED;
540 			goto out_free_data;
541 		}
542 		/* Authentication required */
543 		ret = nvme_auth_negotiate(ctrl, qid);
544 		if (ret) {
545 			dev_warn(ctrl->device,
546 				 "qid %d: authentication setup failed\n", qid);
547 			ret = NVME_SC_AUTH_REQUIRED;
548 		} else {
549 			ret = nvme_auth_wait(ctrl, qid);
550 			if (ret)
551 				dev_warn(ctrl->device,
552 					 "qid %u: authentication failed\n", qid);
553 		}
554 	}
555 out_free_data:
556 	kfree(data);
557 	return ret;
558 }
559 EXPORT_SYMBOL_GPL(nvmf_connect_io_queue);
560 
561 bool nvmf_should_reconnect(struct nvme_ctrl *ctrl)
562 {
563 	if (ctrl->opts->max_reconnects == -1 ||
564 	    ctrl->nr_reconnects < ctrl->opts->max_reconnects)
565 		return true;
566 
567 	return false;
568 }
569 EXPORT_SYMBOL_GPL(nvmf_should_reconnect);
570 
571 /**
572  * nvmf_register_transport() - NVMe Fabrics Library registration function.
573  * @ops:	Transport ops instance to be registered to the
574  *		common fabrics library.
575  *
576  * API function that registers the type of specific transport fabric
577  * being implemented to the common NVMe fabrics library. Part of
578  * the overall init sequence of starting up a fabrics driver.
579  */
580 int nvmf_register_transport(struct nvmf_transport_ops *ops)
581 {
582 	if (!ops->create_ctrl)
583 		return -EINVAL;
584 
585 	down_write(&nvmf_transports_rwsem);
586 	list_add_tail(&ops->entry, &nvmf_transports);
587 	up_write(&nvmf_transports_rwsem);
588 
589 	return 0;
590 }
591 EXPORT_SYMBOL_GPL(nvmf_register_transport);
592 
593 /**
594  * nvmf_unregister_transport() - NVMe Fabrics Library unregistration function.
595  * @ops:	Transport ops instance to be unregistered from the
596  *		common fabrics library.
597  *
598  * Fabrics API function that unregisters the type of specific transport
599  * fabric being implemented from the common NVMe fabrics library.
600  * Part of the overall exit sequence of unloading the implemented driver.
601  */
602 void nvmf_unregister_transport(struct nvmf_transport_ops *ops)
603 {
604 	down_write(&nvmf_transports_rwsem);
605 	list_del(&ops->entry);
606 	up_write(&nvmf_transports_rwsem);
607 }
608 EXPORT_SYMBOL_GPL(nvmf_unregister_transport);
609 
610 static struct nvmf_transport_ops *nvmf_lookup_transport(
611 		struct nvmf_ctrl_options *opts)
612 {
613 	struct nvmf_transport_ops *ops;
614 
615 	lockdep_assert_held(&nvmf_transports_rwsem);
616 
617 	list_for_each_entry(ops, &nvmf_transports, entry) {
618 		if (strcmp(ops->name, opts->transport) == 0)
619 			return ops;
620 	}
621 
622 	return NULL;
623 }
624 
625 static const match_table_t opt_tokens = {
626 	{ NVMF_OPT_TRANSPORT,		"transport=%s"		},
627 	{ NVMF_OPT_TRADDR,		"traddr=%s"		},
628 	{ NVMF_OPT_TRSVCID,		"trsvcid=%s"		},
629 	{ NVMF_OPT_NQN,			"nqn=%s"		},
630 	{ NVMF_OPT_QUEUE_SIZE,		"queue_size=%d"		},
631 	{ NVMF_OPT_NR_IO_QUEUES,	"nr_io_queues=%d"	},
632 	{ NVMF_OPT_RECONNECT_DELAY,	"reconnect_delay=%d"	},
633 	{ NVMF_OPT_CTRL_LOSS_TMO,	"ctrl_loss_tmo=%d"	},
634 	{ NVMF_OPT_KATO,		"keep_alive_tmo=%d"	},
635 	{ NVMF_OPT_HOSTNQN,		"hostnqn=%s"		},
636 	{ NVMF_OPT_HOST_TRADDR,		"host_traddr=%s"	},
637 	{ NVMF_OPT_HOST_IFACE,		"host_iface=%s"		},
638 	{ NVMF_OPT_HOST_ID,		"hostid=%s"		},
639 	{ NVMF_OPT_DUP_CONNECT,		"duplicate_connect"	},
640 	{ NVMF_OPT_DISABLE_SQFLOW,	"disable_sqflow"	},
641 	{ NVMF_OPT_HDR_DIGEST,		"hdr_digest"		},
642 	{ NVMF_OPT_DATA_DIGEST,		"data_digest"		},
643 	{ NVMF_OPT_NR_WRITE_QUEUES,	"nr_write_queues=%d"	},
644 	{ NVMF_OPT_NR_POLL_QUEUES,	"nr_poll_queues=%d"	},
645 	{ NVMF_OPT_TOS,			"tos=%d"		},
646 	{ NVMF_OPT_FAIL_FAST_TMO,	"fast_io_fail_tmo=%d"	},
647 	{ NVMF_OPT_DISCOVERY,		"discovery"		},
648 	{ NVMF_OPT_DHCHAP_SECRET,	"dhchap_secret=%s"	},
649 	{ NVMF_OPT_DHCHAP_CTRL_SECRET,	"dhchap_ctrl_secret=%s"	},
650 	{ NVMF_OPT_ERR,			NULL			}
651 };
652 
653 static int nvmf_parse_options(struct nvmf_ctrl_options *opts,
654 		const char *buf)
655 {
656 	substring_t args[MAX_OPT_ARGS];
657 	char *options, *o, *p;
658 	int token, ret = 0;
659 	size_t nqnlen  = 0;
660 	int ctrl_loss_tmo = NVMF_DEF_CTRL_LOSS_TMO;
661 	uuid_t hostid;
662 	char hostnqn[NVMF_NQN_SIZE];
663 
664 	/* Set defaults */
665 	opts->queue_size = NVMF_DEF_QUEUE_SIZE;
666 	opts->nr_io_queues = num_online_cpus();
667 	opts->reconnect_delay = NVMF_DEF_RECONNECT_DELAY;
668 	opts->kato = 0;
669 	opts->duplicate_connect = false;
670 	opts->fast_io_fail_tmo = NVMF_DEF_FAIL_FAST_TMO;
671 	opts->hdr_digest = false;
672 	opts->data_digest = false;
673 	opts->tos = -1; /* < 0 == use transport default */
674 
675 	options = o = kstrdup(buf, GFP_KERNEL);
676 	if (!options)
677 		return -ENOMEM;
678 
679 	/* use default host if not given by user space */
680 	uuid_copy(&hostid, &nvmf_default_host->id);
681 	strscpy(hostnqn, nvmf_default_host->nqn, NVMF_NQN_SIZE);
682 
683 	while ((p = strsep(&o, ",\n")) != NULL) {
684 		if (!*p)
685 			continue;
686 
687 		token = match_token(p, opt_tokens, args);
688 		opts->mask |= token;
689 		switch (token) {
690 		case NVMF_OPT_TRANSPORT:
691 			p = match_strdup(args);
692 			if (!p) {
693 				ret = -ENOMEM;
694 				goto out;
695 			}
696 			kfree(opts->transport);
697 			opts->transport = p;
698 			break;
699 		case NVMF_OPT_NQN:
700 			p = match_strdup(args);
701 			if (!p) {
702 				ret = -ENOMEM;
703 				goto out;
704 			}
705 			kfree(opts->subsysnqn);
706 			opts->subsysnqn = p;
707 			nqnlen = strlen(opts->subsysnqn);
708 			if (nqnlen >= NVMF_NQN_SIZE) {
709 				pr_err("%s needs to be < %d bytes\n",
710 					opts->subsysnqn, NVMF_NQN_SIZE);
711 				ret = -EINVAL;
712 				goto out;
713 			}
714 			opts->discovery_nqn =
715 				!(strcmp(opts->subsysnqn,
716 					 NVME_DISC_SUBSYS_NAME));
717 			break;
718 		case NVMF_OPT_TRADDR:
719 			p = match_strdup(args);
720 			if (!p) {
721 				ret = -ENOMEM;
722 				goto out;
723 			}
724 			kfree(opts->traddr);
725 			opts->traddr = p;
726 			break;
727 		case NVMF_OPT_TRSVCID:
728 			p = match_strdup(args);
729 			if (!p) {
730 				ret = -ENOMEM;
731 				goto out;
732 			}
733 			kfree(opts->trsvcid);
734 			opts->trsvcid = p;
735 			break;
736 		case NVMF_OPT_QUEUE_SIZE:
737 			if (match_int(args, &token)) {
738 				ret = -EINVAL;
739 				goto out;
740 			}
741 			if (token < NVMF_MIN_QUEUE_SIZE ||
742 			    token > NVMF_MAX_QUEUE_SIZE) {
743 				pr_err("Invalid queue_size %d\n", token);
744 				ret = -EINVAL;
745 				goto out;
746 			}
747 			opts->queue_size = token;
748 			break;
749 		case NVMF_OPT_NR_IO_QUEUES:
750 			if (match_int(args, &token)) {
751 				ret = -EINVAL;
752 				goto out;
753 			}
754 			if (token <= 0) {
755 				pr_err("Invalid number of IOQs %d\n", token);
756 				ret = -EINVAL;
757 				goto out;
758 			}
759 			if (opts->discovery_nqn) {
760 				pr_debug("Ignoring nr_io_queues value for discovery controller\n");
761 				break;
762 			}
763 
764 			opts->nr_io_queues = min_t(unsigned int,
765 					num_online_cpus(), token);
766 			break;
767 		case NVMF_OPT_KATO:
768 			if (match_int(args, &token)) {
769 				ret = -EINVAL;
770 				goto out;
771 			}
772 
773 			if (token < 0) {
774 				pr_err("Invalid keep_alive_tmo %d\n", token);
775 				ret = -EINVAL;
776 				goto out;
777 			} else if (token == 0 && !opts->discovery_nqn) {
778 				/* Allowed for debug */
779 				pr_warn("keep_alive_tmo 0 won't execute keep alives!!!\n");
780 			}
781 			opts->kato = token;
782 			break;
783 		case NVMF_OPT_CTRL_LOSS_TMO:
784 			if (match_int(args, &token)) {
785 				ret = -EINVAL;
786 				goto out;
787 			}
788 
789 			if (token < 0)
790 				pr_warn("ctrl_loss_tmo < 0 will reconnect forever\n");
791 			ctrl_loss_tmo = token;
792 			break;
793 		case NVMF_OPT_FAIL_FAST_TMO:
794 			if (match_int(args, &token)) {
795 				ret = -EINVAL;
796 				goto out;
797 			}
798 
799 			if (token >= 0)
800 				pr_warn("I/O fail on reconnect controller after %d sec\n",
801 					token);
802 			else
803 				token = -1;
804 
805 			opts->fast_io_fail_tmo = token;
806 			break;
807 		case NVMF_OPT_HOSTNQN:
808 			if (opts->host) {
809 				pr_err("hostnqn already user-assigned: %s\n",
810 				       opts->host->nqn);
811 				ret = -EADDRINUSE;
812 				goto out;
813 			}
814 			p = match_strdup(args);
815 			if (!p) {
816 				ret = -ENOMEM;
817 				goto out;
818 			}
819 			nqnlen = strlen(p);
820 			if (nqnlen >= NVMF_NQN_SIZE) {
821 				pr_err("%s needs to be < %d bytes\n",
822 					p, NVMF_NQN_SIZE);
823 				kfree(p);
824 				ret = -EINVAL;
825 				goto out;
826 			}
827 			strscpy(hostnqn, p, NVMF_NQN_SIZE);
828 			kfree(p);
829 			break;
830 		case NVMF_OPT_RECONNECT_DELAY:
831 			if (match_int(args, &token)) {
832 				ret = -EINVAL;
833 				goto out;
834 			}
835 			if (token <= 0) {
836 				pr_err("Invalid reconnect_delay %d\n", token);
837 				ret = -EINVAL;
838 				goto out;
839 			}
840 			opts->reconnect_delay = token;
841 			break;
842 		case NVMF_OPT_HOST_TRADDR:
843 			p = match_strdup(args);
844 			if (!p) {
845 				ret = -ENOMEM;
846 				goto out;
847 			}
848 			kfree(opts->host_traddr);
849 			opts->host_traddr = p;
850 			break;
851 		case NVMF_OPT_HOST_IFACE:
852 			p = match_strdup(args);
853 			if (!p) {
854 				ret = -ENOMEM;
855 				goto out;
856 			}
857 			kfree(opts->host_iface);
858 			opts->host_iface = p;
859 			break;
860 		case NVMF_OPT_HOST_ID:
861 			p = match_strdup(args);
862 			if (!p) {
863 				ret = -ENOMEM;
864 				goto out;
865 			}
866 			ret = uuid_parse(p, &hostid);
867 			if (ret) {
868 				pr_err("Invalid hostid %s\n", p);
869 				ret = -EINVAL;
870 				kfree(p);
871 				goto out;
872 			}
873 			kfree(p);
874 			break;
875 		case NVMF_OPT_DUP_CONNECT:
876 			opts->duplicate_connect = true;
877 			break;
878 		case NVMF_OPT_DISABLE_SQFLOW:
879 			opts->disable_sqflow = true;
880 			break;
881 		case NVMF_OPT_HDR_DIGEST:
882 			opts->hdr_digest = true;
883 			break;
884 		case NVMF_OPT_DATA_DIGEST:
885 			opts->data_digest = true;
886 			break;
887 		case NVMF_OPT_NR_WRITE_QUEUES:
888 			if (match_int(args, &token)) {
889 				ret = -EINVAL;
890 				goto out;
891 			}
892 			if (token <= 0) {
893 				pr_err("Invalid nr_write_queues %d\n", token);
894 				ret = -EINVAL;
895 				goto out;
896 			}
897 			opts->nr_write_queues = token;
898 			break;
899 		case NVMF_OPT_NR_POLL_QUEUES:
900 			if (match_int(args, &token)) {
901 				ret = -EINVAL;
902 				goto out;
903 			}
904 			if (token <= 0) {
905 				pr_err("Invalid nr_poll_queues %d\n", token);
906 				ret = -EINVAL;
907 				goto out;
908 			}
909 			opts->nr_poll_queues = token;
910 			break;
911 		case NVMF_OPT_TOS:
912 			if (match_int(args, &token)) {
913 				ret = -EINVAL;
914 				goto out;
915 			}
916 			if (token < 0) {
917 				pr_err("Invalid type of service %d\n", token);
918 				ret = -EINVAL;
919 				goto out;
920 			}
921 			if (token > 255) {
922 				pr_warn("Clamping type of service to 255\n");
923 				token = 255;
924 			}
925 			opts->tos = token;
926 			break;
927 		case NVMF_OPT_DISCOVERY:
928 			opts->discovery_nqn = true;
929 			break;
930 		case NVMF_OPT_DHCHAP_SECRET:
931 			p = match_strdup(args);
932 			if (!p) {
933 				ret = -ENOMEM;
934 				goto out;
935 			}
936 			if (strlen(p) < 11 || strncmp(p, "DHHC-1:", 7)) {
937 				pr_err("Invalid DH-CHAP secret %s\n", p);
938 				ret = -EINVAL;
939 				goto out;
940 			}
941 			kfree(opts->dhchap_secret);
942 			opts->dhchap_secret = p;
943 			break;
944 		case NVMF_OPT_DHCHAP_CTRL_SECRET:
945 			p = match_strdup(args);
946 			if (!p) {
947 				ret = -ENOMEM;
948 				goto out;
949 			}
950 			if (strlen(p) < 11 || strncmp(p, "DHHC-1:", 7)) {
951 				pr_err("Invalid DH-CHAP secret %s\n", p);
952 				ret = -EINVAL;
953 				goto out;
954 			}
955 			kfree(opts->dhchap_ctrl_secret);
956 			opts->dhchap_ctrl_secret = p;
957 			break;
958 		default:
959 			pr_warn("unknown parameter or missing value '%s' in ctrl creation request\n",
960 				p);
961 			ret = -EINVAL;
962 			goto out;
963 		}
964 	}
965 
966 	if (opts->discovery_nqn) {
967 		opts->nr_io_queues = 0;
968 		opts->nr_write_queues = 0;
969 		opts->nr_poll_queues = 0;
970 		opts->duplicate_connect = true;
971 	} else {
972 		if (!opts->kato)
973 			opts->kato = NVME_DEFAULT_KATO;
974 	}
975 	if (ctrl_loss_tmo < 0) {
976 		opts->max_reconnects = -1;
977 	} else {
978 		opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo,
979 						opts->reconnect_delay);
980 		if (ctrl_loss_tmo < opts->fast_io_fail_tmo)
981 			pr_warn("failfast tmo (%d) larger than controller loss tmo (%d)\n",
982 				opts->fast_io_fail_tmo, ctrl_loss_tmo);
983 	}
984 
985 	opts->host = nvmf_host_add(hostnqn, &hostid);
986 	if (IS_ERR(opts->host)) {
987 		ret = PTR_ERR(opts->host);
988 		opts->host = NULL;
989 		goto out;
990 	}
991 
992 out:
993 	kfree(options);
994 	return ret;
995 }
996 
997 void nvmf_set_io_queues(struct nvmf_ctrl_options *opts, u32 nr_io_queues,
998 			u32 io_queues[HCTX_MAX_TYPES])
999 {
1000 	if (opts->nr_write_queues && opts->nr_io_queues < nr_io_queues) {
1001 		/*
1002 		 * separate read/write queues
1003 		 * hand out dedicated default queues only after we have
1004 		 * sufficient read queues.
1005 		 */
1006 		io_queues[HCTX_TYPE_READ] = opts->nr_io_queues;
1007 		nr_io_queues -= io_queues[HCTX_TYPE_READ];
1008 		io_queues[HCTX_TYPE_DEFAULT] =
1009 			min(opts->nr_write_queues, nr_io_queues);
1010 		nr_io_queues -= io_queues[HCTX_TYPE_DEFAULT];
1011 	} else {
1012 		/*
1013 		 * shared read/write queues
1014 		 * either no write queues were requested, or we don't have
1015 		 * sufficient queue count to have dedicated default queues.
1016 		 */
1017 		io_queues[HCTX_TYPE_DEFAULT] =
1018 			min(opts->nr_io_queues, nr_io_queues);
1019 		nr_io_queues -= io_queues[HCTX_TYPE_DEFAULT];
1020 	}
1021 
1022 	if (opts->nr_poll_queues && nr_io_queues) {
1023 		/* map dedicated poll queues only if we have queues left */
1024 		io_queues[HCTX_TYPE_POLL] =
1025 			min(opts->nr_poll_queues, nr_io_queues);
1026 	}
1027 }
1028 EXPORT_SYMBOL_GPL(nvmf_set_io_queues);
1029 
1030 void nvmf_map_queues(struct blk_mq_tag_set *set, struct nvme_ctrl *ctrl,
1031 		     u32 io_queues[HCTX_MAX_TYPES])
1032 {
1033 	struct nvmf_ctrl_options *opts = ctrl->opts;
1034 
1035 	if (opts->nr_write_queues && io_queues[HCTX_TYPE_READ]) {
1036 		/* separate read/write queues */
1037 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
1038 			io_queues[HCTX_TYPE_DEFAULT];
1039 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
1040 		set->map[HCTX_TYPE_READ].nr_queues =
1041 			io_queues[HCTX_TYPE_READ];
1042 		set->map[HCTX_TYPE_READ].queue_offset =
1043 			io_queues[HCTX_TYPE_DEFAULT];
1044 	} else {
1045 		/* shared read/write queues */
1046 		set->map[HCTX_TYPE_DEFAULT].nr_queues =
1047 			io_queues[HCTX_TYPE_DEFAULT];
1048 		set->map[HCTX_TYPE_DEFAULT].queue_offset = 0;
1049 		set->map[HCTX_TYPE_READ].nr_queues =
1050 			io_queues[HCTX_TYPE_DEFAULT];
1051 		set->map[HCTX_TYPE_READ].queue_offset = 0;
1052 	}
1053 
1054 	blk_mq_map_queues(&set->map[HCTX_TYPE_DEFAULT]);
1055 	blk_mq_map_queues(&set->map[HCTX_TYPE_READ]);
1056 	if (opts->nr_poll_queues && io_queues[HCTX_TYPE_POLL]) {
1057 		/* map dedicated poll queues only if we have queues left */
1058 		set->map[HCTX_TYPE_POLL].nr_queues = io_queues[HCTX_TYPE_POLL];
1059 		set->map[HCTX_TYPE_POLL].queue_offset =
1060 			io_queues[HCTX_TYPE_DEFAULT] +
1061 			io_queues[HCTX_TYPE_READ];
1062 		blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]);
1063 	}
1064 
1065 	dev_info(ctrl->device,
1066 		"mapped %d/%d/%d default/read/poll queues.\n",
1067 		io_queues[HCTX_TYPE_DEFAULT],
1068 		io_queues[HCTX_TYPE_READ],
1069 		io_queues[HCTX_TYPE_POLL]);
1070 }
1071 EXPORT_SYMBOL_GPL(nvmf_map_queues);
1072 
1073 static int nvmf_check_required_opts(struct nvmf_ctrl_options *opts,
1074 		unsigned int required_opts)
1075 {
1076 	if ((opts->mask & required_opts) != required_opts) {
1077 		unsigned int i;
1078 
1079 		for (i = 0; i < ARRAY_SIZE(opt_tokens); i++) {
1080 			if ((opt_tokens[i].token & required_opts) &&
1081 			    !(opt_tokens[i].token & opts->mask)) {
1082 				pr_warn("missing parameter '%s'\n",
1083 					opt_tokens[i].pattern);
1084 			}
1085 		}
1086 
1087 		return -EINVAL;
1088 	}
1089 
1090 	return 0;
1091 }
1092 
1093 bool nvmf_ip_options_match(struct nvme_ctrl *ctrl,
1094 		struct nvmf_ctrl_options *opts)
1095 {
1096 	if (!nvmf_ctlr_matches_baseopts(ctrl, opts) ||
1097 	    strcmp(opts->traddr, ctrl->opts->traddr) ||
1098 	    strcmp(opts->trsvcid, ctrl->opts->trsvcid))
1099 		return false;
1100 
1101 	/*
1102 	 * Checking the local address or host interfaces is rough.
1103 	 *
1104 	 * In most cases, none is specified and the host port or
1105 	 * host interface is selected by the stack.
1106 	 *
1107 	 * Assume no match if:
1108 	 * -  local address or host interface is specified and address
1109 	 *    or host interface is not the same
1110 	 * -  local address or host interface is not specified but
1111 	 *    remote is, or vice versa (admin using specific
1112 	 *    host_traddr/host_iface when it matters).
1113 	 */
1114 	if ((opts->mask & NVMF_OPT_HOST_TRADDR) &&
1115 	    (ctrl->opts->mask & NVMF_OPT_HOST_TRADDR)) {
1116 		if (strcmp(opts->host_traddr, ctrl->opts->host_traddr))
1117 			return false;
1118 	} else if ((opts->mask & NVMF_OPT_HOST_TRADDR) ||
1119 		   (ctrl->opts->mask & NVMF_OPT_HOST_TRADDR)) {
1120 		return false;
1121 	}
1122 
1123 	if ((opts->mask & NVMF_OPT_HOST_IFACE) &&
1124 	    (ctrl->opts->mask & NVMF_OPT_HOST_IFACE)) {
1125 		if (strcmp(opts->host_iface, ctrl->opts->host_iface))
1126 			return false;
1127 	} else if ((opts->mask & NVMF_OPT_HOST_IFACE) ||
1128 		   (ctrl->opts->mask & NVMF_OPT_HOST_IFACE)) {
1129 		return false;
1130 	}
1131 
1132 	return true;
1133 }
1134 EXPORT_SYMBOL_GPL(nvmf_ip_options_match);
1135 
1136 static int nvmf_check_allowed_opts(struct nvmf_ctrl_options *opts,
1137 		unsigned int allowed_opts)
1138 {
1139 	if (opts->mask & ~allowed_opts) {
1140 		unsigned int i;
1141 
1142 		for (i = 0; i < ARRAY_SIZE(opt_tokens); i++) {
1143 			if ((opt_tokens[i].token & opts->mask) &&
1144 			    (opt_tokens[i].token & ~allowed_opts)) {
1145 				pr_warn("invalid parameter '%s'\n",
1146 					opt_tokens[i].pattern);
1147 			}
1148 		}
1149 
1150 		return -EINVAL;
1151 	}
1152 
1153 	return 0;
1154 }
1155 
1156 void nvmf_free_options(struct nvmf_ctrl_options *opts)
1157 {
1158 	nvmf_host_put(opts->host);
1159 	kfree(opts->transport);
1160 	kfree(opts->traddr);
1161 	kfree(opts->trsvcid);
1162 	kfree(opts->subsysnqn);
1163 	kfree(opts->host_traddr);
1164 	kfree(opts->host_iface);
1165 	kfree(opts->dhchap_secret);
1166 	kfree(opts->dhchap_ctrl_secret);
1167 	kfree(opts);
1168 }
1169 EXPORT_SYMBOL_GPL(nvmf_free_options);
1170 
1171 #define NVMF_REQUIRED_OPTS	(NVMF_OPT_TRANSPORT | NVMF_OPT_NQN)
1172 #define NVMF_ALLOWED_OPTS	(NVMF_OPT_QUEUE_SIZE | NVMF_OPT_NR_IO_QUEUES | \
1173 				 NVMF_OPT_KATO | NVMF_OPT_HOSTNQN | \
1174 				 NVMF_OPT_HOST_ID | NVMF_OPT_DUP_CONNECT |\
1175 				 NVMF_OPT_DISABLE_SQFLOW | NVMF_OPT_DISCOVERY |\
1176 				 NVMF_OPT_FAIL_FAST_TMO | NVMF_OPT_DHCHAP_SECRET |\
1177 				 NVMF_OPT_DHCHAP_CTRL_SECRET)
1178 
1179 static struct nvme_ctrl *
1180 nvmf_create_ctrl(struct device *dev, const char *buf)
1181 {
1182 	struct nvmf_ctrl_options *opts;
1183 	struct nvmf_transport_ops *ops;
1184 	struct nvme_ctrl *ctrl;
1185 	int ret;
1186 
1187 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1188 	if (!opts)
1189 		return ERR_PTR(-ENOMEM);
1190 
1191 	ret = nvmf_parse_options(opts, buf);
1192 	if (ret)
1193 		goto out_free_opts;
1194 
1195 
1196 	request_module("nvme-%s", opts->transport);
1197 
1198 	/*
1199 	 * Check the generic options first as we need a valid transport for
1200 	 * the lookup below.  Then clear the generic flags so that transport
1201 	 * drivers don't have to care about them.
1202 	 */
1203 	ret = nvmf_check_required_opts(opts, NVMF_REQUIRED_OPTS);
1204 	if (ret)
1205 		goto out_free_opts;
1206 	opts->mask &= ~NVMF_REQUIRED_OPTS;
1207 
1208 	down_read(&nvmf_transports_rwsem);
1209 	ops = nvmf_lookup_transport(opts);
1210 	if (!ops) {
1211 		pr_info("no handler found for transport %s.\n",
1212 			opts->transport);
1213 		ret = -EINVAL;
1214 		goto out_unlock;
1215 	}
1216 
1217 	if (!try_module_get(ops->module)) {
1218 		ret = -EBUSY;
1219 		goto out_unlock;
1220 	}
1221 	up_read(&nvmf_transports_rwsem);
1222 
1223 	ret = nvmf_check_required_opts(opts, ops->required_opts);
1224 	if (ret)
1225 		goto out_module_put;
1226 	ret = nvmf_check_allowed_opts(opts, NVMF_ALLOWED_OPTS |
1227 				ops->allowed_opts | ops->required_opts);
1228 	if (ret)
1229 		goto out_module_put;
1230 
1231 	ctrl = ops->create_ctrl(dev, opts);
1232 	if (IS_ERR(ctrl)) {
1233 		ret = PTR_ERR(ctrl);
1234 		goto out_module_put;
1235 	}
1236 
1237 	module_put(ops->module);
1238 	return ctrl;
1239 
1240 out_module_put:
1241 	module_put(ops->module);
1242 	goto out_free_opts;
1243 out_unlock:
1244 	up_read(&nvmf_transports_rwsem);
1245 out_free_opts:
1246 	nvmf_free_options(opts);
1247 	return ERR_PTR(ret);
1248 }
1249 
1250 static struct class *nvmf_class;
1251 static struct device *nvmf_device;
1252 static DEFINE_MUTEX(nvmf_dev_mutex);
1253 
1254 static ssize_t nvmf_dev_write(struct file *file, const char __user *ubuf,
1255 		size_t count, loff_t *pos)
1256 {
1257 	struct seq_file *seq_file = file->private_data;
1258 	struct nvme_ctrl *ctrl;
1259 	const char *buf;
1260 	int ret = 0;
1261 
1262 	if (count > PAGE_SIZE)
1263 		return -ENOMEM;
1264 
1265 	buf = memdup_user_nul(ubuf, count);
1266 	if (IS_ERR(buf))
1267 		return PTR_ERR(buf);
1268 
1269 	mutex_lock(&nvmf_dev_mutex);
1270 	if (seq_file->private) {
1271 		ret = -EINVAL;
1272 		goto out_unlock;
1273 	}
1274 
1275 	ctrl = nvmf_create_ctrl(nvmf_device, buf);
1276 	if (IS_ERR(ctrl)) {
1277 		ret = PTR_ERR(ctrl);
1278 		goto out_unlock;
1279 	}
1280 
1281 	seq_file->private = ctrl;
1282 
1283 out_unlock:
1284 	mutex_unlock(&nvmf_dev_mutex);
1285 	kfree(buf);
1286 	return ret ? ret : count;
1287 }
1288 
1289 static void __nvmf_concat_opt_tokens(struct seq_file *seq_file)
1290 {
1291 	const struct match_token *tok;
1292 	int idx;
1293 
1294 	/*
1295 	 * Add dummy entries for instance and cntlid to
1296 	 * signal an invalid/non-existing controller
1297 	 */
1298 	seq_puts(seq_file, "instance=-1,cntlid=-1");
1299 	for (idx = 0; idx < ARRAY_SIZE(opt_tokens); idx++) {
1300 		tok = &opt_tokens[idx];
1301 		if (tok->token == NVMF_OPT_ERR)
1302 			continue;
1303 		seq_puts(seq_file, ",");
1304 		seq_puts(seq_file, tok->pattern);
1305 	}
1306 	seq_puts(seq_file, "\n");
1307 }
1308 
1309 static int nvmf_dev_show(struct seq_file *seq_file, void *private)
1310 {
1311 	struct nvme_ctrl *ctrl;
1312 
1313 	mutex_lock(&nvmf_dev_mutex);
1314 	ctrl = seq_file->private;
1315 	if (!ctrl) {
1316 		__nvmf_concat_opt_tokens(seq_file);
1317 		goto out_unlock;
1318 	}
1319 
1320 	seq_printf(seq_file, "instance=%d,cntlid=%d\n",
1321 			ctrl->instance, ctrl->cntlid);
1322 
1323 out_unlock:
1324 	mutex_unlock(&nvmf_dev_mutex);
1325 	return 0;
1326 }
1327 
1328 static int nvmf_dev_open(struct inode *inode, struct file *file)
1329 {
1330 	/*
1331 	 * The miscdevice code initializes file->private_data, but doesn't
1332 	 * make use of it later.
1333 	 */
1334 	file->private_data = NULL;
1335 	return single_open(file, nvmf_dev_show, NULL);
1336 }
1337 
1338 static int nvmf_dev_release(struct inode *inode, struct file *file)
1339 {
1340 	struct seq_file *seq_file = file->private_data;
1341 	struct nvme_ctrl *ctrl = seq_file->private;
1342 
1343 	if (ctrl)
1344 		nvme_put_ctrl(ctrl);
1345 	return single_release(inode, file);
1346 }
1347 
1348 static const struct file_operations nvmf_dev_fops = {
1349 	.owner		= THIS_MODULE,
1350 	.write		= nvmf_dev_write,
1351 	.read		= seq_read,
1352 	.open		= nvmf_dev_open,
1353 	.release	= nvmf_dev_release,
1354 };
1355 
1356 static struct miscdevice nvmf_misc = {
1357 	.minor		= MISC_DYNAMIC_MINOR,
1358 	.name           = "nvme-fabrics",
1359 	.fops		= &nvmf_dev_fops,
1360 };
1361 
1362 static int __init nvmf_init(void)
1363 {
1364 	int ret;
1365 
1366 	nvmf_default_host = nvmf_host_default();
1367 	if (!nvmf_default_host)
1368 		return -ENOMEM;
1369 
1370 	nvmf_class = class_create("nvme-fabrics");
1371 	if (IS_ERR(nvmf_class)) {
1372 		pr_err("couldn't register class nvme-fabrics\n");
1373 		ret = PTR_ERR(nvmf_class);
1374 		goto out_free_host;
1375 	}
1376 
1377 	nvmf_device =
1378 		device_create(nvmf_class, NULL, MKDEV(0, 0), NULL, "ctl");
1379 	if (IS_ERR(nvmf_device)) {
1380 		pr_err("couldn't create nvme-fabrics device!\n");
1381 		ret = PTR_ERR(nvmf_device);
1382 		goto out_destroy_class;
1383 	}
1384 
1385 	ret = misc_register(&nvmf_misc);
1386 	if (ret) {
1387 		pr_err("couldn't register misc device: %d\n", ret);
1388 		goto out_destroy_device;
1389 	}
1390 
1391 	return 0;
1392 
1393 out_destroy_device:
1394 	device_destroy(nvmf_class, MKDEV(0, 0));
1395 out_destroy_class:
1396 	class_destroy(nvmf_class);
1397 out_free_host:
1398 	nvmf_host_put(nvmf_default_host);
1399 	return ret;
1400 }
1401 
1402 static void __exit nvmf_exit(void)
1403 {
1404 	misc_deregister(&nvmf_misc);
1405 	device_destroy(nvmf_class, MKDEV(0, 0));
1406 	class_destroy(nvmf_class);
1407 	nvmf_host_put(nvmf_default_host);
1408 
1409 	BUILD_BUG_ON(sizeof(struct nvmf_common_command) != 64);
1410 	BUILD_BUG_ON(sizeof(struct nvmf_connect_command) != 64);
1411 	BUILD_BUG_ON(sizeof(struct nvmf_property_get_command) != 64);
1412 	BUILD_BUG_ON(sizeof(struct nvmf_property_set_command) != 64);
1413 	BUILD_BUG_ON(sizeof(struct nvmf_auth_send_command) != 64);
1414 	BUILD_BUG_ON(sizeof(struct nvmf_auth_receive_command) != 64);
1415 	BUILD_BUG_ON(sizeof(struct nvmf_connect_data) != 1024);
1416 	BUILD_BUG_ON(sizeof(struct nvmf_auth_dhchap_negotiate_data) != 8);
1417 	BUILD_BUG_ON(sizeof(struct nvmf_auth_dhchap_challenge_data) != 16);
1418 	BUILD_BUG_ON(sizeof(struct nvmf_auth_dhchap_reply_data) != 16);
1419 	BUILD_BUG_ON(sizeof(struct nvmf_auth_dhchap_success1_data) != 16);
1420 	BUILD_BUG_ON(sizeof(struct nvmf_auth_dhchap_success2_data) != 16);
1421 }
1422 
1423 MODULE_LICENSE("GPL v2");
1424 
1425 module_init(nvmf_init);
1426 module_exit(nvmf_exit);
1427