Merge branch 'for-4.9/libnvdimm' into libnvdimm-for-next
[cascardo/linux.git] / drivers / nvme / host / fabrics.c
1 /*
2  * NVMe over Fabrics common host code.
3  * Copyright (c) 2015-2016 HGST, a Western Digital Company.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15 #include <linux/init.h>
16 #include <linux/miscdevice.h>
17 #include <linux/module.h>
18 #include <linux/mutex.h>
19 #include <linux/parser.h>
20 #include <linux/seq_file.h>
21 #include "nvme.h"
22 #include "fabrics.h"
23
24 static LIST_HEAD(nvmf_transports);
25 static DEFINE_MUTEX(nvmf_transports_mutex);
26
27 static LIST_HEAD(nvmf_hosts);
28 static DEFINE_MUTEX(nvmf_hosts_mutex);
29
30 static struct nvmf_host *nvmf_default_host;
31
32 static struct nvmf_host *__nvmf_host_find(const char *hostnqn)
33 {
34         struct nvmf_host *host;
35
36         list_for_each_entry(host, &nvmf_hosts, list) {
37                 if (!strcmp(host->nqn, hostnqn))
38                         return host;
39         }
40
41         return NULL;
42 }
43
44 static struct nvmf_host *nvmf_host_add(const char *hostnqn)
45 {
46         struct nvmf_host *host;
47
48         mutex_lock(&nvmf_hosts_mutex);
49         host = __nvmf_host_find(hostnqn);
50         if (host) {
51                 kref_get(&host->ref);
52                 goto out_unlock;
53         }
54
55         host = kmalloc(sizeof(*host), GFP_KERNEL);
56         if (!host)
57                 goto out_unlock;
58
59         kref_init(&host->ref);
60         memcpy(host->nqn, hostnqn, NVMF_NQN_SIZE);
61         uuid_be_gen(&host->id);
62
63         list_add_tail(&host->list, &nvmf_hosts);
64 out_unlock:
65         mutex_unlock(&nvmf_hosts_mutex);
66         return host;
67 }
68
69 static struct nvmf_host *nvmf_host_default(void)
70 {
71         struct nvmf_host *host;
72
73         host = kmalloc(sizeof(*host), GFP_KERNEL);
74         if (!host)
75                 return NULL;
76
77         kref_init(&host->ref);
78         uuid_be_gen(&host->id);
79         snprintf(host->nqn, NVMF_NQN_SIZE,
80                 "nqn.2014-08.org.nvmexpress:NVMf:uuid:%pUb", &host->id);
81
82         mutex_lock(&nvmf_hosts_mutex);
83         list_add_tail(&host->list, &nvmf_hosts);
84         mutex_unlock(&nvmf_hosts_mutex);
85
86         return host;
87 }
88
89 static void nvmf_host_destroy(struct kref *ref)
90 {
91         struct nvmf_host *host = container_of(ref, struct nvmf_host, ref);
92
93         mutex_lock(&nvmf_hosts_mutex);
94         list_del(&host->list);
95         mutex_unlock(&nvmf_hosts_mutex);
96
97         kfree(host);
98 }
99
100 static void nvmf_host_put(struct nvmf_host *host)
101 {
102         if (host)
103                 kref_put(&host->ref, nvmf_host_destroy);
104 }
105
106 /**
107  * nvmf_get_address() -  Get address/port
108  * @ctrl:       Host NVMe controller instance which we got the address
109  * @buf:        OUTPUT parameter that will contain the address/port
110  * @size:       buffer size
111  */
112 int nvmf_get_address(struct nvme_ctrl *ctrl, char *buf, int size)
113 {
114         return snprintf(buf, size, "traddr=%s,trsvcid=%s\n",
115                         ctrl->opts->traddr, ctrl->opts->trsvcid);
116 }
117 EXPORT_SYMBOL_GPL(nvmf_get_address);
118
119 /**
120  * nvmf_get_subsysnqn() - Get subsystem NQN
121  * @ctrl:       Host NVMe controller instance which we got the NQN
122  */
123 const char *nvmf_get_subsysnqn(struct nvme_ctrl *ctrl)
124 {
125         return ctrl->opts->subsysnqn;
126 }
127 EXPORT_SYMBOL_GPL(nvmf_get_subsysnqn);
128
129 /**
130  * nvmf_reg_read32() -  NVMe Fabrics "Property Get" API function.
131  * @ctrl:       Host NVMe controller instance maintaining the admin
132  *              queue used to submit the property read command to
133  *              the allocated NVMe controller resource on the target system.
134  * @off:        Starting offset value of the targeted property
135  *              register (see the fabrics section of the NVMe standard).
136  * @val:        OUTPUT parameter that will contain the value of
137  *              the property after a successful read.
138  *
139  * Used by the host system to retrieve a 32-bit capsule property value
140  * from an NVMe controller on the target system.
141  *
142  * ("Capsule property" is an "PCIe register concept" applied to the
143  * NVMe fabrics space.)
144  *
145  * Return:
146  *      0: successful read
147  *      > 0: NVMe error status code
148  *      < 0: Linux errno error code
149  */
150 int nvmf_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val)
151 {
152         struct nvme_command cmd;
153         struct nvme_completion cqe;
154         int ret;
155
156         memset(&cmd, 0, sizeof(cmd));
157         cmd.prop_get.opcode = nvme_fabrics_command;
158         cmd.prop_get.fctype = nvme_fabrics_type_property_get;
159         cmd.prop_get.offset = cpu_to_le32(off);
160
161         ret = __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, &cqe, NULL, 0, 0,
162                         NVME_QID_ANY, 0, 0);
163
164         if (ret >= 0)
165                 *val = le64_to_cpu(cqe.result64);
166         if (unlikely(ret != 0))
167                 dev_err(ctrl->device,
168                         "Property Get error: %d, offset %#x\n",
169                         ret > 0 ? ret & ~NVME_SC_DNR : ret, off);
170
171         return ret;
172 }
173 EXPORT_SYMBOL_GPL(nvmf_reg_read32);
174
175 /**
176  * nvmf_reg_read64() -  NVMe Fabrics "Property Get" API function.
177  * @ctrl:       Host NVMe controller instance maintaining the admin
178  *              queue used to submit the property read command to
179  *              the allocated controller resource on the target system.
180  * @off:        Starting offset value of the targeted property
181  *              register (see the fabrics section of the NVMe standard).
182  * @val:        OUTPUT parameter that will contain the value of
183  *              the property after a successful read.
184  *
185  * Used by the host system to retrieve a 64-bit capsule property value
186  * from an NVMe controller on the target system.
187  *
188  * ("Capsule property" is an "PCIe register concept" applied to the
189  * NVMe fabrics space.)
190  *
191  * Return:
192  *      0: successful read
193  *      > 0: NVMe error status code
194  *      < 0: Linux errno error code
195  */
196 int nvmf_reg_read64(struct nvme_ctrl *ctrl, u32 off, u64 *val)
197 {
198         struct nvme_command cmd;
199         struct nvme_completion cqe;
200         int ret;
201
202         memset(&cmd, 0, sizeof(cmd));
203         cmd.prop_get.opcode = nvme_fabrics_command;
204         cmd.prop_get.fctype = nvme_fabrics_type_property_get;
205         cmd.prop_get.attrib = 1;
206         cmd.prop_get.offset = cpu_to_le32(off);
207
208         ret = __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, &cqe, NULL, 0, 0,
209                         NVME_QID_ANY, 0, 0);
210
211         if (ret >= 0)
212                 *val = le64_to_cpu(cqe.result64);
213         if (unlikely(ret != 0))
214                 dev_err(ctrl->device,
215                         "Property Get error: %d, offset %#x\n",
216                         ret > 0 ? ret & ~NVME_SC_DNR : ret, off);
217         return ret;
218 }
219 EXPORT_SYMBOL_GPL(nvmf_reg_read64);
220
221 /**
222  * nvmf_reg_write32() -  NVMe Fabrics "Property Write" API function.
223  * @ctrl:       Host NVMe controller instance maintaining the admin
224  *              queue used to submit the property read command to
225  *              the allocated NVMe controller resource on the target system.
226  * @off:        Starting offset value of the targeted property
227  *              register (see the fabrics section of the NVMe standard).
228  * @val:        Input parameter that contains the value to be
229  *              written to the property.
230  *
231  * Used by the NVMe host system to write a 32-bit capsule property value
232  * to an NVMe controller on the target system.
233  *
234  * ("Capsule property" is an "PCIe register concept" applied to the
235  * NVMe fabrics space.)
236  *
237  * Return:
238  *      0: successful write
239  *      > 0: NVMe error status code
240  *      < 0: Linux errno error code
241  */
242 int nvmf_reg_write32(struct nvme_ctrl *ctrl, u32 off, u32 val)
243 {
244         struct nvme_command cmd;
245         int ret;
246
247         memset(&cmd, 0, sizeof(cmd));
248         cmd.prop_set.opcode = nvme_fabrics_command;
249         cmd.prop_set.fctype = nvme_fabrics_type_property_set;
250         cmd.prop_set.attrib = 0;
251         cmd.prop_set.offset = cpu_to_le32(off);
252         cmd.prop_set.value = cpu_to_le64(val);
253
254         ret = __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, NULL, 0, 0,
255                         NVME_QID_ANY, 0, 0);
256         if (unlikely(ret))
257                 dev_err(ctrl->device,
258                         "Property Set error: %d, offset %#x\n",
259                         ret > 0 ? ret & ~NVME_SC_DNR : ret, off);
260         return ret;
261 }
262 EXPORT_SYMBOL_GPL(nvmf_reg_write32);
263
264 /**
265  * nvmf_log_connect_error() - Error-parsing-diagnostic print
266  * out function for connect() errors.
267  *
268  * @ctrl: the specific /dev/nvmeX device that had the error.
269  *
270  * @errval: Error code to be decoded in a more human-friendly
271  *          printout.
272  *
273  * @offset: For use with the NVMe error code NVME_SC_CONNECT_INVALID_PARAM.
274  *
275  * @cmd: This is the SQE portion of a submission capsule.
276  *
277  * @data: This is the "Data" portion of a submission capsule.
278  */
279 static void nvmf_log_connect_error(struct nvme_ctrl *ctrl,
280                 int errval, int offset, struct nvme_command *cmd,
281                 struct nvmf_connect_data *data)
282 {
283         int err_sctype = errval & (~NVME_SC_DNR);
284
285         switch (err_sctype) {
286
287         case (NVME_SC_CONNECT_INVALID_PARAM):
288                 if (offset >> 16) {
289                         char *inv_data = "Connect Invalid Data Parameter";
290
291                         switch (offset & 0xffff) {
292                         case (offsetof(struct nvmf_connect_data, cntlid)):
293                                 dev_err(ctrl->device,
294                                         "%s, cntlid: %d\n",
295                                         inv_data, data->cntlid);
296                                 break;
297                         case (offsetof(struct nvmf_connect_data, hostnqn)):
298                                 dev_err(ctrl->device,
299                                         "%s, hostnqn \"%s\"\n",
300                                         inv_data, data->hostnqn);
301                                 break;
302                         case (offsetof(struct nvmf_connect_data, subsysnqn)):
303                                 dev_err(ctrl->device,
304                                         "%s, subsysnqn \"%s\"\n",
305                                         inv_data, data->subsysnqn);
306                                 break;
307                         default:
308                                 dev_err(ctrl->device,
309                                         "%s, starting byte offset: %d\n",
310                                        inv_data, offset & 0xffff);
311                                 break;
312                         }
313                 } else {
314                         char *inv_sqe = "Connect Invalid SQE Parameter";
315
316                         switch (offset) {
317                         case (offsetof(struct nvmf_connect_command, qid)):
318                                 dev_err(ctrl->device,
319                                        "%s, qid %d\n",
320                                         inv_sqe, cmd->connect.qid);
321                                 break;
322                         default:
323                                 dev_err(ctrl->device,
324                                         "%s, starting byte offset: %d\n",
325                                         inv_sqe, offset);
326                         }
327                 }
328                 break;
329         default:
330                 dev_err(ctrl->device,
331                         "Connect command failed, error wo/DNR bit: %d\n",
332                         err_sctype);
333                 break;
334         } /* switch (err_sctype) */
335 }
336
337 /**
338  * nvmf_connect_admin_queue() - NVMe Fabrics Admin Queue "Connect"
339  *                              API function.
340  * @ctrl:       Host nvme controller instance used to request
341  *              a new NVMe controller allocation on the target
342  *              system and  establish an NVMe Admin connection to
343  *              that controller.
344  *
345  * This function enables an NVMe host device to request a new allocation of
346  * an NVMe controller resource on a target system as well establish a
347  * fabrics-protocol connection of the NVMe Admin queue between the
348  * host system device and the allocated NVMe controller on the
349  * target system via a NVMe Fabrics "Connect" command.
350  *
351  * Return:
352  *      0: success
353  *      > 0: NVMe error status code
354  *      < 0: Linux errno error code
355  *
356  */
357 int nvmf_connect_admin_queue(struct nvme_ctrl *ctrl)
358 {
359         struct nvme_command cmd;
360         struct nvme_completion cqe;
361         struct nvmf_connect_data *data;
362         int ret;
363
364         memset(&cmd, 0, sizeof(cmd));
365         cmd.connect.opcode = nvme_fabrics_command;
366         cmd.connect.fctype = nvme_fabrics_type_connect;
367         cmd.connect.qid = 0;
368
369         /*
370          * fabrics spec sets a minimum of depth 32 for admin queue,
371          * so set the queue with this depth always until
372          * justification otherwise.
373          */
374         cmd.connect.sqsize = cpu_to_le16(NVMF_AQ_DEPTH - 1);
375
376         /*
377          * Set keep-alive timeout in seconds granularity (ms * 1000)
378          * and add a grace period for controller kato enforcement
379          */
380         cmd.connect.kato = ctrl->opts->discovery_nqn ? 0 :
381                 cpu_to_le32((ctrl->kato + NVME_KATO_GRACE) * 1000);
382
383         data = kzalloc(sizeof(*data), GFP_KERNEL);
384         if (!data)
385                 return -ENOMEM;
386
387         memcpy(&data->hostid, &ctrl->opts->host->id, sizeof(uuid_be));
388         data->cntlid = cpu_to_le16(0xffff);
389         strncpy(data->subsysnqn, ctrl->opts->subsysnqn, NVMF_NQN_SIZE);
390         strncpy(data->hostnqn, ctrl->opts->host->nqn, NVMF_NQN_SIZE);
391
392         ret = __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, &cqe,
393                         data, sizeof(*data), 0, NVME_QID_ANY, 1,
394                         BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
395         if (ret) {
396                 nvmf_log_connect_error(ctrl, ret, le32_to_cpu(cqe.result),
397                                        &cmd, data);
398                 goto out_free_data;
399         }
400
401         ctrl->cntlid = le16_to_cpu(cqe.result16);
402
403 out_free_data:
404         kfree(data);
405         return ret;
406 }
407 EXPORT_SYMBOL_GPL(nvmf_connect_admin_queue);
408
409 /**
410  * nvmf_connect_io_queue() - NVMe Fabrics I/O Queue "Connect"
411  *                           API function.
412  * @ctrl:       Host nvme controller instance used to establish an
413  *              NVMe I/O queue connection to the already allocated NVMe
414  *              controller on the target system.
415  * @qid:        NVMe I/O queue number for the new I/O connection between
416  *              host and target (note qid == 0 is illegal as this is
417  *              the Admin queue, per NVMe standard).
418  *
419  * This function issues a fabrics-protocol connection
420  * of a NVMe I/O queue (via NVMe Fabrics "Connect" command)
421  * between the host system device and the allocated NVMe controller
422  * on the target system.
423  *
424  * Return:
425  *      0: success
426  *      > 0: NVMe error status code
427  *      < 0: Linux errno error code
428  */
429 int nvmf_connect_io_queue(struct nvme_ctrl *ctrl, u16 qid)
430 {
431         struct nvme_command cmd;
432         struct nvmf_connect_data *data;
433         struct nvme_completion cqe;
434         int ret;
435
436         memset(&cmd, 0, sizeof(cmd));
437         cmd.connect.opcode = nvme_fabrics_command;
438         cmd.connect.fctype = nvme_fabrics_type_connect;
439         cmd.connect.qid = cpu_to_le16(qid);
440         cmd.connect.sqsize = cpu_to_le16(ctrl->sqsize);
441
442         data = kzalloc(sizeof(*data), GFP_KERNEL);
443         if (!data)
444                 return -ENOMEM;
445
446         memcpy(&data->hostid, &ctrl->opts->host->id, sizeof(uuid_be));
447         data->cntlid = cpu_to_le16(ctrl->cntlid);
448         strncpy(data->subsysnqn, ctrl->opts->subsysnqn, NVMF_NQN_SIZE);
449         strncpy(data->hostnqn, ctrl->opts->host->nqn, NVMF_NQN_SIZE);
450
451         ret = __nvme_submit_sync_cmd(ctrl->connect_q, &cmd, &cqe,
452                         data, sizeof(*data), 0, qid, 1,
453                         BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
454         if (ret) {
455                 nvmf_log_connect_error(ctrl, ret, le32_to_cpu(cqe.result),
456                                        &cmd, data);
457         }
458         kfree(data);
459         return ret;
460 }
461 EXPORT_SYMBOL_GPL(nvmf_connect_io_queue);
462
463 /**
464  * nvmf_register_transport() - NVMe Fabrics Library registration function.
465  * @ops:        Transport ops instance to be registered to the
466  *              common fabrics library.
467  *
468  * API function that registers the type of specific transport fabric
469  * being implemented to the common NVMe fabrics library. Part of
470  * the overall init sequence of starting up a fabrics driver.
471  */
472 void nvmf_register_transport(struct nvmf_transport_ops *ops)
473 {
474         mutex_lock(&nvmf_transports_mutex);
475         list_add_tail(&ops->entry, &nvmf_transports);
476         mutex_unlock(&nvmf_transports_mutex);
477 }
478 EXPORT_SYMBOL_GPL(nvmf_register_transport);
479
480 /**
481  * nvmf_unregister_transport() - NVMe Fabrics Library unregistration function.
482  * @ops:        Transport ops instance to be unregistered from the
483  *              common fabrics library.
484  *
485  * Fabrics API function that unregisters the type of specific transport
486  * fabric being implemented from the common NVMe fabrics library.
487  * Part of the overall exit sequence of unloading the implemented driver.
488  */
489 void nvmf_unregister_transport(struct nvmf_transport_ops *ops)
490 {
491         mutex_lock(&nvmf_transports_mutex);
492         list_del(&ops->entry);
493         mutex_unlock(&nvmf_transports_mutex);
494 }
495 EXPORT_SYMBOL_GPL(nvmf_unregister_transport);
496
497 static struct nvmf_transport_ops *nvmf_lookup_transport(
498                 struct nvmf_ctrl_options *opts)
499 {
500         struct nvmf_transport_ops *ops;
501
502         lockdep_assert_held(&nvmf_transports_mutex);
503
504         list_for_each_entry(ops, &nvmf_transports, entry) {
505                 if (strcmp(ops->name, opts->transport) == 0)
506                         return ops;
507         }
508
509         return NULL;
510 }
511
512 static const match_table_t opt_tokens = {
513         { NVMF_OPT_TRANSPORT,           "transport=%s"          },
514         { NVMF_OPT_TRADDR,              "traddr=%s"             },
515         { NVMF_OPT_TRSVCID,             "trsvcid=%s"            },
516         { NVMF_OPT_NQN,                 "nqn=%s"                },
517         { NVMF_OPT_QUEUE_SIZE,          "queue_size=%d"         },
518         { NVMF_OPT_NR_IO_QUEUES,        "nr_io_queues=%d"       },
519         { NVMF_OPT_RECONNECT_DELAY,     "reconnect_delay=%d"    },
520         { NVMF_OPT_KATO,                "keep_alive_tmo=%d"     },
521         { NVMF_OPT_HOSTNQN,             "hostnqn=%s"            },
522         { NVMF_OPT_ERR,                 NULL                    }
523 };
524
525 static int nvmf_parse_options(struct nvmf_ctrl_options *opts,
526                 const char *buf)
527 {
528         substring_t args[MAX_OPT_ARGS];
529         char *options, *o, *p;
530         int token, ret = 0;
531         size_t nqnlen  = 0;
532
533         /* Set defaults */
534         opts->queue_size = NVMF_DEF_QUEUE_SIZE;
535         opts->nr_io_queues = num_online_cpus();
536         opts->reconnect_delay = NVMF_DEF_RECONNECT_DELAY;
537
538         options = o = kstrdup(buf, GFP_KERNEL);
539         if (!options)
540                 return -ENOMEM;
541
542         while ((p = strsep(&o, ",\n")) != NULL) {
543                 if (!*p)
544                         continue;
545
546                 token = match_token(p, opt_tokens, args);
547                 opts->mask |= token;
548                 switch (token) {
549                 case NVMF_OPT_TRANSPORT:
550                         p = match_strdup(args);
551                         if (!p) {
552                                 ret = -ENOMEM;
553                                 goto out;
554                         }
555                         opts->transport = p;
556                         break;
557                 case NVMF_OPT_NQN:
558                         p = match_strdup(args);
559                         if (!p) {
560                                 ret = -ENOMEM;
561                                 goto out;
562                         }
563                         opts->subsysnqn = p;
564                         nqnlen = strlen(opts->subsysnqn);
565                         if (nqnlen >= NVMF_NQN_SIZE) {
566                                 pr_err("%s needs to be < %d bytes\n",
567                                 opts->subsysnqn, NVMF_NQN_SIZE);
568                                 ret = -EINVAL;
569                                 goto out;
570                         }
571                         opts->discovery_nqn =
572                                 !(strcmp(opts->subsysnqn,
573                                          NVME_DISC_SUBSYS_NAME));
574                         if (opts->discovery_nqn)
575                                 opts->nr_io_queues = 0;
576                         break;
577                 case NVMF_OPT_TRADDR:
578                         p = match_strdup(args);
579                         if (!p) {
580                                 ret = -ENOMEM;
581                                 goto out;
582                         }
583                         opts->traddr = p;
584                         break;
585                 case NVMF_OPT_TRSVCID:
586                         p = match_strdup(args);
587                         if (!p) {
588                                 ret = -ENOMEM;
589                                 goto out;
590                         }
591                         opts->trsvcid = p;
592                         break;
593                 case NVMF_OPT_QUEUE_SIZE:
594                         if (match_int(args, &token)) {
595                                 ret = -EINVAL;
596                                 goto out;
597                         }
598                         if (token < NVMF_MIN_QUEUE_SIZE ||
599                             token > NVMF_MAX_QUEUE_SIZE) {
600                                 pr_err("Invalid queue_size %d\n", token);
601                                 ret = -EINVAL;
602                                 goto out;
603                         }
604                         opts->queue_size = token;
605                         break;
606                 case NVMF_OPT_NR_IO_QUEUES:
607                         if (match_int(args, &token)) {
608                                 ret = -EINVAL;
609                                 goto out;
610                         }
611                         if (token <= 0) {
612                                 pr_err("Invalid number of IOQs %d\n", token);
613                                 ret = -EINVAL;
614                                 goto out;
615                         }
616                         opts->nr_io_queues = min_t(unsigned int,
617                                         num_online_cpus(), token);
618                         break;
619                 case NVMF_OPT_KATO:
620                         if (match_int(args, &token)) {
621                                 ret = -EINVAL;
622                                 goto out;
623                         }
624
625                         if (opts->discovery_nqn) {
626                                 pr_err("Discovery controllers cannot accept keep_alive_tmo != 0\n");
627                                 ret = -EINVAL;
628                                 goto out;
629                         }
630
631                         if (token < 0) {
632                                 pr_err("Invalid keep_alive_tmo %d\n", token);
633                                 ret = -EINVAL;
634                                 goto out;
635                         } else if (token == 0) {
636                                 /* Allowed for debug */
637                                 pr_warn("keep_alive_tmo 0 won't execute keep alives!!!\n");
638                         }
639                         opts->kato = token;
640                         break;
641                 case NVMF_OPT_HOSTNQN:
642                         if (opts->host) {
643                                 pr_err("hostnqn already user-assigned: %s\n",
644                                        opts->host->nqn);
645                                 ret = -EADDRINUSE;
646                                 goto out;
647                         }
648                         p = match_strdup(args);
649                         if (!p) {
650                                 ret = -ENOMEM;
651                                 goto out;
652                         }
653                         nqnlen = strlen(p);
654                         if (nqnlen >= NVMF_NQN_SIZE) {
655                                 pr_err("%s needs to be < %d bytes\n",
656                                         p, NVMF_NQN_SIZE);
657                                 ret = -EINVAL;
658                                 goto out;
659                         }
660                         opts->host = nvmf_host_add(p);
661                         if (!opts->host) {
662                                 ret = -ENOMEM;
663                                 goto out;
664                         }
665                         break;
666                 case NVMF_OPT_RECONNECT_DELAY:
667                         if (match_int(args, &token)) {
668                                 ret = -EINVAL;
669                                 goto out;
670                         }
671                         if (token <= 0) {
672                                 pr_err("Invalid reconnect_delay %d\n", token);
673                                 ret = -EINVAL;
674                                 goto out;
675                         }
676                         opts->reconnect_delay = token;
677                         break;
678                 default:
679                         pr_warn("unknown parameter or missing value '%s' in ctrl creation request\n",
680                                 p);
681                         ret = -EINVAL;
682                         goto out;
683                 }
684         }
685
686         if (!opts->host) {
687                 kref_get(&nvmf_default_host->ref);
688                 opts->host = nvmf_default_host;
689         }
690
691 out:
692         if (!opts->discovery_nqn && !opts->kato)
693                 opts->kato = NVME_DEFAULT_KATO;
694         kfree(options);
695         return ret;
696 }
697
698 static int nvmf_check_required_opts(struct nvmf_ctrl_options *opts,
699                 unsigned int required_opts)
700 {
701         if ((opts->mask & required_opts) != required_opts) {
702                 int i;
703
704                 for (i = 0; i < ARRAY_SIZE(opt_tokens); i++) {
705                         if ((opt_tokens[i].token & required_opts) &&
706                             !(opt_tokens[i].token & opts->mask)) {
707                                 pr_warn("missing parameter '%s'\n",
708                                         opt_tokens[i].pattern);
709                         }
710                 }
711
712                 return -EINVAL;
713         }
714
715         return 0;
716 }
717
718 static int nvmf_check_allowed_opts(struct nvmf_ctrl_options *opts,
719                 unsigned int allowed_opts)
720 {
721         if (opts->mask & ~allowed_opts) {
722                 int i;
723
724                 for (i = 0; i < ARRAY_SIZE(opt_tokens); i++) {
725                         if (opt_tokens[i].token & ~allowed_opts) {
726                                 pr_warn("invalid parameter '%s'\n",
727                                         opt_tokens[i].pattern);
728                         }
729                 }
730
731                 return -EINVAL;
732         }
733
734         return 0;
735 }
736
737 void nvmf_free_options(struct nvmf_ctrl_options *opts)
738 {
739         nvmf_host_put(opts->host);
740         kfree(opts->transport);
741         kfree(opts->traddr);
742         kfree(opts->trsvcid);
743         kfree(opts->subsysnqn);
744         kfree(opts);
745 }
746 EXPORT_SYMBOL_GPL(nvmf_free_options);
747
748 #define NVMF_REQUIRED_OPTS      (NVMF_OPT_TRANSPORT | NVMF_OPT_NQN)
749 #define NVMF_ALLOWED_OPTS       (NVMF_OPT_QUEUE_SIZE | NVMF_OPT_NR_IO_QUEUES | \
750                                  NVMF_OPT_KATO | NVMF_OPT_HOSTNQN)
751
752 static struct nvme_ctrl *
753 nvmf_create_ctrl(struct device *dev, const char *buf, size_t count)
754 {
755         struct nvmf_ctrl_options *opts;
756         struct nvmf_transport_ops *ops;
757         struct nvme_ctrl *ctrl;
758         int ret;
759
760         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
761         if (!opts)
762                 return ERR_PTR(-ENOMEM);
763
764         ret = nvmf_parse_options(opts, buf);
765         if (ret)
766                 goto out_free_opts;
767
768         /*
769          * Check the generic options first as we need a valid transport for
770          * the lookup below.  Then clear the generic flags so that transport
771          * drivers don't have to care about them.
772          */
773         ret = nvmf_check_required_opts(opts, NVMF_REQUIRED_OPTS);
774         if (ret)
775                 goto out_free_opts;
776         opts->mask &= ~NVMF_REQUIRED_OPTS;
777
778         mutex_lock(&nvmf_transports_mutex);
779         ops = nvmf_lookup_transport(opts);
780         if (!ops) {
781                 pr_info("no handler found for transport %s.\n",
782                         opts->transport);
783                 ret = -EINVAL;
784                 goto out_unlock;
785         }
786
787         ret = nvmf_check_required_opts(opts, ops->required_opts);
788         if (ret)
789                 goto out_unlock;
790         ret = nvmf_check_allowed_opts(opts, NVMF_ALLOWED_OPTS |
791                                 ops->allowed_opts | ops->required_opts);
792         if (ret)
793                 goto out_unlock;
794
795         ctrl = ops->create_ctrl(dev, opts);
796         if (IS_ERR(ctrl)) {
797                 ret = PTR_ERR(ctrl);
798                 goto out_unlock;
799         }
800
801         mutex_unlock(&nvmf_transports_mutex);
802         return ctrl;
803
804 out_unlock:
805         mutex_unlock(&nvmf_transports_mutex);
806 out_free_opts:
807         nvmf_host_put(opts->host);
808         kfree(opts);
809         return ERR_PTR(ret);
810 }
811
812 static struct class *nvmf_class;
813 static struct device *nvmf_device;
814 static DEFINE_MUTEX(nvmf_dev_mutex);
815
816 static ssize_t nvmf_dev_write(struct file *file, const char __user *ubuf,
817                 size_t count, loff_t *pos)
818 {
819         struct seq_file *seq_file = file->private_data;
820         struct nvme_ctrl *ctrl;
821         const char *buf;
822         int ret = 0;
823
824         if (count > PAGE_SIZE)
825                 return -ENOMEM;
826
827         buf = memdup_user_nul(ubuf, count);
828         if (IS_ERR(buf))
829                 return PTR_ERR(buf);
830
831         mutex_lock(&nvmf_dev_mutex);
832         if (seq_file->private) {
833                 ret = -EINVAL;
834                 goto out_unlock;
835         }
836
837         ctrl = nvmf_create_ctrl(nvmf_device, buf, count);
838         if (IS_ERR(ctrl)) {
839                 ret = PTR_ERR(ctrl);
840                 goto out_unlock;
841         }
842
843         seq_file->private = ctrl;
844
845 out_unlock:
846         mutex_unlock(&nvmf_dev_mutex);
847         kfree(buf);
848         return ret ? ret : count;
849 }
850
851 static int nvmf_dev_show(struct seq_file *seq_file, void *private)
852 {
853         struct nvme_ctrl *ctrl;
854         int ret = 0;
855
856         mutex_lock(&nvmf_dev_mutex);
857         ctrl = seq_file->private;
858         if (!ctrl) {
859                 ret = -EINVAL;
860                 goto out_unlock;
861         }
862
863         seq_printf(seq_file, "instance=%d,cntlid=%d\n",
864                         ctrl->instance, ctrl->cntlid);
865
866 out_unlock:
867         mutex_unlock(&nvmf_dev_mutex);
868         return ret;
869 }
870
871 static int nvmf_dev_open(struct inode *inode, struct file *file)
872 {
873         /*
874          * The miscdevice code initializes file->private_data, but doesn't
875          * make use of it later.
876          */
877         file->private_data = NULL;
878         return single_open(file, nvmf_dev_show, NULL);
879 }
880
881 static int nvmf_dev_release(struct inode *inode, struct file *file)
882 {
883         struct seq_file *seq_file = file->private_data;
884         struct nvme_ctrl *ctrl = seq_file->private;
885
886         if (ctrl)
887                 nvme_put_ctrl(ctrl);
888         return single_release(inode, file);
889 }
890
891 static const struct file_operations nvmf_dev_fops = {
892         .owner          = THIS_MODULE,
893         .write          = nvmf_dev_write,
894         .read           = seq_read,
895         .open           = nvmf_dev_open,
896         .release        = nvmf_dev_release,
897 };
898
899 static struct miscdevice nvmf_misc = {
900         .minor          = MISC_DYNAMIC_MINOR,
901         .name           = "nvme-fabrics",
902         .fops           = &nvmf_dev_fops,
903 };
904
905 static int __init nvmf_init(void)
906 {
907         int ret;
908
909         nvmf_default_host = nvmf_host_default();
910         if (!nvmf_default_host)
911                 return -ENOMEM;
912
913         nvmf_class = class_create(THIS_MODULE, "nvme-fabrics");
914         if (IS_ERR(nvmf_class)) {
915                 pr_err("couldn't register class nvme-fabrics\n");
916                 ret = PTR_ERR(nvmf_class);
917                 goto out_free_host;
918         }
919
920         nvmf_device =
921                 device_create(nvmf_class, NULL, MKDEV(0, 0), NULL, "ctl");
922         if (IS_ERR(nvmf_device)) {
923                 pr_err("couldn't create nvme-fabris device!\n");
924                 ret = PTR_ERR(nvmf_device);
925                 goto out_destroy_class;
926         }
927
928         ret = misc_register(&nvmf_misc);
929         if (ret) {
930                 pr_err("couldn't register misc device: %d\n", ret);
931                 goto out_destroy_device;
932         }
933
934         return 0;
935
936 out_destroy_device:
937         device_destroy(nvmf_class, MKDEV(0, 0));
938 out_destroy_class:
939         class_destroy(nvmf_class);
940 out_free_host:
941         nvmf_host_put(nvmf_default_host);
942         return ret;
943 }
944
945 static void __exit nvmf_exit(void)
946 {
947         misc_deregister(&nvmf_misc);
948         device_destroy(nvmf_class, MKDEV(0, 0));
949         class_destroy(nvmf_class);
950         nvmf_host_put(nvmf_default_host);
951
952         BUILD_BUG_ON(sizeof(struct nvmf_connect_command) != 64);
953         BUILD_BUG_ON(sizeof(struct nvmf_property_get_command) != 64);
954         BUILD_BUG_ON(sizeof(struct nvmf_property_set_command) != 64);
955         BUILD_BUG_ON(sizeof(struct nvmf_connect_data) != 1024);
956 }
957
958 MODULE_LICENSE("GPL v2");
959
960 module_init(nvmf_init);
961 module_exit(nvmf_exit);