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