nvme-fabrics: allow user passing header digest
[linux-2.6-microblaze.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 DECLARE_RWSEM(nvmf_transports_rwsem);
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         strlcpy(host->nqn, hostnqn, NVMF_NQN_SIZE);
61
62         list_add_tail(&host->list, &nvmf_hosts);
63 out_unlock:
64         mutex_unlock(&nvmf_hosts_mutex);
65         return host;
66 }
67
68 static struct nvmf_host *nvmf_host_default(void)
69 {
70         struct nvmf_host *host;
71
72         host = kmalloc(sizeof(*host), GFP_KERNEL);
73         if (!host)
74                 return NULL;
75
76         kref_init(&host->ref);
77         uuid_gen(&host->id);
78         snprintf(host->nqn, NVMF_NQN_SIZE,
79                 "nqn.2014-08.org.nvmexpress:uuid:%pUb", &host->id);
80
81         mutex_lock(&nvmf_hosts_mutex);
82         list_add_tail(&host->list, &nvmf_hosts);
83         mutex_unlock(&nvmf_hosts_mutex);
84
85         return host;
86 }
87
88 static void nvmf_host_destroy(struct kref *ref)
89 {
90         struct nvmf_host *host = container_of(ref, struct nvmf_host, ref);
91
92         mutex_lock(&nvmf_hosts_mutex);
93         list_del(&host->list);
94         mutex_unlock(&nvmf_hosts_mutex);
95
96         kfree(host);
97 }
98
99 static void nvmf_host_put(struct nvmf_host *host)
100 {
101         if (host)
102                 kref_put(&host->ref, nvmf_host_destroy);
103 }
104
105 /**
106  * nvmf_get_address() -  Get address/port
107  * @ctrl:       Host NVMe controller instance which we got the address
108  * @buf:        OUTPUT parameter that will contain the address/port
109  * @size:       buffer size
110  */
111 int nvmf_get_address(struct nvme_ctrl *ctrl, char *buf, int size)
112 {
113         int len = 0;
114
115         if (ctrl->opts->mask & NVMF_OPT_TRADDR)
116                 len += snprintf(buf, size, "traddr=%s", ctrl->opts->traddr);
117         if (ctrl->opts->mask & NVMF_OPT_TRSVCID)
118                 len += snprintf(buf + len, size - len, "%strsvcid=%s",
119                                 (len) ? "," : "", ctrl->opts->trsvcid);
120         if (ctrl->opts->mask & NVMF_OPT_HOST_TRADDR)
121                 len += snprintf(buf + len, size - len, "%shost_traddr=%s",
122                                 (len) ? "," : "", ctrl->opts->host_traddr);
123         len += snprintf(buf + len, size - len, "\n");
124
125         return len;
126 }
127 EXPORT_SYMBOL_GPL(nvmf_get_address);
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         union nvme_result res;
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, &res, NULL, 0, 0,
162                         NVME_QID_ANY, 0, 0);
163
164         if (ret >= 0)
165                 *val = le64_to_cpu(res.u64);
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         union nvme_result res;
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, &res, NULL, 0, 0,
209                         NVME_QID_ANY, 0, 0);
210
211         if (ret >= 0)
212                 *val = le64_to_cpu(res.u64);
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
330         case NVME_SC_CONNECT_INVALID_HOST:
331                 dev_err(ctrl->device,
332                         "Connect for subsystem %s is not allowed, hostnqn: %s\n",
333                         data->subsysnqn, data->hostnqn);
334                 break;
335
336         case NVME_SC_CONNECT_CTRL_BUSY:
337                 dev_err(ctrl->device,
338                         "Connect command failed: controller is busy or not available\n");
339                 break;
340
341         case NVME_SC_CONNECT_FORMAT:
342                 dev_err(ctrl->device,
343                         "Connect incompatible format: %d",
344                         cmd->connect.recfmt);
345                 break;
346
347         default:
348                 dev_err(ctrl->device,
349                         "Connect command failed, error wo/DNR bit: %d\n",
350                         err_sctype);
351                 break;
352         } /* switch (err_sctype) */
353 }
354
355 /**
356  * nvmf_connect_admin_queue() - NVMe Fabrics Admin Queue "Connect"
357  *                              API function.
358  * @ctrl:       Host nvme controller instance used to request
359  *              a new NVMe controller allocation on the target
360  *              system and  establish an NVMe Admin connection to
361  *              that controller.
362  *
363  * This function enables an NVMe host device to request a new allocation of
364  * an NVMe controller resource on a target system as well establish a
365  * fabrics-protocol connection of the NVMe Admin queue between the
366  * host system device and the allocated NVMe controller on the
367  * target system via a NVMe Fabrics "Connect" command.
368  *
369  * Return:
370  *      0: success
371  *      > 0: NVMe error status code
372  *      < 0: Linux errno error code
373  *
374  */
375 int nvmf_connect_admin_queue(struct nvme_ctrl *ctrl)
376 {
377         struct nvme_command cmd;
378         union nvme_result res;
379         struct nvmf_connect_data *data;
380         int ret;
381
382         memset(&cmd, 0, sizeof(cmd));
383         cmd.connect.opcode = nvme_fabrics_command;
384         cmd.connect.fctype = nvme_fabrics_type_connect;
385         cmd.connect.qid = 0;
386         cmd.connect.sqsize = cpu_to_le16(NVME_AQ_DEPTH - 1);
387
388         /*
389          * Set keep-alive timeout in seconds granularity (ms * 1000)
390          * and add a grace period for controller kato enforcement
391          */
392         cmd.connect.kato = ctrl->opts->discovery_nqn ? 0 :
393                 cpu_to_le32((ctrl->kato + NVME_KATO_GRACE) * 1000);
394
395         if (ctrl->opts->disable_sqflow)
396                 cmd.connect.cattr |= NVME_CONNECT_DISABLE_SQFLOW;
397
398         data = kzalloc(sizeof(*data), GFP_KERNEL);
399         if (!data)
400                 return -ENOMEM;
401
402         uuid_copy(&data->hostid, &ctrl->opts->host->id);
403         data->cntlid = cpu_to_le16(0xffff);
404         strncpy(data->subsysnqn, ctrl->opts->subsysnqn, NVMF_NQN_SIZE);
405         strncpy(data->hostnqn, ctrl->opts->host->nqn, NVMF_NQN_SIZE);
406
407         ret = __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, &res,
408                         data, sizeof(*data), 0, NVME_QID_ANY, 1,
409                         BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
410         if (ret) {
411                 nvmf_log_connect_error(ctrl, ret, le32_to_cpu(res.u32),
412                                        &cmd, data);
413                 goto out_free_data;
414         }
415
416         ctrl->cntlid = le16_to_cpu(res.u16);
417
418 out_free_data:
419         kfree(data);
420         return ret;
421 }
422 EXPORT_SYMBOL_GPL(nvmf_connect_admin_queue);
423
424 /**
425  * nvmf_connect_io_queue() - NVMe Fabrics I/O Queue "Connect"
426  *                           API function.
427  * @ctrl:       Host nvme controller instance used to establish an
428  *              NVMe I/O queue connection to the already allocated NVMe
429  *              controller on the target system.
430  * @qid:        NVMe I/O queue number for the new I/O connection between
431  *              host and target (note qid == 0 is illegal as this is
432  *              the Admin queue, per NVMe standard).
433  *
434  * This function issues a fabrics-protocol connection
435  * of a NVMe I/O queue (via NVMe Fabrics "Connect" command)
436  * between the host system device and the allocated NVMe controller
437  * on the target system.
438  *
439  * Return:
440  *      0: success
441  *      > 0: NVMe error status code
442  *      < 0: Linux errno error code
443  */
444 int nvmf_connect_io_queue(struct nvme_ctrl *ctrl, u16 qid)
445 {
446         struct nvme_command cmd;
447         struct nvmf_connect_data *data;
448         union nvme_result res;
449         int ret;
450
451         memset(&cmd, 0, sizeof(cmd));
452         cmd.connect.opcode = nvme_fabrics_command;
453         cmd.connect.fctype = nvme_fabrics_type_connect;
454         cmd.connect.qid = cpu_to_le16(qid);
455         cmd.connect.sqsize = cpu_to_le16(ctrl->sqsize);
456
457         if (ctrl->opts->disable_sqflow)
458                 cmd.connect.cattr |= NVME_CONNECT_DISABLE_SQFLOW;
459
460         data = kzalloc(sizeof(*data), GFP_KERNEL);
461         if (!data)
462                 return -ENOMEM;
463
464         uuid_copy(&data->hostid, &ctrl->opts->host->id);
465         data->cntlid = cpu_to_le16(ctrl->cntlid);
466         strncpy(data->subsysnqn, ctrl->opts->subsysnqn, NVMF_NQN_SIZE);
467         strncpy(data->hostnqn, ctrl->opts->host->nqn, NVMF_NQN_SIZE);
468
469         ret = __nvme_submit_sync_cmd(ctrl->connect_q, &cmd, &res,
470                         data, sizeof(*data), 0, qid, 1,
471                         BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
472         if (ret) {
473                 nvmf_log_connect_error(ctrl, ret, le32_to_cpu(res.u32),
474                                        &cmd, data);
475         }
476         kfree(data);
477         return ret;
478 }
479 EXPORT_SYMBOL_GPL(nvmf_connect_io_queue);
480
481 bool nvmf_should_reconnect(struct nvme_ctrl *ctrl)
482 {
483         if (ctrl->opts->max_reconnects == -1 ||
484             ctrl->nr_reconnects < ctrl->opts->max_reconnects)
485                 return true;
486
487         return false;
488 }
489 EXPORT_SYMBOL_GPL(nvmf_should_reconnect);
490
491 /**
492  * nvmf_register_transport() - NVMe Fabrics Library registration function.
493  * @ops:        Transport ops instance to be registered to the
494  *              common fabrics library.
495  *
496  * API function that registers the type of specific transport fabric
497  * being implemented to the common NVMe fabrics library. Part of
498  * the overall init sequence of starting up a fabrics driver.
499  */
500 int nvmf_register_transport(struct nvmf_transport_ops *ops)
501 {
502         if (!ops->create_ctrl)
503                 return -EINVAL;
504
505         down_write(&nvmf_transports_rwsem);
506         list_add_tail(&ops->entry, &nvmf_transports);
507         up_write(&nvmf_transports_rwsem);
508
509         return 0;
510 }
511 EXPORT_SYMBOL_GPL(nvmf_register_transport);
512
513 /**
514  * nvmf_unregister_transport() - NVMe Fabrics Library unregistration function.
515  * @ops:        Transport ops instance to be unregistered from the
516  *              common fabrics library.
517  *
518  * Fabrics API function that unregisters the type of specific transport
519  * fabric being implemented from the common NVMe fabrics library.
520  * Part of the overall exit sequence of unloading the implemented driver.
521  */
522 void nvmf_unregister_transport(struct nvmf_transport_ops *ops)
523 {
524         down_write(&nvmf_transports_rwsem);
525         list_del(&ops->entry);
526         up_write(&nvmf_transports_rwsem);
527 }
528 EXPORT_SYMBOL_GPL(nvmf_unregister_transport);
529
530 static struct nvmf_transport_ops *nvmf_lookup_transport(
531                 struct nvmf_ctrl_options *opts)
532 {
533         struct nvmf_transport_ops *ops;
534
535         lockdep_assert_held(&nvmf_transports_rwsem);
536
537         list_for_each_entry(ops, &nvmf_transports, entry) {
538                 if (strcmp(ops->name, opts->transport) == 0)
539                         return ops;
540         }
541
542         return NULL;
543 }
544
545 /*
546  * For something we're not in a state to send to the device the default action
547  * is to busy it and retry it after the controller state is recovered.  However,
548  * if the controller is deleting or if anything is marked for failfast or
549  * nvme multipath it is immediately failed.
550  *
551  * Note: commands used to initialize the controller will be marked for failfast.
552  * Note: nvme cli/ioctl commands are marked for failfast.
553  */
554 blk_status_t nvmf_fail_nonready_command(struct nvme_ctrl *ctrl,
555                 struct request *rq)
556 {
557         if (ctrl->state != NVME_CTRL_DELETING &&
558             ctrl->state != NVME_CTRL_DEAD &&
559             !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH))
560                 return BLK_STS_RESOURCE;
561
562         nvme_req(rq)->status = NVME_SC_HOST_PATH_ERROR;
563         blk_mq_start_request(rq);
564         nvme_complete_rq(rq);
565         return BLK_STS_OK;
566 }
567 EXPORT_SYMBOL_GPL(nvmf_fail_nonready_command);
568
569 bool __nvmf_check_ready(struct nvme_ctrl *ctrl, struct request *rq,
570                 bool queue_live)
571 {
572         struct nvme_request *req = nvme_req(rq);
573
574         /*
575          * If we are in some state of setup or teardown only allow
576          * internally generated commands.
577          */
578         if (!blk_rq_is_passthrough(rq) || (req->flags & NVME_REQ_USERCMD))
579                 return false;
580
581         /*
582          * Only allow commands on a live queue, except for the connect command,
583          * which is require to set the queue live in the appropinquate states.
584          */
585         switch (ctrl->state) {
586         case NVME_CTRL_NEW:
587         case NVME_CTRL_CONNECTING:
588                 if (req->cmd->common.opcode == nvme_fabrics_command &&
589                     req->cmd->fabrics.fctype == nvme_fabrics_type_connect)
590                         return true;
591                 break;
592         default:
593                 break;
594         case NVME_CTRL_DEAD:
595                 return false;
596         }
597
598         return queue_live;
599 }
600 EXPORT_SYMBOL_GPL(__nvmf_check_ready);
601
602 static const match_table_t opt_tokens = {
603         { NVMF_OPT_TRANSPORT,           "transport=%s"          },
604         { NVMF_OPT_TRADDR,              "traddr=%s"             },
605         { NVMF_OPT_TRSVCID,             "trsvcid=%s"            },
606         { NVMF_OPT_NQN,                 "nqn=%s"                },
607         { NVMF_OPT_QUEUE_SIZE,          "queue_size=%d"         },
608         { NVMF_OPT_NR_IO_QUEUES,        "nr_io_queues=%d"       },
609         { NVMF_OPT_RECONNECT_DELAY,     "reconnect_delay=%d"    },
610         { NVMF_OPT_CTRL_LOSS_TMO,       "ctrl_loss_tmo=%d"      },
611         { NVMF_OPT_KATO,                "keep_alive_tmo=%d"     },
612         { NVMF_OPT_HOSTNQN,             "hostnqn=%s"            },
613         { NVMF_OPT_HOST_TRADDR,         "host_traddr=%s"        },
614         { NVMF_OPT_HOST_ID,             "hostid=%s"             },
615         { NVMF_OPT_DUP_CONNECT,         "duplicate_connect"     },
616         { NVMF_OPT_DISABLE_SQFLOW,      "disable_sqflow"        },
617         { NVMF_OPT_HDR_DIGEST,          "hdr_digest"            },
618         { NVMF_OPT_ERR,                 NULL                    }
619 };
620
621 static int nvmf_parse_options(struct nvmf_ctrl_options *opts,
622                 const char *buf)
623 {
624         substring_t args[MAX_OPT_ARGS];
625         char *options, *o, *p;
626         int token, ret = 0;
627         size_t nqnlen  = 0;
628         int ctrl_loss_tmo = NVMF_DEF_CTRL_LOSS_TMO;
629         uuid_t hostid;
630
631         /* Set defaults */
632         opts->queue_size = NVMF_DEF_QUEUE_SIZE;
633         opts->nr_io_queues = num_online_cpus();
634         opts->reconnect_delay = NVMF_DEF_RECONNECT_DELAY;
635         opts->kato = NVME_DEFAULT_KATO;
636         opts->duplicate_connect = false;
637         opts->hdr_digest = false;
638
639         options = o = kstrdup(buf, GFP_KERNEL);
640         if (!options)
641                 return -ENOMEM;
642
643         uuid_gen(&hostid);
644
645         while ((p = strsep(&o, ",\n")) != NULL) {
646                 if (!*p)
647                         continue;
648
649                 token = match_token(p, opt_tokens, args);
650                 opts->mask |= token;
651                 switch (token) {
652                 case NVMF_OPT_TRANSPORT:
653                         p = match_strdup(args);
654                         if (!p) {
655                                 ret = -ENOMEM;
656                                 goto out;
657                         }
658                         kfree(opts->transport);
659                         opts->transport = p;
660                         break;
661                 case NVMF_OPT_NQN:
662                         p = match_strdup(args);
663                         if (!p) {
664                                 ret = -ENOMEM;
665                                 goto out;
666                         }
667                         kfree(opts->subsysnqn);
668                         opts->subsysnqn = p;
669                         nqnlen = strlen(opts->subsysnqn);
670                         if (nqnlen >= NVMF_NQN_SIZE) {
671                                 pr_err("%s needs to be < %d bytes\n",
672                                         opts->subsysnqn, NVMF_NQN_SIZE);
673                                 ret = -EINVAL;
674                                 goto out;
675                         }
676                         opts->discovery_nqn =
677                                 !(strcmp(opts->subsysnqn,
678                                          NVME_DISC_SUBSYS_NAME));
679                         break;
680                 case NVMF_OPT_TRADDR:
681                         p = match_strdup(args);
682                         if (!p) {
683                                 ret = -ENOMEM;
684                                 goto out;
685                         }
686                         kfree(opts->traddr);
687                         opts->traddr = p;
688                         break;
689                 case NVMF_OPT_TRSVCID:
690                         p = match_strdup(args);
691                         if (!p) {
692                                 ret = -ENOMEM;
693                                 goto out;
694                         }
695                         kfree(opts->trsvcid);
696                         opts->trsvcid = p;
697                         break;
698                 case NVMF_OPT_QUEUE_SIZE:
699                         if (match_int(args, &token)) {
700                                 ret = -EINVAL;
701                                 goto out;
702                         }
703                         if (token < NVMF_MIN_QUEUE_SIZE ||
704                             token > NVMF_MAX_QUEUE_SIZE) {
705                                 pr_err("Invalid queue_size %d\n", token);
706                                 ret = -EINVAL;
707                                 goto out;
708                         }
709                         opts->queue_size = token;
710                         break;
711                 case NVMF_OPT_NR_IO_QUEUES:
712                         if (match_int(args, &token)) {
713                                 ret = -EINVAL;
714                                 goto out;
715                         }
716                         if (token <= 0) {
717                                 pr_err("Invalid number of IOQs %d\n", token);
718                                 ret = -EINVAL;
719                                 goto out;
720                         }
721                         if (opts->discovery_nqn) {
722                                 pr_debug("Ignoring nr_io_queues value for discovery controller\n");
723                                 break;
724                         }
725
726                         opts->nr_io_queues = min_t(unsigned int,
727                                         num_online_cpus(), token);
728                         break;
729                 case NVMF_OPT_KATO:
730                         if (match_int(args, &token)) {
731                                 ret = -EINVAL;
732                                 goto out;
733                         }
734
735                         if (token < 0) {
736                                 pr_err("Invalid keep_alive_tmo %d\n", token);
737                                 ret = -EINVAL;
738                                 goto out;
739                         } else if (token == 0 && !opts->discovery_nqn) {
740                                 /* Allowed for debug */
741                                 pr_warn("keep_alive_tmo 0 won't execute keep alives!!!\n");
742                         }
743                         opts->kato = token;
744
745                         if (opts->discovery_nqn && opts->kato) {
746                                 pr_err("Discovery controllers cannot accept KATO != 0\n");
747                                 ret = -EINVAL;
748                                 goto out;
749                         }
750
751                         break;
752                 case NVMF_OPT_CTRL_LOSS_TMO:
753                         if (match_int(args, &token)) {
754                                 ret = -EINVAL;
755                                 goto out;
756                         }
757
758                         if (token < 0)
759                                 pr_warn("ctrl_loss_tmo < 0 will reconnect forever\n");
760                         ctrl_loss_tmo = token;
761                         break;
762                 case NVMF_OPT_HOSTNQN:
763                         if (opts->host) {
764                                 pr_err("hostnqn already user-assigned: %s\n",
765                                        opts->host->nqn);
766                                 ret = -EADDRINUSE;
767                                 goto out;
768                         }
769                         p = match_strdup(args);
770                         if (!p) {
771                                 ret = -ENOMEM;
772                                 goto out;
773                         }
774                         nqnlen = strlen(p);
775                         if (nqnlen >= NVMF_NQN_SIZE) {
776                                 pr_err("%s needs to be < %d bytes\n",
777                                         p, NVMF_NQN_SIZE);
778                                 kfree(p);
779                                 ret = -EINVAL;
780                                 goto out;
781                         }
782                         nvmf_host_put(opts->host);
783                         opts->host = nvmf_host_add(p);
784                         kfree(p);
785                         if (!opts->host) {
786                                 ret = -ENOMEM;
787                                 goto out;
788                         }
789                         break;
790                 case NVMF_OPT_RECONNECT_DELAY:
791                         if (match_int(args, &token)) {
792                                 ret = -EINVAL;
793                                 goto out;
794                         }
795                         if (token <= 0) {
796                                 pr_err("Invalid reconnect_delay %d\n", token);
797                                 ret = -EINVAL;
798                                 goto out;
799                         }
800                         opts->reconnect_delay = token;
801                         break;
802                 case NVMF_OPT_HOST_TRADDR:
803                         p = match_strdup(args);
804                         if (!p) {
805                                 ret = -ENOMEM;
806                                 goto out;
807                         }
808                         kfree(opts->host_traddr);
809                         opts->host_traddr = p;
810                         break;
811                 case NVMF_OPT_HOST_ID:
812                         p = match_strdup(args);
813                         if (!p) {
814                                 ret = -ENOMEM;
815                                 goto out;
816                         }
817                         ret = uuid_parse(p, &hostid);
818                         if (ret) {
819                                 pr_err("Invalid hostid %s\n", p);
820                                 ret = -EINVAL;
821                                 kfree(p);
822                                 goto out;
823                         }
824                         kfree(p);
825                         break;
826                 case NVMF_OPT_DUP_CONNECT:
827                         opts->duplicate_connect = true;
828                         break;
829                 case NVMF_OPT_DISABLE_SQFLOW:
830                         opts->disable_sqflow = true;
831                         break;
832                 case NVMF_OPT_HDR_DIGEST:
833                         opts->hdr_digest = true;
834                         break;
835                 default:
836                         pr_warn("unknown parameter or missing value '%s' in ctrl creation request\n",
837                                 p);
838                         ret = -EINVAL;
839                         goto out;
840                 }
841         }
842
843         if (opts->discovery_nqn) {
844                 opts->kato = 0;
845                 opts->nr_io_queues = 0;
846                 opts->duplicate_connect = true;
847         }
848         if (ctrl_loss_tmo < 0)
849                 opts->max_reconnects = -1;
850         else
851                 opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo,
852                                                 opts->reconnect_delay);
853
854         if (!opts->host) {
855                 kref_get(&nvmf_default_host->ref);
856                 opts->host = nvmf_default_host;
857         }
858
859         uuid_copy(&opts->host->id, &hostid);
860
861 out:
862         kfree(options);
863         return ret;
864 }
865
866 static int nvmf_check_required_opts(struct nvmf_ctrl_options *opts,
867                 unsigned int required_opts)
868 {
869         if ((opts->mask & required_opts) != required_opts) {
870                 int i;
871
872                 for (i = 0; i < ARRAY_SIZE(opt_tokens); i++) {
873                         if ((opt_tokens[i].token & required_opts) &&
874                             !(opt_tokens[i].token & opts->mask)) {
875                                 pr_warn("missing parameter '%s'\n",
876                                         opt_tokens[i].pattern);
877                         }
878                 }
879
880                 return -EINVAL;
881         }
882
883         return 0;
884 }
885
886 bool nvmf_ip_options_match(struct nvme_ctrl *ctrl,
887                 struct nvmf_ctrl_options *opts)
888 {
889         if (!nvmf_ctlr_matches_baseopts(ctrl, opts) ||
890             strcmp(opts->traddr, ctrl->opts->traddr) ||
891             strcmp(opts->trsvcid, ctrl->opts->trsvcid))
892                 return false;
893
894         /*
895          * Checking the local address is rough. In most cases, none is specified
896          * and the host port is selected by the stack.
897          *
898          * Assume no match if:
899          * -  local address is specified and address is not the same
900          * -  local address is not specified but remote is, or vice versa
901          *    (admin using specific host_traddr when it matters).
902          */
903         if ((opts->mask & NVMF_OPT_HOST_TRADDR) &&
904             (ctrl->opts->mask & NVMF_OPT_HOST_TRADDR)) {
905                 if (strcmp(opts->host_traddr, ctrl->opts->host_traddr))
906                         return false;
907         } else if ((opts->mask & NVMF_OPT_HOST_TRADDR) ||
908                    (ctrl->opts->mask & NVMF_OPT_HOST_TRADDR)) {
909                 return false;
910         }
911
912         return true;
913 }
914 EXPORT_SYMBOL_GPL(nvmf_ip_options_match);
915
916 static int nvmf_check_allowed_opts(struct nvmf_ctrl_options *opts,
917                 unsigned int allowed_opts)
918 {
919         if (opts->mask & ~allowed_opts) {
920                 int i;
921
922                 for (i = 0; i < ARRAY_SIZE(opt_tokens); i++) {
923                         if ((opt_tokens[i].token & opts->mask) &&
924                             (opt_tokens[i].token & ~allowed_opts)) {
925                                 pr_warn("invalid parameter '%s'\n",
926                                         opt_tokens[i].pattern);
927                         }
928                 }
929
930                 return -EINVAL;
931         }
932
933         return 0;
934 }
935
936 void nvmf_free_options(struct nvmf_ctrl_options *opts)
937 {
938         nvmf_host_put(opts->host);
939         kfree(opts->transport);
940         kfree(opts->traddr);
941         kfree(opts->trsvcid);
942         kfree(opts->subsysnqn);
943         kfree(opts->host_traddr);
944         kfree(opts);
945 }
946 EXPORT_SYMBOL_GPL(nvmf_free_options);
947
948 #define NVMF_REQUIRED_OPTS      (NVMF_OPT_TRANSPORT | NVMF_OPT_NQN)
949 #define NVMF_ALLOWED_OPTS       (NVMF_OPT_QUEUE_SIZE | NVMF_OPT_NR_IO_QUEUES | \
950                                  NVMF_OPT_KATO | NVMF_OPT_HOSTNQN | \
951                                  NVMF_OPT_HOST_ID | NVMF_OPT_DUP_CONNECT |\
952                                  NVMF_OPT_DISABLE_SQFLOW)
953
954 static struct nvme_ctrl *
955 nvmf_create_ctrl(struct device *dev, const char *buf, size_t count)
956 {
957         struct nvmf_ctrl_options *opts;
958         struct nvmf_transport_ops *ops;
959         struct nvme_ctrl *ctrl;
960         int ret;
961
962         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
963         if (!opts)
964                 return ERR_PTR(-ENOMEM);
965
966         ret = nvmf_parse_options(opts, buf);
967         if (ret)
968                 goto out_free_opts;
969
970
971         request_module("nvme-%s", opts->transport);
972
973         /*
974          * Check the generic options first as we need a valid transport for
975          * the lookup below.  Then clear the generic flags so that transport
976          * drivers don't have to care about them.
977          */
978         ret = nvmf_check_required_opts(opts, NVMF_REQUIRED_OPTS);
979         if (ret)
980                 goto out_free_opts;
981         opts->mask &= ~NVMF_REQUIRED_OPTS;
982
983         down_read(&nvmf_transports_rwsem);
984         ops = nvmf_lookup_transport(opts);
985         if (!ops) {
986                 pr_info("no handler found for transport %s.\n",
987                         opts->transport);
988                 ret = -EINVAL;
989                 goto out_unlock;
990         }
991
992         if (!try_module_get(ops->module)) {
993                 ret = -EBUSY;
994                 goto out_unlock;
995         }
996         up_read(&nvmf_transports_rwsem);
997
998         ret = nvmf_check_required_opts(opts, ops->required_opts);
999         if (ret)
1000                 goto out_module_put;
1001         ret = nvmf_check_allowed_opts(opts, NVMF_ALLOWED_OPTS |
1002                                 ops->allowed_opts | ops->required_opts);
1003         if (ret)
1004                 goto out_module_put;
1005
1006         ctrl = ops->create_ctrl(dev, opts);
1007         if (IS_ERR(ctrl)) {
1008                 ret = PTR_ERR(ctrl);
1009                 goto out_module_put;
1010         }
1011
1012         module_put(ops->module);
1013         return ctrl;
1014
1015 out_module_put:
1016         module_put(ops->module);
1017         goto out_free_opts;
1018 out_unlock:
1019         up_read(&nvmf_transports_rwsem);
1020 out_free_opts:
1021         nvmf_free_options(opts);
1022         return ERR_PTR(ret);
1023 }
1024
1025 static struct class *nvmf_class;
1026 static struct device *nvmf_device;
1027 static DEFINE_MUTEX(nvmf_dev_mutex);
1028
1029 static ssize_t nvmf_dev_write(struct file *file, const char __user *ubuf,
1030                 size_t count, loff_t *pos)
1031 {
1032         struct seq_file *seq_file = file->private_data;
1033         struct nvme_ctrl *ctrl;
1034         const char *buf;
1035         int ret = 0;
1036
1037         if (count > PAGE_SIZE)
1038                 return -ENOMEM;
1039
1040         buf = memdup_user_nul(ubuf, count);
1041         if (IS_ERR(buf))
1042                 return PTR_ERR(buf);
1043
1044         mutex_lock(&nvmf_dev_mutex);
1045         if (seq_file->private) {
1046                 ret = -EINVAL;
1047                 goto out_unlock;
1048         }
1049
1050         ctrl = nvmf_create_ctrl(nvmf_device, buf, count);
1051         if (IS_ERR(ctrl)) {
1052                 ret = PTR_ERR(ctrl);
1053                 goto out_unlock;
1054         }
1055
1056         seq_file->private = ctrl;
1057
1058 out_unlock:
1059         mutex_unlock(&nvmf_dev_mutex);
1060         kfree(buf);
1061         return ret ? ret : count;
1062 }
1063
1064 static int nvmf_dev_show(struct seq_file *seq_file, void *private)
1065 {
1066         struct nvme_ctrl *ctrl;
1067         int ret = 0;
1068
1069         mutex_lock(&nvmf_dev_mutex);
1070         ctrl = seq_file->private;
1071         if (!ctrl) {
1072                 ret = -EINVAL;
1073                 goto out_unlock;
1074         }
1075
1076         seq_printf(seq_file, "instance=%d,cntlid=%d\n",
1077                         ctrl->instance, ctrl->cntlid);
1078
1079 out_unlock:
1080         mutex_unlock(&nvmf_dev_mutex);
1081         return ret;
1082 }
1083
1084 static int nvmf_dev_open(struct inode *inode, struct file *file)
1085 {
1086         /*
1087          * The miscdevice code initializes file->private_data, but doesn't
1088          * make use of it later.
1089          */
1090         file->private_data = NULL;
1091         return single_open(file, nvmf_dev_show, NULL);
1092 }
1093
1094 static int nvmf_dev_release(struct inode *inode, struct file *file)
1095 {
1096         struct seq_file *seq_file = file->private_data;
1097         struct nvme_ctrl *ctrl = seq_file->private;
1098
1099         if (ctrl)
1100                 nvme_put_ctrl(ctrl);
1101         return single_release(inode, file);
1102 }
1103
1104 static const struct file_operations nvmf_dev_fops = {
1105         .owner          = THIS_MODULE,
1106         .write          = nvmf_dev_write,
1107         .read           = seq_read,
1108         .open           = nvmf_dev_open,
1109         .release        = nvmf_dev_release,
1110 };
1111
1112 static struct miscdevice nvmf_misc = {
1113         .minor          = MISC_DYNAMIC_MINOR,
1114         .name           = "nvme-fabrics",
1115         .fops           = &nvmf_dev_fops,
1116 };
1117
1118 static int __init nvmf_init(void)
1119 {
1120         int ret;
1121
1122         nvmf_default_host = nvmf_host_default();
1123         if (!nvmf_default_host)
1124                 return -ENOMEM;
1125
1126         nvmf_class = class_create(THIS_MODULE, "nvme-fabrics");
1127         if (IS_ERR(nvmf_class)) {
1128                 pr_err("couldn't register class nvme-fabrics\n");
1129                 ret = PTR_ERR(nvmf_class);
1130                 goto out_free_host;
1131         }
1132
1133         nvmf_device =
1134                 device_create(nvmf_class, NULL, MKDEV(0, 0), NULL, "ctl");
1135         if (IS_ERR(nvmf_device)) {
1136                 pr_err("couldn't create nvme-fabris device!\n");
1137                 ret = PTR_ERR(nvmf_device);
1138                 goto out_destroy_class;
1139         }
1140
1141         ret = misc_register(&nvmf_misc);
1142         if (ret) {
1143                 pr_err("couldn't register misc device: %d\n", ret);
1144                 goto out_destroy_device;
1145         }
1146
1147         return 0;
1148
1149 out_destroy_device:
1150         device_destroy(nvmf_class, MKDEV(0, 0));
1151 out_destroy_class:
1152         class_destroy(nvmf_class);
1153 out_free_host:
1154         nvmf_host_put(nvmf_default_host);
1155         return ret;
1156 }
1157
1158 static void __exit nvmf_exit(void)
1159 {
1160         misc_deregister(&nvmf_misc);
1161         device_destroy(nvmf_class, MKDEV(0, 0));
1162         class_destroy(nvmf_class);
1163         nvmf_host_put(nvmf_default_host);
1164
1165         BUILD_BUG_ON(sizeof(struct nvmf_connect_command) != 64);
1166         BUILD_BUG_ON(sizeof(struct nvmf_property_get_command) != 64);
1167         BUILD_BUG_ON(sizeof(struct nvmf_property_set_command) != 64);
1168         BUILD_BUG_ON(sizeof(struct nvmf_connect_data) != 1024);
1169 }
1170
1171 MODULE_LICENSE("GPL v2");
1172
1173 module_init(nvmf_init);
1174 module_exit(nvmf_exit);