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