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