linux/drivers/nvme/target/core.c
<<
>>
Prefs
   1/*
   2 * Common code for the NVMe target.
   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/module.h>
  16#include <linux/random.h>
  17#include <linux/rculist.h>
  18#include <linux/pci-p2pdma.h>
  19#include <linux/scatterlist.h>
  20
  21#define CREATE_TRACE_POINTS
  22#include "trace.h"
  23
  24#include "nvmet.h"
  25
  26struct workqueue_struct *buffered_io_wq;
  27static const struct nvmet_fabrics_ops *nvmet_transports[NVMF_TRTYPE_MAX];
  28static DEFINE_IDA(cntlid_ida);
  29
  30/*
  31 * This read/write semaphore is used to synchronize access to configuration
  32 * information on a target system that will result in discovery log page
  33 * information change for at least one host.
  34 * The full list of resources to protected by this semaphore is:
  35 *
  36 *  - subsystems list
  37 *  - per-subsystem allowed hosts list
  38 *  - allow_any_host subsystem attribute
  39 *  - nvmet_genctr
  40 *  - the nvmet_transports array
  41 *
  42 * When updating any of those lists/structures write lock should be obtained,
  43 * while when reading (popolating discovery log page or checking host-subsystem
  44 * link) read lock is obtained to allow concurrent reads.
  45 */
  46DECLARE_RWSEM(nvmet_config_sem);
  47
  48u32 nvmet_ana_group_enabled[NVMET_MAX_ANAGRPS + 1];
  49u64 nvmet_ana_chgcnt;
  50DECLARE_RWSEM(nvmet_ana_sem);
  51
  52inline u16 errno_to_nvme_status(struct nvmet_req *req, int errno)
  53{
  54        u16 status;
  55
  56        switch (errno) {
  57        case 0:
  58                status = NVME_SC_SUCCESS;
  59                break;
  60        case -ENOSPC:
  61                req->error_loc = offsetof(struct nvme_rw_command, length);
  62                status = NVME_SC_CAP_EXCEEDED | NVME_SC_DNR;
  63                break;
  64        case -EREMOTEIO:
  65                req->error_loc = offsetof(struct nvme_rw_command, slba);
  66                status = NVME_SC_LBA_RANGE | NVME_SC_DNR;
  67                break;
  68        case -EOPNOTSUPP:
  69                req->error_loc = offsetof(struct nvme_common_command, opcode);
  70                switch (req->cmd->common.opcode) {
  71                case nvme_cmd_dsm:
  72                case nvme_cmd_write_zeroes:
  73                        status = NVME_SC_ONCS_NOT_SUPPORTED | NVME_SC_DNR;
  74                        break;
  75                default:
  76                        status = NVME_SC_INVALID_OPCODE | NVME_SC_DNR;
  77                }
  78                break;
  79        case -ENODATA:
  80                req->error_loc = offsetof(struct nvme_rw_command, nsid);
  81                status = NVME_SC_ACCESS_DENIED;
  82                break;
  83        case -EIO:
  84                /* FALLTHRU */
  85        default:
  86                req->error_loc = offsetof(struct nvme_common_command, opcode);
  87                status = NVME_SC_INTERNAL | NVME_SC_DNR;
  88        }
  89
  90        return status;
  91}
  92
  93u16 nvmet_report_invalid_opcode(struct nvmet_req *req)
  94{
  95        pr_debug("unhandled cmd %d on qid %d\n", req->cmd->common.opcode,
  96                 req->sq->qid);
  97
  98        req->error_loc = offsetof(struct nvme_common_command, opcode);
  99        return NVME_SC_INVALID_OPCODE | NVME_SC_DNR;
 100}
 101
 102static struct nvmet_subsys *nvmet_find_get_subsys(struct nvmet_port *port,
 103                const char *subsysnqn);
 104
 105u16 nvmet_copy_to_sgl(struct nvmet_req *req, off_t off, const void *buf,
 106                size_t len)
 107{
 108        if (sg_pcopy_from_buffer(req->sg, req->sg_cnt, buf, len, off) != len) {
 109                req->error_loc = offsetof(struct nvme_common_command, dptr);
 110                return NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR;
 111        }
 112        return 0;
 113}
 114
 115u16 nvmet_copy_from_sgl(struct nvmet_req *req, off_t off, void *buf, size_t len)
 116{
 117        if (sg_pcopy_to_buffer(req->sg, req->sg_cnt, buf, len, off) != len) {
 118                req->error_loc = offsetof(struct nvme_common_command, dptr);
 119                return NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR;
 120        }
 121        return 0;
 122}
 123
 124u16 nvmet_zero_sgl(struct nvmet_req *req, off_t off, size_t len)
 125{
 126        if (sg_zero_buffer(req->sg, req->sg_cnt, len, off) != len) {
 127                req->error_loc = offsetof(struct nvme_common_command, dptr);
 128                return NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR;
 129        }
 130        return 0;
 131}
 132
 133static unsigned int nvmet_max_nsid(struct nvmet_subsys *subsys)
 134{
 135        unsigned long nsid = 0;
 136        struct nvmet_ns *cur;
 137        unsigned long idx;
 138
 139        xa_for_each(&subsys->namespaces, idx, cur)
 140                nsid = cur->nsid;
 141
 142        return nsid;
 143}
 144
 145static u32 nvmet_async_event_result(struct nvmet_async_event *aen)
 146{
 147        return aen->event_type | (aen->event_info << 8) | (aen->log_page << 16);
 148}
 149
 150static void nvmet_async_events_failall(struct nvmet_ctrl *ctrl)
 151{
 152        u16 status = NVME_SC_INTERNAL | NVME_SC_DNR;
 153        struct nvmet_req *req;
 154
 155        mutex_lock(&ctrl->lock);
 156        while (ctrl->nr_async_event_cmds) {
 157                req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds];
 158                mutex_unlock(&ctrl->lock);
 159                nvmet_req_complete(req, status);
 160                mutex_lock(&ctrl->lock);
 161        }
 162        mutex_unlock(&ctrl->lock);
 163}
 164
 165static void nvmet_async_events_process(struct nvmet_ctrl *ctrl)
 166{
 167        struct nvmet_async_event *aen;
 168        struct nvmet_req *req;
 169
 170        mutex_lock(&ctrl->lock);
 171        while (ctrl->nr_async_event_cmds && !list_empty(&ctrl->async_events)) {
 172                aen = list_first_entry(&ctrl->async_events,
 173                                       struct nvmet_async_event, entry);
 174                req = ctrl->async_event_cmds[--ctrl->nr_async_event_cmds];
 175                nvmet_set_result(req, nvmet_async_event_result(aen));
 176
 177                list_del(&aen->entry);
 178                kfree(aen);
 179
 180                mutex_unlock(&ctrl->lock);
 181                trace_nvmet_async_event(ctrl, req->cqe->result.u32);
 182                nvmet_req_complete(req, 0);
 183                mutex_lock(&ctrl->lock);
 184        }
 185        mutex_unlock(&ctrl->lock);
 186}
 187
 188static void nvmet_async_events_free(struct nvmet_ctrl *ctrl)
 189{
 190        struct nvmet_async_event *aen, *tmp;
 191
 192        mutex_lock(&ctrl->lock);
 193        list_for_each_entry_safe(aen, tmp, &ctrl->async_events, entry) {
 194                list_del(&aen->entry);
 195                kfree(aen);
 196        }
 197        mutex_unlock(&ctrl->lock);
 198}
 199
 200static void nvmet_async_event_work(struct work_struct *work)
 201{
 202        struct nvmet_ctrl *ctrl =
 203                container_of(work, struct nvmet_ctrl, async_event_work);
 204
 205        nvmet_async_events_process(ctrl);
 206}
 207
 208void nvmet_add_async_event(struct nvmet_ctrl *ctrl, u8 event_type,
 209                u8 event_info, u8 log_page)
 210{
 211        struct nvmet_async_event *aen;
 212
 213        aen = kmalloc(sizeof(*aen), GFP_KERNEL);
 214        if (!aen)
 215                return;
 216
 217        aen->event_type = event_type;
 218        aen->event_info = event_info;
 219        aen->log_page = log_page;
 220
 221        mutex_lock(&ctrl->lock);
 222        list_add_tail(&aen->entry, &ctrl->async_events);
 223        mutex_unlock(&ctrl->lock);
 224
 225        schedule_work(&ctrl->async_event_work);
 226}
 227
 228static void nvmet_add_to_changed_ns_log(struct nvmet_ctrl *ctrl, __le32 nsid)
 229{
 230        u32 i;
 231
 232        mutex_lock(&ctrl->lock);
 233        if (ctrl->nr_changed_ns > NVME_MAX_CHANGED_NAMESPACES)
 234                goto out_unlock;
 235
 236        for (i = 0; i < ctrl->nr_changed_ns; i++) {
 237                if (ctrl->changed_ns_list[i] == nsid)
 238                        goto out_unlock;
 239        }
 240
 241        if (ctrl->nr_changed_ns == NVME_MAX_CHANGED_NAMESPACES) {
 242                ctrl->changed_ns_list[0] = cpu_to_le32(0xffffffff);
 243                ctrl->nr_changed_ns = U32_MAX;
 244                goto out_unlock;
 245        }
 246
 247        ctrl->changed_ns_list[ctrl->nr_changed_ns++] = nsid;
 248out_unlock:
 249        mutex_unlock(&ctrl->lock);
 250}
 251
 252void nvmet_ns_changed(struct nvmet_subsys *subsys, u32 nsid)
 253{
 254        struct nvmet_ctrl *ctrl;
 255
 256        lockdep_assert_held(&subsys->lock);
 257
 258        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
 259                nvmet_add_to_changed_ns_log(ctrl, cpu_to_le32(nsid));
 260                if (nvmet_aen_bit_disabled(ctrl, NVME_AEN_BIT_NS_ATTR))
 261                        continue;
 262                nvmet_add_async_event(ctrl, NVME_AER_TYPE_NOTICE,
 263                                NVME_AER_NOTICE_NS_CHANGED,
 264                                NVME_LOG_CHANGED_NS);
 265        }
 266}
 267
 268void nvmet_send_ana_event(struct nvmet_subsys *subsys,
 269                struct nvmet_port *port)
 270{
 271        struct nvmet_ctrl *ctrl;
 272
 273        mutex_lock(&subsys->lock);
 274        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
 275                if (port && ctrl->port != port)
 276                        continue;
 277                if (nvmet_aen_bit_disabled(ctrl, NVME_AEN_BIT_ANA_CHANGE))
 278                        continue;
 279                nvmet_add_async_event(ctrl, NVME_AER_TYPE_NOTICE,
 280                                NVME_AER_NOTICE_ANA, NVME_LOG_ANA);
 281        }
 282        mutex_unlock(&subsys->lock);
 283}
 284
 285void nvmet_port_send_ana_event(struct nvmet_port *port)
 286{
 287        struct nvmet_subsys_link *p;
 288
 289        down_read(&nvmet_config_sem);
 290        list_for_each_entry(p, &port->subsystems, entry)
 291                nvmet_send_ana_event(p->subsys, port);
 292        up_read(&nvmet_config_sem);
 293}
 294
 295int nvmet_register_transport(const struct nvmet_fabrics_ops *ops)
 296{
 297        int ret = 0;
 298
 299        down_write(&nvmet_config_sem);
 300        if (nvmet_transports[ops->type])
 301                ret = -EINVAL;
 302        else
 303                nvmet_transports[ops->type] = ops;
 304        up_write(&nvmet_config_sem);
 305
 306        return ret;
 307}
 308EXPORT_SYMBOL_GPL(nvmet_register_transport);
 309
 310void nvmet_unregister_transport(const struct nvmet_fabrics_ops *ops)
 311{
 312        down_write(&nvmet_config_sem);
 313        nvmet_transports[ops->type] = NULL;
 314        up_write(&nvmet_config_sem);
 315}
 316EXPORT_SYMBOL_GPL(nvmet_unregister_transport);
 317
 318void nvmet_port_del_ctrls(struct nvmet_port *port, struct nvmet_subsys *subsys)
 319{
 320        struct nvmet_ctrl *ctrl;
 321
 322        mutex_lock(&subsys->lock);
 323        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
 324                if (ctrl->port == port)
 325                        ctrl->ops->delete_ctrl(ctrl);
 326        }
 327        mutex_unlock(&subsys->lock);
 328}
 329
 330int nvmet_enable_port(struct nvmet_port *port)
 331{
 332        const struct nvmet_fabrics_ops *ops;
 333        int ret;
 334
 335        lockdep_assert_held(&nvmet_config_sem);
 336
 337        ops = nvmet_transports[port->disc_addr.trtype];
 338        if (!ops) {
 339                up_write(&nvmet_config_sem);
 340                request_module("nvmet-transport-%d", port->disc_addr.trtype);
 341                down_write(&nvmet_config_sem);
 342                ops = nvmet_transports[port->disc_addr.trtype];
 343                if (!ops) {
 344                        pr_err("transport type %d not supported\n",
 345                                port->disc_addr.trtype);
 346                        return -EINVAL;
 347                }
 348        }
 349
 350        if (!try_module_get(ops->owner))
 351                return -EINVAL;
 352
 353        /*
 354         * If the user requested PI support and the transport isn't pi capable,
 355         * don't enable the port.
 356         */
 357        if (port->pi_enable && !(ops->flags & NVMF_METADATA_SUPPORTED)) {
 358                pr_err("T10-PI is not supported by transport type %d\n",
 359                       port->disc_addr.trtype);
 360                ret = -EINVAL;
 361                goto out_put;
 362        }
 363
 364        ret = ops->add_port(port);
 365        if (ret)
 366                goto out_put;
 367
 368        /* If the transport didn't set inline_data_size, then disable it. */
 369        if (port->inline_data_size < 0)
 370                port->inline_data_size = 0;
 371
 372        port->enabled = true;
 373        port->tr_ops = ops;
 374        return 0;
 375
 376out_put:
 377        module_put(ops->owner);
 378        return ret;
 379}
 380
 381void nvmet_disable_port(struct nvmet_port *port)
 382{
 383        const struct nvmet_fabrics_ops *ops;
 384
 385        lockdep_assert_held(&nvmet_config_sem);
 386
 387        port->enabled = false;
 388        port->tr_ops = NULL;
 389
 390        ops = nvmet_transports[port->disc_addr.trtype];
 391        ops->remove_port(port);
 392        module_put(ops->owner);
 393}
 394
 395static void nvmet_keep_alive_timer(struct work_struct *work)
 396{
 397        struct nvmet_ctrl *ctrl = container_of(to_delayed_work(work),
 398                        struct nvmet_ctrl, ka_work);
 399        bool cmd_seen = ctrl->cmd_seen;
 400
 401        ctrl->cmd_seen = false;
 402        if (cmd_seen) {
 403                pr_debug("ctrl %d reschedule traffic based keep-alive timer\n",
 404                        ctrl->cntlid);
 405                schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
 406                return;
 407        }
 408
 409        pr_err("ctrl %d keep-alive timer (%d seconds) expired!\n",
 410                ctrl->cntlid, ctrl->kato);
 411
 412        nvmet_ctrl_fatal_error(ctrl);
 413}
 414
 415void nvmet_start_keep_alive_timer(struct nvmet_ctrl *ctrl)
 416{
 417        if (unlikely(ctrl->kato == 0))
 418                return;
 419
 420        pr_debug("ctrl %d start keep-alive timer for %d secs\n",
 421                ctrl->cntlid, ctrl->kato);
 422
 423        INIT_DELAYED_WORK(&ctrl->ka_work, nvmet_keep_alive_timer);
 424        schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
 425}
 426
 427void nvmet_stop_keep_alive_timer(struct nvmet_ctrl *ctrl)
 428{
 429        if (unlikely(ctrl->kato == 0))
 430                return;
 431
 432        pr_debug("ctrl %d stop keep-alive\n", ctrl->cntlid);
 433
 434        cancel_delayed_work_sync(&ctrl->ka_work);
 435}
 436
 437u16 nvmet_req_find_ns(struct nvmet_req *req)
 438{
 439        u32 nsid = le32_to_cpu(req->cmd->common.nsid);
 440
 441        req->ns = xa_load(&nvmet_req_subsys(req)->namespaces, nsid);
 442        if (unlikely(!req->ns)) {
 443                req->error_loc = offsetof(struct nvme_common_command, nsid);
 444                return NVME_SC_INVALID_NS | NVME_SC_DNR;
 445        }
 446
 447        percpu_ref_get(&req->ns->ref);
 448        return NVME_SC_SUCCESS;
 449}
 450
 451static void nvmet_destroy_namespace(struct percpu_ref *ref)
 452{
 453        struct nvmet_ns *ns = container_of(ref, struct nvmet_ns, ref);
 454
 455        complete(&ns->disable_done);
 456}
 457
 458void nvmet_put_namespace(struct nvmet_ns *ns)
 459{
 460        percpu_ref_put(&ns->ref);
 461}
 462
 463static void nvmet_ns_dev_disable(struct nvmet_ns *ns)
 464{
 465        nvmet_bdev_ns_disable(ns);
 466        nvmet_file_ns_disable(ns);
 467}
 468
 469static int nvmet_p2pmem_ns_enable(struct nvmet_ns *ns)
 470{
 471        int ret;
 472        struct pci_dev *p2p_dev;
 473
 474        if (!ns->use_p2pmem)
 475                return 0;
 476
 477        if (!ns->bdev) {
 478                pr_err("peer-to-peer DMA is not supported by non-block device namespaces\n");
 479                return -EINVAL;
 480        }
 481
 482        if (!blk_queue_pci_p2pdma(ns->bdev->bd_queue)) {
 483                pr_err("peer-to-peer DMA is not supported by the driver of %s\n",
 484                       ns->device_path);
 485                return -EINVAL;
 486        }
 487
 488        if (ns->p2p_dev) {
 489                ret = pci_p2pdma_distance(ns->p2p_dev, nvmet_ns_dev(ns), true);
 490                if (ret < 0)
 491                        return -EINVAL;
 492        } else {
 493                /*
 494                 * Right now we just check that there is p2pmem available so
 495                 * we can report an error to the user right away if there
 496                 * is not. We'll find the actual device to use once we
 497                 * setup the controller when the port's device is available.
 498                 */
 499
 500                p2p_dev = pci_p2pmem_find(nvmet_ns_dev(ns));
 501                if (!p2p_dev) {
 502                        pr_err("no peer-to-peer memory is available for %s\n",
 503                               ns->device_path);
 504                        return -EINVAL;
 505                }
 506
 507                pci_dev_put(p2p_dev);
 508        }
 509
 510        return 0;
 511}
 512
 513/*
 514 * Note: ctrl->subsys->lock should be held when calling this function
 515 */
 516static void nvmet_p2pmem_ns_add_p2p(struct nvmet_ctrl *ctrl,
 517                                    struct nvmet_ns *ns)
 518{
 519        struct device *clients[2];
 520        struct pci_dev *p2p_dev;
 521        int ret;
 522
 523        if (!ctrl->p2p_client || !ns->use_p2pmem)
 524                return;
 525
 526        if (ns->p2p_dev) {
 527                ret = pci_p2pdma_distance(ns->p2p_dev, ctrl->p2p_client, true);
 528                if (ret < 0)
 529                        return;
 530
 531                p2p_dev = pci_dev_get(ns->p2p_dev);
 532        } else {
 533                clients[0] = ctrl->p2p_client;
 534                clients[1] = nvmet_ns_dev(ns);
 535
 536                p2p_dev = pci_p2pmem_find_many(clients, ARRAY_SIZE(clients));
 537                if (!p2p_dev) {
 538                        pr_err("no peer-to-peer memory is available that's supported by %s and %s\n",
 539                               dev_name(ctrl->p2p_client), ns->device_path);
 540                        return;
 541                }
 542        }
 543
 544        ret = radix_tree_insert(&ctrl->p2p_ns_map, ns->nsid, p2p_dev);
 545        if (ret < 0)
 546                pci_dev_put(p2p_dev);
 547
 548        pr_info("using p2pmem on %s for nsid %d\n", pci_name(p2p_dev),
 549                ns->nsid);
 550}
 551
 552void nvmet_ns_revalidate(struct nvmet_ns *ns)
 553{
 554        loff_t oldsize = ns->size;
 555
 556        if (ns->bdev)
 557                nvmet_bdev_ns_revalidate(ns);
 558        else
 559                nvmet_file_ns_revalidate(ns);
 560
 561        if (oldsize != ns->size)
 562                nvmet_ns_changed(ns->subsys, ns->nsid);
 563}
 564
 565int nvmet_ns_enable(struct nvmet_ns *ns)
 566{
 567        struct nvmet_subsys *subsys = ns->subsys;
 568        struct nvmet_ctrl *ctrl;
 569        int ret;
 570
 571        mutex_lock(&subsys->lock);
 572        ret = 0;
 573
 574        if (nvmet_passthru_ctrl(subsys)) {
 575                pr_info("cannot enable both passthru and regular namespaces for a single subsystem");
 576                goto out_unlock;
 577        }
 578
 579        if (ns->enabled)
 580                goto out_unlock;
 581
 582        ret = -EMFILE;
 583        if (subsys->nr_namespaces == NVMET_MAX_NAMESPACES)
 584                goto out_unlock;
 585
 586        ret = nvmet_bdev_ns_enable(ns);
 587        if (ret == -ENOTBLK)
 588                ret = nvmet_file_ns_enable(ns);
 589        if (ret)
 590                goto out_unlock;
 591
 592        ret = nvmet_p2pmem_ns_enable(ns);
 593        if (ret)
 594                goto out_dev_disable;
 595
 596        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
 597                nvmet_p2pmem_ns_add_p2p(ctrl, ns);
 598
 599        ret = percpu_ref_init(&ns->ref, nvmet_destroy_namespace,
 600                                0, GFP_KERNEL);
 601        if (ret)
 602                goto out_dev_put;
 603
 604        if (ns->nsid > subsys->max_nsid)
 605                subsys->max_nsid = ns->nsid;
 606
 607        ret = xa_insert(&subsys->namespaces, ns->nsid, ns, GFP_KERNEL);
 608        if (ret)
 609                goto out_restore_subsys_maxnsid;
 610
 611        subsys->nr_namespaces++;
 612
 613        nvmet_ns_changed(subsys, ns->nsid);
 614        ns->enabled = true;
 615        ret = 0;
 616out_unlock:
 617        mutex_unlock(&subsys->lock);
 618        return ret;
 619
 620out_restore_subsys_maxnsid:
 621        subsys->max_nsid = nvmet_max_nsid(subsys);
 622        percpu_ref_exit(&ns->ref);
 623out_dev_put:
 624        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
 625                pci_dev_put(radix_tree_delete(&ctrl->p2p_ns_map, ns->nsid));
 626out_dev_disable:
 627        nvmet_ns_dev_disable(ns);
 628        goto out_unlock;
 629}
 630
 631void nvmet_ns_disable(struct nvmet_ns *ns)
 632{
 633        struct nvmet_subsys *subsys = ns->subsys;
 634        struct nvmet_ctrl *ctrl;
 635
 636        mutex_lock(&subsys->lock);
 637        if (!ns->enabled)
 638                goto out_unlock;
 639
 640        ns->enabled = false;
 641        xa_erase(&ns->subsys->namespaces, ns->nsid);
 642        if (ns->nsid == subsys->max_nsid)
 643                subsys->max_nsid = nvmet_max_nsid(subsys);
 644
 645        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
 646                pci_dev_put(radix_tree_delete(&ctrl->p2p_ns_map, ns->nsid));
 647
 648        mutex_unlock(&subsys->lock);
 649
 650        /*
 651         * Now that we removed the namespaces from the lookup list, we
 652         * can kill the per_cpu ref and wait for any remaining references
 653         * to be dropped, as well as a RCU grace period for anyone only
 654         * using the namepace under rcu_read_lock().  Note that we can't
 655         * use call_rcu here as we need to ensure the namespaces have
 656         * been fully destroyed before unloading the module.
 657         */
 658        percpu_ref_kill(&ns->ref);
 659        synchronize_rcu();
 660        wait_for_completion(&ns->disable_done);
 661        percpu_ref_exit(&ns->ref);
 662
 663        mutex_lock(&subsys->lock);
 664        subsys->nr_namespaces--;
 665        nvmet_ns_changed(subsys, ns->nsid);
 666        nvmet_ns_dev_disable(ns);
 667out_unlock:
 668        mutex_unlock(&subsys->lock);
 669}
 670
 671void nvmet_ns_free(struct nvmet_ns *ns)
 672{
 673        nvmet_ns_disable(ns);
 674
 675        down_write(&nvmet_ana_sem);
 676        nvmet_ana_group_enabled[ns->anagrpid]--;
 677        up_write(&nvmet_ana_sem);
 678
 679        kfree(ns->device_path);
 680        kfree(ns);
 681}
 682
 683struct nvmet_ns *nvmet_ns_alloc(struct nvmet_subsys *subsys, u32 nsid)
 684{
 685        struct nvmet_ns *ns;
 686
 687        ns = kzalloc(sizeof(*ns), GFP_KERNEL);
 688        if (!ns)
 689                return NULL;
 690
 691        init_completion(&ns->disable_done);
 692
 693        ns->nsid = nsid;
 694        ns->subsys = subsys;
 695
 696        down_write(&nvmet_ana_sem);
 697        ns->anagrpid = NVMET_DEFAULT_ANA_GRPID;
 698        nvmet_ana_group_enabled[ns->anagrpid]++;
 699        up_write(&nvmet_ana_sem);
 700
 701        uuid_gen(&ns->uuid);
 702        ns->buffered_io = false;
 703
 704        return ns;
 705}
 706
 707static void nvmet_update_sq_head(struct nvmet_req *req)
 708{
 709        if (req->sq->size) {
 710                u32 old_sqhd, new_sqhd;
 711
 712                do {
 713                        old_sqhd = req->sq->sqhd;
 714                        new_sqhd = (old_sqhd + 1) % req->sq->size;
 715                } while (cmpxchg(&req->sq->sqhd, old_sqhd, new_sqhd) !=
 716                                        old_sqhd);
 717        }
 718        req->cqe->sq_head = cpu_to_le16(req->sq->sqhd & 0x0000FFFF);
 719}
 720
 721static void nvmet_set_error(struct nvmet_req *req, u16 status)
 722{
 723        struct nvmet_ctrl *ctrl = req->sq->ctrl;
 724        struct nvme_error_slot *new_error_slot;
 725        unsigned long flags;
 726
 727        req->cqe->status = cpu_to_le16(status << 1);
 728
 729        if (!ctrl || req->error_loc == NVMET_NO_ERROR_LOC)
 730                return;
 731
 732        spin_lock_irqsave(&ctrl->error_lock, flags);
 733        ctrl->err_counter++;
 734        new_error_slot =
 735                &ctrl->slots[ctrl->err_counter % NVMET_ERROR_LOG_SLOTS];
 736
 737        new_error_slot->error_count = cpu_to_le64(ctrl->err_counter);
 738        new_error_slot->sqid = cpu_to_le16(req->sq->qid);
 739        new_error_slot->cmdid = cpu_to_le16(req->cmd->common.command_id);
 740        new_error_slot->status_field = cpu_to_le16(status << 1);
 741        new_error_slot->param_error_location = cpu_to_le16(req->error_loc);
 742        new_error_slot->lba = cpu_to_le64(req->error_slba);
 743        new_error_slot->nsid = req->cmd->common.nsid;
 744        spin_unlock_irqrestore(&ctrl->error_lock, flags);
 745
 746        /* set the more bit for this request */
 747        req->cqe->status |= cpu_to_le16(1 << 14);
 748}
 749
 750static void __nvmet_req_complete(struct nvmet_req *req, u16 status)
 751{
 752        if (!req->sq->sqhd_disabled)
 753                nvmet_update_sq_head(req);
 754        req->cqe->sq_id = cpu_to_le16(req->sq->qid);
 755        req->cqe->command_id = req->cmd->common.command_id;
 756
 757        if (unlikely(status))
 758                nvmet_set_error(req, status);
 759
 760        trace_nvmet_req_complete(req);
 761
 762        if (req->ns)
 763                nvmet_put_namespace(req->ns);
 764        req->ops->queue_response(req);
 765}
 766
 767void nvmet_req_complete(struct nvmet_req *req, u16 status)
 768{
 769        __nvmet_req_complete(req, status);
 770        percpu_ref_put(&req->sq->ref);
 771}
 772EXPORT_SYMBOL_GPL(nvmet_req_complete);
 773
 774void nvmet_cq_setup(struct nvmet_ctrl *ctrl, struct nvmet_cq *cq,
 775                u16 qid, u16 size)
 776{
 777        cq->qid = qid;
 778        cq->size = size;
 779}
 780
 781void nvmet_sq_setup(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq,
 782                u16 qid, u16 size)
 783{
 784        sq->sqhd = 0;
 785        sq->qid = qid;
 786        sq->size = size;
 787
 788        ctrl->sqs[qid] = sq;
 789}
 790
 791static void nvmet_confirm_sq(struct percpu_ref *ref)
 792{
 793        struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref);
 794
 795        complete(&sq->confirm_done);
 796}
 797
 798void nvmet_sq_destroy(struct nvmet_sq *sq)
 799{
 800        struct nvmet_ctrl *ctrl = sq->ctrl;
 801
 802        /*
 803         * If this is the admin queue, complete all AERs so that our
 804         * queue doesn't have outstanding requests on it.
 805         */
 806        if (ctrl && ctrl->sqs && ctrl->sqs[0] == sq)
 807                nvmet_async_events_failall(ctrl);
 808        percpu_ref_kill_and_confirm(&sq->ref, nvmet_confirm_sq);
 809        wait_for_completion(&sq->confirm_done);
 810        wait_for_completion(&sq->free_done);
 811        percpu_ref_exit(&sq->ref);
 812
 813        if (ctrl) {
 814                nvmet_ctrl_put(ctrl);
 815                sq->ctrl = NULL; /* allows reusing the queue later */
 816        }
 817}
 818EXPORT_SYMBOL_GPL(nvmet_sq_destroy);
 819
 820static void nvmet_sq_free(struct percpu_ref *ref)
 821{
 822        struct nvmet_sq *sq = container_of(ref, struct nvmet_sq, ref);
 823
 824        complete(&sq->free_done);
 825}
 826
 827int nvmet_sq_init(struct nvmet_sq *sq)
 828{
 829        int ret;
 830
 831        ret = percpu_ref_init(&sq->ref, nvmet_sq_free, 0, GFP_KERNEL);
 832        if (ret) {
 833                pr_err("percpu_ref init failed!\n");
 834                return ret;
 835        }
 836        init_completion(&sq->free_done);
 837        init_completion(&sq->confirm_done);
 838
 839        return 0;
 840}
 841EXPORT_SYMBOL_GPL(nvmet_sq_init);
 842
 843static inline u16 nvmet_check_ana_state(struct nvmet_port *port,
 844                struct nvmet_ns *ns)
 845{
 846        enum nvme_ana_state state = port->ana_state[ns->anagrpid];
 847
 848        if (unlikely(state == NVME_ANA_INACCESSIBLE))
 849                return NVME_SC_ANA_INACCESSIBLE;
 850        if (unlikely(state == NVME_ANA_PERSISTENT_LOSS))
 851                return NVME_SC_ANA_PERSISTENT_LOSS;
 852        if (unlikely(state == NVME_ANA_CHANGE))
 853                return NVME_SC_ANA_TRANSITION;
 854        return 0;
 855}
 856
 857static inline u16 nvmet_io_cmd_check_access(struct nvmet_req *req)
 858{
 859        if (unlikely(req->ns->readonly)) {
 860                switch (req->cmd->common.opcode) {
 861                case nvme_cmd_read:
 862                case nvme_cmd_flush:
 863                        break;
 864                default:
 865                        return NVME_SC_NS_WRITE_PROTECTED;
 866                }
 867        }
 868
 869        return 0;
 870}
 871
 872static u16 nvmet_parse_io_cmd(struct nvmet_req *req)
 873{
 874        struct nvme_command *cmd = req->cmd;
 875        u16 ret;
 876
 877        ret = nvmet_check_ctrl_status(req, cmd);
 878        if (unlikely(ret))
 879                return ret;
 880
 881        if (nvmet_req_passthru_ctrl(req))
 882                return nvmet_parse_passthru_io_cmd(req);
 883
 884        ret = nvmet_req_find_ns(req);
 885        if (unlikely(ret))
 886                return ret;
 887
 888        ret = nvmet_check_ana_state(req->port, req->ns);
 889        if (unlikely(ret)) {
 890                req->error_loc = offsetof(struct nvme_common_command, nsid);
 891                return ret;
 892        }
 893        ret = nvmet_io_cmd_check_access(req);
 894        if (unlikely(ret)) {
 895                req->error_loc = offsetof(struct nvme_common_command, nsid);
 896                return ret;
 897        }
 898
 899        if (req->ns->file)
 900                return nvmet_file_parse_io_cmd(req);
 901
 902        return nvmet_bdev_parse_io_cmd(req);
 903}
 904
 905bool nvmet_req_init(struct nvmet_req *req, struct nvmet_cq *cq,
 906                struct nvmet_sq *sq, const struct nvmet_fabrics_ops *ops)
 907{
 908        u8 flags = req->cmd->common.flags;
 909        u16 status;
 910
 911        req->cq = cq;
 912        req->sq = sq;
 913        req->ops = ops;
 914        req->sg = NULL;
 915        req->metadata_sg = NULL;
 916        req->sg_cnt = 0;
 917        req->metadata_sg_cnt = 0;
 918        req->transfer_len = 0;
 919        req->metadata_len = 0;
 920        req->cqe->status = 0;
 921        req->cqe->sq_head = 0;
 922        req->ns = NULL;
 923        req->error_loc = NVMET_NO_ERROR_LOC;
 924        req->error_slba = 0;
 925
 926        /* no support for fused commands yet */
 927        if (unlikely(flags & (NVME_CMD_FUSE_FIRST | NVME_CMD_FUSE_SECOND))) {
 928                req->error_loc = offsetof(struct nvme_common_command, flags);
 929                status = NVME_SC_INVALID_FIELD | NVME_SC_DNR;
 930                goto fail;
 931        }
 932
 933        /*
 934         * For fabrics, PSDT field shall describe metadata pointer (MPTR) that
 935         * contains an address of a single contiguous physical buffer that is
 936         * byte aligned.
 937         */
 938        if (unlikely((flags & NVME_CMD_SGL_ALL) != NVME_CMD_SGL_METABUF)) {
 939                req->error_loc = offsetof(struct nvme_common_command, flags);
 940                status = NVME_SC_INVALID_FIELD | NVME_SC_DNR;
 941                goto fail;
 942        }
 943
 944        if (unlikely(!req->sq->ctrl))
 945                /* will return an error for any non-connect command: */
 946                status = nvmet_parse_connect_cmd(req);
 947        else if (likely(req->sq->qid != 0))
 948                status = nvmet_parse_io_cmd(req);
 949        else
 950                status = nvmet_parse_admin_cmd(req);
 951
 952        if (status)
 953                goto fail;
 954
 955        trace_nvmet_req_init(req, req->cmd);
 956
 957        if (unlikely(!percpu_ref_tryget_live(&sq->ref))) {
 958                status = NVME_SC_INVALID_FIELD | NVME_SC_DNR;
 959                goto fail;
 960        }
 961
 962        if (sq->ctrl)
 963                sq->ctrl->cmd_seen = true;
 964
 965        return true;
 966
 967fail:
 968        __nvmet_req_complete(req, status);
 969        return false;
 970}
 971EXPORT_SYMBOL_GPL(nvmet_req_init);
 972
 973void nvmet_req_uninit(struct nvmet_req *req)
 974{
 975        percpu_ref_put(&req->sq->ref);
 976        if (req->ns)
 977                nvmet_put_namespace(req->ns);
 978}
 979EXPORT_SYMBOL_GPL(nvmet_req_uninit);
 980
 981bool nvmet_check_transfer_len(struct nvmet_req *req, size_t len)
 982{
 983        if (unlikely(len != req->transfer_len)) {
 984                req->error_loc = offsetof(struct nvme_common_command, dptr);
 985                nvmet_req_complete(req, NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR);
 986                return false;
 987        }
 988
 989        return true;
 990}
 991EXPORT_SYMBOL_GPL(nvmet_check_transfer_len);
 992
 993bool nvmet_check_data_len_lte(struct nvmet_req *req, size_t data_len)
 994{
 995        if (unlikely(data_len > req->transfer_len)) {
 996                req->error_loc = offsetof(struct nvme_common_command, dptr);
 997                nvmet_req_complete(req, NVME_SC_SGL_INVALID_DATA | NVME_SC_DNR);
 998                return false;
 999        }
1000
1001        return true;
1002}
1003
1004static unsigned int nvmet_data_transfer_len(struct nvmet_req *req)
1005{
1006        return req->transfer_len - req->metadata_len;
1007}
1008
1009static int nvmet_req_alloc_p2pmem_sgls(struct nvmet_req *req)
1010{
1011        req->sg = pci_p2pmem_alloc_sgl(req->p2p_dev, &req->sg_cnt,
1012                        nvmet_data_transfer_len(req));
1013        if (!req->sg)
1014                goto out_err;
1015
1016        if (req->metadata_len) {
1017                req->metadata_sg = pci_p2pmem_alloc_sgl(req->p2p_dev,
1018                                &req->metadata_sg_cnt, req->metadata_len);
1019                if (!req->metadata_sg)
1020                        goto out_free_sg;
1021        }
1022        return 0;
1023out_free_sg:
1024        pci_p2pmem_free_sgl(req->p2p_dev, req->sg);
1025out_err:
1026        return -ENOMEM;
1027}
1028
1029static bool nvmet_req_find_p2p_dev(struct nvmet_req *req)
1030{
1031        if (!IS_ENABLED(CONFIG_PCI_P2PDMA))
1032                return false;
1033
1034        if (req->sq->ctrl && req->sq->qid && req->ns) {
1035                req->p2p_dev = radix_tree_lookup(&req->sq->ctrl->p2p_ns_map,
1036                                                 req->ns->nsid);
1037                if (req->p2p_dev)
1038                        return true;
1039        }
1040
1041        req->p2p_dev = NULL;
1042        return false;
1043}
1044
1045int nvmet_req_alloc_sgls(struct nvmet_req *req)
1046{
1047        if (nvmet_req_find_p2p_dev(req) && !nvmet_req_alloc_p2pmem_sgls(req))
1048                return 0;
1049
1050        req->sg = sgl_alloc(nvmet_data_transfer_len(req), GFP_KERNEL,
1051                            &req->sg_cnt);
1052        if (unlikely(!req->sg))
1053                goto out;
1054
1055        if (req->metadata_len) {
1056                req->metadata_sg = sgl_alloc(req->metadata_len, GFP_KERNEL,
1057                                             &req->metadata_sg_cnt);
1058                if (unlikely(!req->metadata_sg))
1059                        goto out_free;
1060        }
1061
1062        return 0;
1063out_free:
1064        sgl_free(req->sg);
1065out:
1066        return -ENOMEM;
1067}
1068EXPORT_SYMBOL_GPL(nvmet_req_alloc_sgls);
1069
1070void nvmet_req_free_sgls(struct nvmet_req *req)
1071{
1072        if (req->p2p_dev) {
1073                pci_p2pmem_free_sgl(req->p2p_dev, req->sg);
1074                if (req->metadata_sg)
1075                        pci_p2pmem_free_sgl(req->p2p_dev, req->metadata_sg);
1076        } else {
1077                sgl_free(req->sg);
1078                if (req->metadata_sg)
1079                        sgl_free(req->metadata_sg);
1080        }
1081
1082        req->sg = NULL;
1083        req->metadata_sg = NULL;
1084        req->sg_cnt = 0;
1085        req->metadata_sg_cnt = 0;
1086}
1087EXPORT_SYMBOL_GPL(nvmet_req_free_sgls);
1088
1089static inline bool nvmet_cc_en(u32 cc)
1090{
1091        return (cc >> NVME_CC_EN_SHIFT) & 0x1;
1092}
1093
1094static inline u8 nvmet_cc_css(u32 cc)
1095{
1096        return (cc >> NVME_CC_CSS_SHIFT) & 0x7;
1097}
1098
1099static inline u8 nvmet_cc_mps(u32 cc)
1100{
1101        return (cc >> NVME_CC_MPS_SHIFT) & 0xf;
1102}
1103
1104static inline u8 nvmet_cc_ams(u32 cc)
1105{
1106        return (cc >> NVME_CC_AMS_SHIFT) & 0x7;
1107}
1108
1109static inline u8 nvmet_cc_shn(u32 cc)
1110{
1111        return (cc >> NVME_CC_SHN_SHIFT) & 0x3;
1112}
1113
1114static inline u8 nvmet_cc_iosqes(u32 cc)
1115{
1116        return (cc >> NVME_CC_IOSQES_SHIFT) & 0xf;
1117}
1118
1119static inline u8 nvmet_cc_iocqes(u32 cc)
1120{
1121        return (cc >> NVME_CC_IOCQES_SHIFT) & 0xf;
1122}
1123
1124static void nvmet_start_ctrl(struct nvmet_ctrl *ctrl)
1125{
1126        lockdep_assert_held(&ctrl->lock);
1127
1128        if (nvmet_cc_iosqes(ctrl->cc) != NVME_NVM_IOSQES ||
1129            nvmet_cc_iocqes(ctrl->cc) != NVME_NVM_IOCQES ||
1130            nvmet_cc_mps(ctrl->cc) != 0 ||
1131            nvmet_cc_ams(ctrl->cc) != 0 ||
1132            nvmet_cc_css(ctrl->cc) != 0) {
1133                ctrl->csts = NVME_CSTS_CFS;
1134                return;
1135        }
1136
1137        ctrl->csts = NVME_CSTS_RDY;
1138
1139        /*
1140         * Controllers that are not yet enabled should not really enforce the
1141         * keep alive timeout, but we still want to track a timeout and cleanup
1142         * in case a host died before it enabled the controller.  Hence, simply
1143         * reset the keep alive timer when the controller is enabled.
1144         */
1145        if (ctrl->kato)
1146                mod_delayed_work(system_wq, &ctrl->ka_work, ctrl->kato * HZ);
1147}
1148
1149static void nvmet_clear_ctrl(struct nvmet_ctrl *ctrl)
1150{
1151        lockdep_assert_held(&ctrl->lock);
1152
1153        /* XXX: tear down queues? */
1154        ctrl->csts &= ~NVME_CSTS_RDY;
1155        ctrl->cc = 0;
1156}
1157
1158void nvmet_update_cc(struct nvmet_ctrl *ctrl, u32 new)
1159{
1160        u32 old;
1161
1162        mutex_lock(&ctrl->lock);
1163        old = ctrl->cc;
1164        ctrl->cc = new;
1165
1166        if (nvmet_cc_en(new) && !nvmet_cc_en(old))
1167                nvmet_start_ctrl(ctrl);
1168        if (!nvmet_cc_en(new) && nvmet_cc_en(old))
1169                nvmet_clear_ctrl(ctrl);
1170        if (nvmet_cc_shn(new) && !nvmet_cc_shn(old)) {
1171                nvmet_clear_ctrl(ctrl);
1172                ctrl->csts |= NVME_CSTS_SHST_CMPLT;
1173        }
1174        if (!nvmet_cc_shn(new) && nvmet_cc_shn(old))
1175                ctrl->csts &= ~NVME_CSTS_SHST_CMPLT;
1176        mutex_unlock(&ctrl->lock);
1177}
1178
1179static void nvmet_init_cap(struct nvmet_ctrl *ctrl)
1180{
1181        /* command sets supported: NVMe command set: */
1182        ctrl->cap = (1ULL << 37);
1183        /* CC.EN timeout in 500msec units: */
1184        ctrl->cap |= (15ULL << 24);
1185        /* maximum queue entries supported: */
1186        ctrl->cap |= NVMET_QUEUE_SIZE - 1;
1187}
1188
1189u16 nvmet_ctrl_find_get(const char *subsysnqn, const char *hostnqn, u16 cntlid,
1190                struct nvmet_req *req, struct nvmet_ctrl **ret)
1191{
1192        struct nvmet_subsys *subsys;
1193        struct nvmet_ctrl *ctrl;
1194        u16 status = 0;
1195
1196        subsys = nvmet_find_get_subsys(req->port, subsysnqn);
1197        if (!subsys) {
1198                pr_warn("connect request for invalid subsystem %s!\n",
1199                        subsysnqn);
1200                req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(subsysnqn);
1201                return NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR;
1202        }
1203
1204        mutex_lock(&subsys->lock);
1205        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
1206                if (ctrl->cntlid == cntlid) {
1207                        if (strncmp(hostnqn, ctrl->hostnqn, NVMF_NQN_SIZE)) {
1208                                pr_warn("hostnqn mismatch.\n");
1209                                continue;
1210                        }
1211                        if (!kref_get_unless_zero(&ctrl->ref))
1212                                continue;
1213
1214                        *ret = ctrl;
1215                        goto out;
1216                }
1217        }
1218
1219        pr_warn("could not find controller %d for subsys %s / host %s\n",
1220                cntlid, subsysnqn, hostnqn);
1221        req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(cntlid);
1222        status = NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR;
1223
1224out:
1225        mutex_unlock(&subsys->lock);
1226        nvmet_subsys_put(subsys);
1227        return status;
1228}
1229
1230u16 nvmet_check_ctrl_status(struct nvmet_req *req, struct nvme_command *cmd)
1231{
1232        if (unlikely(!(req->sq->ctrl->cc & NVME_CC_ENABLE))) {
1233                pr_err("got cmd %d while CC.EN == 0 on qid = %d\n",
1234                       cmd->common.opcode, req->sq->qid);
1235                return NVME_SC_CMD_SEQ_ERROR | NVME_SC_DNR;
1236        }
1237
1238        if (unlikely(!(req->sq->ctrl->csts & NVME_CSTS_RDY))) {
1239                pr_err("got cmd %d while CSTS.RDY == 0 on qid = %d\n",
1240                       cmd->common.opcode, req->sq->qid);
1241                return NVME_SC_CMD_SEQ_ERROR | NVME_SC_DNR;
1242        }
1243        return 0;
1244}
1245
1246bool nvmet_host_allowed(struct nvmet_subsys *subsys, const char *hostnqn)
1247{
1248        struct nvmet_host_link *p;
1249
1250        lockdep_assert_held(&nvmet_config_sem);
1251
1252        if (subsys->allow_any_host)
1253                return true;
1254
1255        if (subsys->type == NVME_NQN_DISC) /* allow all access to disc subsys */
1256                return true;
1257
1258        list_for_each_entry(p, &subsys->hosts, entry) {
1259                if (!strcmp(nvmet_host_name(p->host), hostnqn))
1260                        return true;
1261        }
1262
1263        return false;
1264}
1265
1266/*
1267 * Note: ctrl->subsys->lock should be held when calling this function
1268 */
1269static void nvmet_setup_p2p_ns_map(struct nvmet_ctrl *ctrl,
1270                struct nvmet_req *req)
1271{
1272        struct nvmet_ns *ns;
1273        unsigned long idx;
1274
1275        if (!req->p2p_client)
1276                return;
1277
1278        ctrl->p2p_client = get_device(req->p2p_client);
1279
1280        xa_for_each(&ctrl->subsys->namespaces, idx, ns)
1281                nvmet_p2pmem_ns_add_p2p(ctrl, ns);
1282}
1283
1284/*
1285 * Note: ctrl->subsys->lock should be held when calling this function
1286 */
1287static void nvmet_release_p2p_ns_map(struct nvmet_ctrl *ctrl)
1288{
1289        struct radix_tree_iter iter;
1290        void __rcu **slot;
1291
1292        radix_tree_for_each_slot(slot, &ctrl->p2p_ns_map, &iter, 0)
1293                pci_dev_put(radix_tree_deref_slot(slot));
1294
1295        put_device(ctrl->p2p_client);
1296}
1297
1298static void nvmet_fatal_error_handler(struct work_struct *work)
1299{
1300        struct nvmet_ctrl *ctrl =
1301                        container_of(work, struct nvmet_ctrl, fatal_err_work);
1302
1303        pr_err("ctrl %d fatal error occurred!\n", ctrl->cntlid);
1304        ctrl->ops->delete_ctrl(ctrl);
1305}
1306
1307u16 nvmet_alloc_ctrl(const char *subsysnqn, const char *hostnqn,
1308                struct nvmet_req *req, u32 kato, struct nvmet_ctrl **ctrlp)
1309{
1310        struct nvmet_subsys *subsys;
1311        struct nvmet_ctrl *ctrl;
1312        int ret;
1313        u16 status;
1314
1315        status = NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR;
1316        subsys = nvmet_find_get_subsys(req->port, subsysnqn);
1317        if (!subsys) {
1318                pr_warn("connect request for invalid subsystem %s!\n",
1319                        subsysnqn);
1320                req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(subsysnqn);
1321                goto out;
1322        }
1323
1324        status = NVME_SC_CONNECT_INVALID_PARAM | NVME_SC_DNR;
1325        down_read(&nvmet_config_sem);
1326        if (!nvmet_host_allowed(subsys, hostnqn)) {
1327                pr_info("connect by host %s for subsystem %s not allowed\n",
1328                        hostnqn, subsysnqn);
1329                req->cqe->result.u32 = IPO_IATTR_CONNECT_DATA(hostnqn);
1330                up_read(&nvmet_config_sem);
1331                status = NVME_SC_CONNECT_INVALID_HOST | NVME_SC_DNR;
1332                goto out_put_subsystem;
1333        }
1334        up_read(&nvmet_config_sem);
1335
1336        status = NVME_SC_INTERNAL;
1337        ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
1338        if (!ctrl)
1339                goto out_put_subsystem;
1340        mutex_init(&ctrl->lock);
1341
1342        nvmet_init_cap(ctrl);
1343
1344        ctrl->port = req->port;
1345
1346        INIT_WORK(&ctrl->async_event_work, nvmet_async_event_work);
1347        INIT_LIST_HEAD(&ctrl->async_events);
1348        INIT_RADIX_TREE(&ctrl->p2p_ns_map, GFP_KERNEL);
1349        INIT_WORK(&ctrl->fatal_err_work, nvmet_fatal_error_handler);
1350
1351        memcpy(ctrl->subsysnqn, subsysnqn, NVMF_NQN_SIZE);
1352        memcpy(ctrl->hostnqn, hostnqn, NVMF_NQN_SIZE);
1353
1354        kref_init(&ctrl->ref);
1355        ctrl->subsys = subsys;
1356        WRITE_ONCE(ctrl->aen_enabled, NVMET_AEN_CFG_OPTIONAL);
1357
1358        ctrl->changed_ns_list = kmalloc_array(NVME_MAX_CHANGED_NAMESPACES,
1359                        sizeof(__le32), GFP_KERNEL);
1360        if (!ctrl->changed_ns_list)
1361                goto out_free_ctrl;
1362
1363        ctrl->sqs = kcalloc(subsys->max_qid + 1,
1364                        sizeof(struct nvmet_sq *),
1365                        GFP_KERNEL);
1366        if (!ctrl->sqs)
1367                goto out_free_changed_ns_list;
1368
1369        if (subsys->cntlid_min > subsys->cntlid_max)
1370                goto out_free_changed_ns_list;
1371
1372        ret = ida_simple_get(&cntlid_ida,
1373                             subsys->cntlid_min, subsys->cntlid_max,
1374                             GFP_KERNEL);
1375        if (ret < 0) {
1376                status = NVME_SC_CONNECT_CTRL_BUSY | NVME_SC_DNR;
1377                goto out_free_sqs;
1378        }
1379        ctrl->cntlid = ret;
1380
1381        ctrl->ops = req->ops;
1382
1383        /*
1384         * Discovery controllers may use some arbitrary high value
1385         * in order to cleanup stale discovery sessions
1386         */
1387        if ((ctrl->subsys->type == NVME_NQN_DISC) && !kato)
1388                kato = NVMET_DISC_KATO_MS;
1389
1390        /* keep-alive timeout in seconds */
1391        ctrl->kato = DIV_ROUND_UP(kato, 1000);
1392
1393        ctrl->err_counter = 0;
1394        spin_lock_init(&ctrl->error_lock);
1395
1396        nvmet_start_keep_alive_timer(ctrl);
1397
1398        mutex_lock(&subsys->lock);
1399        list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
1400        nvmet_setup_p2p_ns_map(ctrl, req);
1401        mutex_unlock(&subsys->lock);
1402
1403        *ctrlp = ctrl;
1404        return 0;
1405
1406out_free_sqs:
1407        kfree(ctrl->sqs);
1408out_free_changed_ns_list:
1409        kfree(ctrl->changed_ns_list);
1410out_free_ctrl:
1411        kfree(ctrl);
1412out_put_subsystem:
1413        nvmet_subsys_put(subsys);
1414out:
1415        return status;
1416}
1417
1418static void nvmet_ctrl_free(struct kref *ref)
1419{
1420        struct nvmet_ctrl *ctrl = container_of(ref, struct nvmet_ctrl, ref);
1421        struct nvmet_subsys *subsys = ctrl->subsys;
1422
1423        mutex_lock(&subsys->lock);
1424        nvmet_release_p2p_ns_map(ctrl);
1425        list_del(&ctrl->subsys_entry);
1426        mutex_unlock(&subsys->lock);
1427
1428        nvmet_stop_keep_alive_timer(ctrl);
1429
1430        flush_work(&ctrl->async_event_work);
1431        cancel_work_sync(&ctrl->fatal_err_work);
1432
1433        ida_simple_remove(&cntlid_ida, ctrl->cntlid);
1434
1435        nvmet_async_events_free(ctrl);
1436        kfree(ctrl->sqs);
1437        kfree(ctrl->changed_ns_list);
1438        kfree(ctrl);
1439
1440        nvmet_subsys_put(subsys);
1441}
1442
1443void nvmet_ctrl_put(struct nvmet_ctrl *ctrl)
1444{
1445        kref_put(&ctrl->ref, nvmet_ctrl_free);
1446}
1447
1448void nvmet_ctrl_fatal_error(struct nvmet_ctrl *ctrl)
1449{
1450        mutex_lock(&ctrl->lock);
1451        if (!(ctrl->csts & NVME_CSTS_CFS)) {
1452                ctrl->csts |= NVME_CSTS_CFS;
1453                schedule_work(&ctrl->fatal_err_work);
1454        }
1455        mutex_unlock(&ctrl->lock);
1456}
1457EXPORT_SYMBOL_GPL(nvmet_ctrl_fatal_error);
1458
1459static struct nvmet_subsys *nvmet_find_get_subsys(struct nvmet_port *port,
1460                const char *subsysnqn)
1461{
1462        struct nvmet_subsys_link *p;
1463
1464        if (!port)
1465                return NULL;
1466
1467        if (!strcmp(NVME_DISC_SUBSYS_NAME, subsysnqn)) {
1468                if (!kref_get_unless_zero(&nvmet_disc_subsys->ref))
1469                        return NULL;
1470                return nvmet_disc_subsys;
1471        }
1472
1473        down_read(&nvmet_config_sem);
1474        list_for_each_entry(p, &port->subsystems, entry) {
1475                if (!strncmp(p->subsys->subsysnqn, subsysnqn,
1476                                NVMF_NQN_SIZE)) {
1477                        if (!kref_get_unless_zero(&p->subsys->ref))
1478                                break;
1479                        up_read(&nvmet_config_sem);
1480                        return p->subsys;
1481                }
1482        }
1483        up_read(&nvmet_config_sem);
1484        return NULL;
1485}
1486
1487struct nvmet_subsys *nvmet_subsys_alloc(const char *subsysnqn,
1488                enum nvme_subsys_type type)
1489{
1490        struct nvmet_subsys *subsys;
1491
1492        subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
1493        if (!subsys)
1494                return ERR_PTR(-ENOMEM);
1495
1496        subsys->ver = NVMET_DEFAULT_VS;
1497        /* generate a random serial number as our controllers are ephemeral: */
1498        get_random_bytes(&subsys->serial, sizeof(subsys->serial));
1499
1500        switch (type) {
1501        case NVME_NQN_NVME:
1502                subsys->max_qid = NVMET_NR_QUEUES;
1503                break;
1504        case NVME_NQN_DISC:
1505                subsys->max_qid = 0;
1506                break;
1507        default:
1508                pr_err("%s: Unknown Subsystem type - %d\n", __func__, type);
1509                kfree(subsys);
1510                return ERR_PTR(-EINVAL);
1511        }
1512        subsys->type = type;
1513        subsys->subsysnqn = kstrndup(subsysnqn, NVMF_NQN_SIZE,
1514                        GFP_KERNEL);
1515        if (!subsys->subsysnqn) {
1516                kfree(subsys);
1517                return ERR_PTR(-ENOMEM);
1518        }
1519        subsys->cntlid_min = NVME_CNTLID_MIN;
1520        subsys->cntlid_max = NVME_CNTLID_MAX;
1521        kref_init(&subsys->ref);
1522
1523        mutex_init(&subsys->lock);
1524        xa_init(&subsys->namespaces);
1525        INIT_LIST_HEAD(&subsys->ctrls);
1526        INIT_LIST_HEAD(&subsys->hosts);
1527
1528        return subsys;
1529}
1530
1531static void nvmet_subsys_free(struct kref *ref)
1532{
1533        struct nvmet_subsys *subsys =
1534                container_of(ref, struct nvmet_subsys, ref);
1535
1536        WARN_ON_ONCE(!xa_empty(&subsys->namespaces));
1537
1538        xa_destroy(&subsys->namespaces);
1539        nvmet_passthru_subsys_free(subsys);
1540
1541        kfree(subsys->subsysnqn);
1542        kfree(subsys->model_number);
1543        kfree(subsys);
1544}
1545
1546void nvmet_subsys_del_ctrls(struct nvmet_subsys *subsys)
1547{
1548        struct nvmet_ctrl *ctrl;
1549
1550        mutex_lock(&subsys->lock);
1551        list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
1552                ctrl->ops->delete_ctrl(ctrl);
1553        mutex_unlock(&subsys->lock);
1554}
1555
1556void nvmet_subsys_put(struct nvmet_subsys *subsys)
1557{
1558        kref_put(&subsys->ref, nvmet_subsys_free);
1559}
1560
1561static int __init nvmet_init(void)
1562{
1563        int error;
1564
1565        nvmet_ana_group_enabled[NVMET_DEFAULT_ANA_GRPID] = 1;
1566
1567        buffered_io_wq = alloc_workqueue("nvmet-buffered-io-wq",
1568                        WQ_MEM_RECLAIM, 0);
1569        if (!buffered_io_wq) {
1570                error = -ENOMEM;
1571                goto out;
1572        }
1573
1574        error = nvmet_init_discovery();
1575        if (error)
1576                goto out_free_work_queue;
1577
1578        error = nvmet_init_configfs();
1579        if (error)
1580                goto out_exit_discovery;
1581        return 0;
1582
1583out_exit_discovery:
1584        nvmet_exit_discovery();
1585out_free_work_queue:
1586        destroy_workqueue(buffered_io_wq);
1587out:
1588        return error;
1589}
1590
1591static void __exit nvmet_exit(void)
1592{
1593        nvmet_exit_configfs();
1594        nvmet_exit_discovery();
1595        ida_destroy(&cntlid_ida);
1596        destroy_workqueue(buffered_io_wq);
1597
1598        BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_entry) != 1024);
1599        BUILD_BUG_ON(sizeof(struct nvmf_disc_rsp_page_hdr) != 1024);
1600}
1601
1602module_init(nvmet_init);
1603module_exit(nvmet_exit);
1604
1605MODULE_LICENSE("GPL v2");
1606