linux/drivers/target/target_core_transport.c
<<
>>
Prefs
   1/*******************************************************************************
   2 * Filename:  target_core_transport.c
   3 *
   4 * This file contains the Generic Target Engine Core.
   5 *
   6 * Copyright (c) 2002, 2003, 2004, 2005 PyX Technologies, Inc.
   7 * Copyright (c) 2005, 2006, 2007 SBE, Inc.
   8 * Copyright (c) 2007-2010 Rising Tide Systems
   9 * Copyright (c) 2008-2010 Linux-iSCSI.org
  10 *
  11 * Nicholas A. Bellinger <nab@kernel.org>
  12 *
  13 * This program is free software; you can redistribute it and/or modify
  14 * it under the terms of the GNU General Public License as published by
  15 * the Free Software Foundation; either version 2 of the License, or
  16 * (at your option) any later version.
  17 *
  18 * This program is distributed in the hope that it will be useful,
  19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  21 * GNU General Public License for more details.
  22 *
  23 * You should have received a copy of the GNU General Public License
  24 * along with this program; if not, write to the Free Software
  25 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  26 *
  27 ******************************************************************************/
  28
  29#include <linux/net.h>
  30#include <linux/delay.h>
  31#include <linux/string.h>
  32#include <linux/timer.h>
  33#include <linux/slab.h>
  34#include <linux/blkdev.h>
  35#include <linux/spinlock.h>
  36#include <linux/kthread.h>
  37#include <linux/in.h>
  38#include <linux/cdrom.h>
  39#include <linux/module.h>
  40#include <linux/ratelimit.h>
  41#include <asm/unaligned.h>
  42#include <net/sock.h>
  43#include <net/tcp.h>
  44#include <scsi/scsi.h>
  45#include <scsi/scsi_cmnd.h>
  46#include <scsi/scsi_tcq.h>
  47
  48#include <target/target_core_base.h>
  49#include <target/target_core_backend.h>
  50#include <target/target_core_fabric.h>
  51#include <target/target_core_configfs.h>
  52
  53#include "target_core_internal.h"
  54#include "target_core_alua.h"
  55#include "target_core_pr.h"
  56#include "target_core_ua.h"
  57
  58static int sub_api_initialized;
  59
  60static struct workqueue_struct *target_completion_wq;
  61static struct kmem_cache *se_sess_cache;
  62struct kmem_cache *se_ua_cache;
  63struct kmem_cache *t10_pr_reg_cache;
  64struct kmem_cache *t10_alua_lu_gp_cache;
  65struct kmem_cache *t10_alua_lu_gp_mem_cache;
  66struct kmem_cache *t10_alua_tg_pt_gp_cache;
  67struct kmem_cache *t10_alua_tg_pt_gp_mem_cache;
  68
  69static void transport_complete_task_attr(struct se_cmd *cmd);
  70static void transport_handle_queue_full(struct se_cmd *cmd,
  71                struct se_device *dev);
  72static int transport_generic_get_mem(struct se_cmd *cmd);
  73static int target_get_sess_cmd(struct se_session *, struct se_cmd *, bool);
  74static void transport_put_cmd(struct se_cmd *cmd);
  75static int transport_set_sense_codes(struct se_cmd *cmd, u8 asc, u8 ascq);
  76static void target_complete_ok_work(struct work_struct *work);
  77
  78int init_se_kmem_caches(void)
  79{
  80        se_sess_cache = kmem_cache_create("se_sess_cache",
  81                        sizeof(struct se_session), __alignof__(struct se_session),
  82                        0, NULL);
  83        if (!se_sess_cache) {
  84                pr_err("kmem_cache_create() for struct se_session"
  85                                " failed\n");
  86                goto out;
  87        }
  88        se_ua_cache = kmem_cache_create("se_ua_cache",
  89                        sizeof(struct se_ua), __alignof__(struct se_ua),
  90                        0, NULL);
  91        if (!se_ua_cache) {
  92                pr_err("kmem_cache_create() for struct se_ua failed\n");
  93                goto out_free_sess_cache;
  94        }
  95        t10_pr_reg_cache = kmem_cache_create("t10_pr_reg_cache",
  96                        sizeof(struct t10_pr_registration),
  97                        __alignof__(struct t10_pr_registration), 0, NULL);
  98        if (!t10_pr_reg_cache) {
  99                pr_err("kmem_cache_create() for struct t10_pr_registration"
 100                                " failed\n");
 101                goto out_free_ua_cache;
 102        }
 103        t10_alua_lu_gp_cache = kmem_cache_create("t10_alua_lu_gp_cache",
 104                        sizeof(struct t10_alua_lu_gp), __alignof__(struct t10_alua_lu_gp),
 105                        0, NULL);
 106        if (!t10_alua_lu_gp_cache) {
 107                pr_err("kmem_cache_create() for t10_alua_lu_gp_cache"
 108                                " failed\n");
 109                goto out_free_pr_reg_cache;
 110        }
 111        t10_alua_lu_gp_mem_cache = kmem_cache_create("t10_alua_lu_gp_mem_cache",
 112                        sizeof(struct t10_alua_lu_gp_member),
 113                        __alignof__(struct t10_alua_lu_gp_member), 0, NULL);
 114        if (!t10_alua_lu_gp_mem_cache) {
 115                pr_err("kmem_cache_create() for t10_alua_lu_gp_mem_"
 116                                "cache failed\n");
 117                goto out_free_lu_gp_cache;
 118        }
 119        t10_alua_tg_pt_gp_cache = kmem_cache_create("t10_alua_tg_pt_gp_cache",
 120                        sizeof(struct t10_alua_tg_pt_gp),
 121                        __alignof__(struct t10_alua_tg_pt_gp), 0, NULL);
 122        if (!t10_alua_tg_pt_gp_cache) {
 123                pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
 124                                "cache failed\n");
 125                goto out_free_lu_gp_mem_cache;
 126        }
 127        t10_alua_tg_pt_gp_mem_cache = kmem_cache_create(
 128                        "t10_alua_tg_pt_gp_mem_cache",
 129                        sizeof(struct t10_alua_tg_pt_gp_member),
 130                        __alignof__(struct t10_alua_tg_pt_gp_member),
 131                        0, NULL);
 132        if (!t10_alua_tg_pt_gp_mem_cache) {
 133                pr_err("kmem_cache_create() for t10_alua_tg_pt_gp_"
 134                                "mem_t failed\n");
 135                goto out_free_tg_pt_gp_cache;
 136        }
 137
 138        target_completion_wq = alloc_workqueue("target_completion",
 139                                               WQ_MEM_RECLAIM, 0);
 140        if (!target_completion_wq)
 141                goto out_free_tg_pt_gp_mem_cache;
 142
 143        return 0;
 144
 145out_free_tg_pt_gp_mem_cache:
 146        kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
 147out_free_tg_pt_gp_cache:
 148        kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
 149out_free_lu_gp_mem_cache:
 150        kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
 151out_free_lu_gp_cache:
 152        kmem_cache_destroy(t10_alua_lu_gp_cache);
 153out_free_pr_reg_cache:
 154        kmem_cache_destroy(t10_pr_reg_cache);
 155out_free_ua_cache:
 156        kmem_cache_destroy(se_ua_cache);
 157out_free_sess_cache:
 158        kmem_cache_destroy(se_sess_cache);
 159out:
 160        return -ENOMEM;
 161}
 162
 163void release_se_kmem_caches(void)
 164{
 165        destroy_workqueue(target_completion_wq);
 166        kmem_cache_destroy(se_sess_cache);
 167        kmem_cache_destroy(se_ua_cache);
 168        kmem_cache_destroy(t10_pr_reg_cache);
 169        kmem_cache_destroy(t10_alua_lu_gp_cache);
 170        kmem_cache_destroy(t10_alua_lu_gp_mem_cache);
 171        kmem_cache_destroy(t10_alua_tg_pt_gp_cache);
 172        kmem_cache_destroy(t10_alua_tg_pt_gp_mem_cache);
 173}
 174
 175/* This code ensures unique mib indexes are handed out. */
 176static DEFINE_SPINLOCK(scsi_mib_index_lock);
 177static u32 scsi_mib_index[SCSI_INDEX_TYPE_MAX];
 178
 179/*
 180 * Allocate a new row index for the entry type specified
 181 */
 182u32 scsi_get_new_index(scsi_index_t type)
 183{
 184        u32 new_index;
 185
 186        BUG_ON((type < 0) || (type >= SCSI_INDEX_TYPE_MAX));
 187
 188        spin_lock(&scsi_mib_index_lock);
 189        new_index = ++scsi_mib_index[type];
 190        spin_unlock(&scsi_mib_index_lock);
 191
 192        return new_index;
 193}
 194
 195void transport_subsystem_check_init(void)
 196{
 197        int ret;
 198
 199        if (sub_api_initialized)
 200                return;
 201
 202        ret = request_module("target_core_iblock");
 203        if (ret != 0)
 204                pr_err("Unable to load target_core_iblock\n");
 205
 206        ret = request_module("target_core_file");
 207        if (ret != 0)
 208                pr_err("Unable to load target_core_file\n");
 209
 210        ret = request_module("target_core_pscsi");
 211        if (ret != 0)
 212                pr_err("Unable to load target_core_pscsi\n");
 213
 214        ret = request_module("target_core_stgt");
 215        if (ret != 0)
 216                pr_err("Unable to load target_core_stgt\n");
 217
 218        sub_api_initialized = 1;
 219        return;
 220}
 221
 222struct se_session *transport_init_session(void)
 223{
 224        struct se_session *se_sess;
 225
 226        se_sess = kmem_cache_zalloc(se_sess_cache, GFP_KERNEL);
 227        if (!se_sess) {
 228                pr_err("Unable to allocate struct se_session from"
 229                                " se_sess_cache\n");
 230                return ERR_PTR(-ENOMEM);
 231        }
 232        INIT_LIST_HEAD(&se_sess->sess_list);
 233        INIT_LIST_HEAD(&se_sess->sess_acl_list);
 234        INIT_LIST_HEAD(&se_sess->sess_cmd_list);
 235        spin_lock_init(&se_sess->sess_cmd_lock);
 236        kref_init(&se_sess->sess_kref);
 237
 238        return se_sess;
 239}
 240EXPORT_SYMBOL(transport_init_session);
 241
 242/*
 243 * Called with spin_lock_irqsave(&struct se_portal_group->session_lock called.
 244 */
 245void __transport_register_session(
 246        struct se_portal_group *se_tpg,
 247        struct se_node_acl *se_nacl,
 248        struct se_session *se_sess,
 249        void *fabric_sess_ptr)
 250{
 251        unsigned char buf[PR_REG_ISID_LEN];
 252
 253        se_sess->se_tpg = se_tpg;
 254        se_sess->fabric_sess_ptr = fabric_sess_ptr;
 255        /*
 256         * Used by struct se_node_acl's under ConfigFS to locate active se_session-t
 257         *
 258         * Only set for struct se_session's that will actually be moving I/O.
 259         * eg: *NOT* discovery sessions.
 260         */
 261        if (se_nacl) {
 262                /*
 263                 * If the fabric module supports an ISID based TransportID,
 264                 * save this value in binary from the fabric I_T Nexus now.
 265                 */
 266                if (se_tpg->se_tpg_tfo->sess_get_initiator_sid != NULL) {
 267                        memset(&buf[0], 0, PR_REG_ISID_LEN);
 268                        se_tpg->se_tpg_tfo->sess_get_initiator_sid(se_sess,
 269                                        &buf[0], PR_REG_ISID_LEN);
 270                        se_sess->sess_bin_isid = get_unaligned_be64(&buf[0]);
 271                }
 272                kref_get(&se_nacl->acl_kref);
 273
 274                spin_lock_irq(&se_nacl->nacl_sess_lock);
 275                /*
 276                 * The se_nacl->nacl_sess pointer will be set to the
 277                 * last active I_T Nexus for each struct se_node_acl.
 278                 */
 279                se_nacl->nacl_sess = se_sess;
 280
 281                list_add_tail(&se_sess->sess_acl_list,
 282                              &se_nacl->acl_sess_list);
 283                spin_unlock_irq(&se_nacl->nacl_sess_lock);
 284        }
 285        list_add_tail(&se_sess->sess_list, &se_tpg->tpg_sess_list);
 286
 287        pr_debug("TARGET_CORE[%s]: Registered fabric_sess_ptr: %p\n",
 288                se_tpg->se_tpg_tfo->get_fabric_name(), se_sess->fabric_sess_ptr);
 289}
 290EXPORT_SYMBOL(__transport_register_session);
 291
 292void transport_register_session(
 293        struct se_portal_group *se_tpg,
 294        struct se_node_acl *se_nacl,
 295        struct se_session *se_sess,
 296        void *fabric_sess_ptr)
 297{
 298        unsigned long flags;
 299
 300        spin_lock_irqsave(&se_tpg->session_lock, flags);
 301        __transport_register_session(se_tpg, se_nacl, se_sess, fabric_sess_ptr);
 302        spin_unlock_irqrestore(&se_tpg->session_lock, flags);
 303}
 304EXPORT_SYMBOL(transport_register_session);
 305
 306void target_release_session(struct kref *kref)
 307{
 308        struct se_session *se_sess = container_of(kref,
 309                        struct se_session, sess_kref);
 310        struct se_portal_group *se_tpg = se_sess->se_tpg;
 311
 312        se_tpg->se_tpg_tfo->close_session(se_sess);
 313}
 314
 315void target_get_session(struct se_session *se_sess)
 316{
 317        kref_get(&se_sess->sess_kref);
 318}
 319EXPORT_SYMBOL(target_get_session);
 320
 321void target_put_session(struct se_session *se_sess)
 322{
 323        struct se_portal_group *tpg = se_sess->se_tpg;
 324
 325        if (tpg->se_tpg_tfo->put_session != NULL) {
 326                tpg->se_tpg_tfo->put_session(se_sess);
 327                return;
 328        }
 329        kref_put(&se_sess->sess_kref, target_release_session);
 330}
 331EXPORT_SYMBOL(target_put_session);
 332
 333static void target_complete_nacl(struct kref *kref)
 334{
 335        struct se_node_acl *nacl = container_of(kref,
 336                                struct se_node_acl, acl_kref);
 337
 338        complete(&nacl->acl_free_comp);
 339}
 340
 341void target_put_nacl(struct se_node_acl *nacl)
 342{
 343        kref_put(&nacl->acl_kref, target_complete_nacl);
 344}
 345
 346void transport_deregister_session_configfs(struct se_session *se_sess)
 347{
 348        struct se_node_acl *se_nacl;
 349        unsigned long flags;
 350        /*
 351         * Used by struct se_node_acl's under ConfigFS to locate active struct se_session
 352         */
 353        se_nacl = se_sess->se_node_acl;
 354        if (se_nacl) {
 355                spin_lock_irqsave(&se_nacl->nacl_sess_lock, flags);
 356                if (se_nacl->acl_stop == 0)
 357                        list_del(&se_sess->sess_acl_list);
 358                /*
 359                 * If the session list is empty, then clear the pointer.
 360                 * Otherwise, set the struct se_session pointer from the tail
 361                 * element of the per struct se_node_acl active session list.
 362                 */
 363                if (list_empty(&se_nacl->acl_sess_list))
 364                        se_nacl->nacl_sess = NULL;
 365                else {
 366                        se_nacl->nacl_sess = container_of(
 367                                        se_nacl->acl_sess_list.prev,
 368                                        struct se_session, sess_acl_list);
 369                }
 370                spin_unlock_irqrestore(&se_nacl->nacl_sess_lock, flags);
 371        }
 372}
 373EXPORT_SYMBOL(transport_deregister_session_configfs);
 374
 375void transport_free_session(struct se_session *se_sess)
 376{
 377        kmem_cache_free(se_sess_cache, se_sess);
 378}
 379EXPORT_SYMBOL(transport_free_session);
 380
 381void transport_deregister_session(struct se_session *se_sess)
 382{
 383        struct se_portal_group *se_tpg = se_sess->se_tpg;
 384        struct target_core_fabric_ops *se_tfo;
 385        struct se_node_acl *se_nacl;
 386        unsigned long flags;
 387        bool comp_nacl = true;
 388
 389        if (!se_tpg) {
 390                transport_free_session(se_sess);
 391                return;
 392        }
 393        se_tfo = se_tpg->se_tpg_tfo;
 394
 395        spin_lock_irqsave(&se_tpg->session_lock, flags);
 396        list_del(&se_sess->sess_list);
 397        se_sess->se_tpg = NULL;
 398        se_sess->fabric_sess_ptr = NULL;
 399        spin_unlock_irqrestore(&se_tpg->session_lock, flags);
 400
 401        /*
 402         * Determine if we need to do extra work for this initiator node's
 403         * struct se_node_acl if it had been previously dynamically generated.
 404         */
 405        se_nacl = se_sess->se_node_acl;
 406
 407        spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
 408        if (se_nacl && se_nacl->dynamic_node_acl) {
 409                if (!se_tfo->tpg_check_demo_mode_cache(se_tpg)) {
 410                        list_del(&se_nacl->acl_list);
 411                        se_tpg->num_node_acls--;
 412                        spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
 413                        core_tpg_wait_for_nacl_pr_ref(se_nacl);
 414                        core_free_device_list_for_node(se_nacl, se_tpg);
 415                        se_tfo->tpg_release_fabric_acl(se_tpg, se_nacl);
 416
 417                        comp_nacl = false;
 418                        spin_lock_irqsave(&se_tpg->acl_node_lock, flags);
 419                }
 420        }
 421        spin_unlock_irqrestore(&se_tpg->acl_node_lock, flags);
 422
 423        pr_debug("TARGET_CORE[%s]: Deregistered fabric_sess\n",
 424                se_tpg->se_tpg_tfo->get_fabric_name());
 425        /*
 426         * If last kref is dropping now for an explict NodeACL, awake sleeping
 427         * ->acl_free_comp caller to wakeup configfs se_node_acl->acl_group
 428         * removal context.
 429         */
 430        if (se_nacl && comp_nacl == true)
 431                target_put_nacl(se_nacl);
 432
 433        transport_free_session(se_sess);
 434}
 435EXPORT_SYMBOL(transport_deregister_session);
 436
 437/*
 438 * Called with cmd->t_state_lock held.
 439 */
 440static void target_remove_from_state_list(struct se_cmd *cmd)
 441{
 442        struct se_device *dev = cmd->se_dev;
 443        unsigned long flags;
 444
 445        if (!dev)
 446                return;
 447
 448        if (cmd->transport_state & CMD_T_BUSY)
 449                return;
 450
 451        spin_lock_irqsave(&dev->execute_task_lock, flags);
 452        if (cmd->state_active) {
 453                list_del(&cmd->state_list);
 454                cmd->state_active = false;
 455        }
 456        spin_unlock_irqrestore(&dev->execute_task_lock, flags);
 457}
 458
 459static int transport_cmd_check_stop(struct se_cmd *cmd, bool remove_from_lists)
 460{
 461        unsigned long flags;
 462
 463        spin_lock_irqsave(&cmd->t_state_lock, flags);
 464        /*
 465         * Determine if IOCTL context caller in requesting the stopping of this
 466         * command for LUN shutdown purposes.
 467         */
 468        if (cmd->transport_state & CMD_T_LUN_STOP) {
 469                pr_debug("%s:%d CMD_T_LUN_STOP for ITT: 0x%08x\n",
 470                        __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd));
 471
 472                cmd->transport_state &= ~CMD_T_ACTIVE;
 473                if (remove_from_lists)
 474                        target_remove_from_state_list(cmd);
 475                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 476
 477                complete(&cmd->transport_lun_stop_comp);
 478                return 1;
 479        }
 480
 481        if (remove_from_lists) {
 482                target_remove_from_state_list(cmd);
 483
 484                /*
 485                 * Clear struct se_cmd->se_lun before the handoff to FE.
 486                 */
 487                cmd->se_lun = NULL;
 488        }
 489
 490        /*
 491         * Determine if frontend context caller is requesting the stopping of
 492         * this command for frontend exceptions.
 493         */
 494        if (cmd->transport_state & CMD_T_STOP) {
 495                pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n",
 496                        __func__, __LINE__,
 497                        cmd->se_tfo->get_task_tag(cmd));
 498
 499                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 500
 501                complete(&cmd->t_transport_stop_comp);
 502                return 1;
 503        }
 504
 505        cmd->transport_state &= ~CMD_T_ACTIVE;
 506        if (remove_from_lists) {
 507                /*
 508                 * Some fabric modules like tcm_loop can release
 509                 * their internally allocated I/O reference now and
 510                 * struct se_cmd now.
 511                 *
 512                 * Fabric modules are expected to return '1' here if the
 513                 * se_cmd being passed is released at this point,
 514                 * or zero if not being released.
 515                 */
 516                if (cmd->se_tfo->check_stop_free != NULL) {
 517                        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 518                        return cmd->se_tfo->check_stop_free(cmd);
 519                }
 520        }
 521
 522        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 523        return 0;
 524}
 525
 526static int transport_cmd_check_stop_to_fabric(struct se_cmd *cmd)
 527{
 528        return transport_cmd_check_stop(cmd, true);
 529}
 530
 531static void transport_lun_remove_cmd(struct se_cmd *cmd)
 532{
 533        struct se_lun *lun = cmd->se_lun;
 534        unsigned long flags;
 535
 536        if (!lun)
 537                return;
 538
 539        spin_lock_irqsave(&cmd->t_state_lock, flags);
 540        if (cmd->transport_state & CMD_T_DEV_ACTIVE) {
 541                cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
 542                target_remove_from_state_list(cmd);
 543        }
 544        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 545
 546        spin_lock_irqsave(&lun->lun_cmd_lock, flags);
 547        if (!list_empty(&cmd->se_lun_node))
 548                list_del_init(&cmd->se_lun_node);
 549        spin_unlock_irqrestore(&lun->lun_cmd_lock, flags);
 550}
 551
 552void transport_cmd_finish_abort(struct se_cmd *cmd, int remove)
 553{
 554        if (!(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
 555                transport_lun_remove_cmd(cmd);
 556
 557        if (transport_cmd_check_stop_to_fabric(cmd))
 558                return;
 559        if (remove)
 560                transport_put_cmd(cmd);
 561}
 562
 563static void target_complete_failure_work(struct work_struct *work)
 564{
 565        struct se_cmd *cmd = container_of(work, struct se_cmd, work);
 566
 567        transport_generic_request_failure(cmd);
 568}
 569
 570/*
 571 * Used when asking transport to copy Sense Data from the underlying
 572 * Linux/SCSI struct scsi_cmnd
 573 */
 574static unsigned char *transport_get_sense_buffer(struct se_cmd *cmd)
 575{
 576        unsigned char *buffer = cmd->sense_buffer;
 577        struct se_device *dev = cmd->se_dev;
 578        u32 offset = 0;
 579
 580        WARN_ON(!cmd->se_lun);
 581
 582        if (!dev)
 583                return NULL;
 584
 585        if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION)
 586                return NULL;
 587
 588        offset = cmd->se_tfo->set_fabric_sense_len(cmd, TRANSPORT_SENSE_BUFFER);
 589
 590        /* Automatically padded */
 591        cmd->scsi_sense_length = TRANSPORT_SENSE_BUFFER + offset;
 592
 593        pr_debug("HBA_[%u]_PLUG[%s]: Requesting sense for SAM STATUS: 0x%02x\n",
 594                dev->se_hba->hba_id, dev->transport->name, cmd->scsi_status);
 595        return &buffer[offset];
 596}
 597
 598void target_complete_cmd(struct se_cmd *cmd, u8 scsi_status)
 599{
 600        struct se_device *dev = cmd->se_dev;
 601        int success = scsi_status == GOOD;
 602        unsigned long flags;
 603
 604        cmd->scsi_status = scsi_status;
 605
 606
 607        spin_lock_irqsave(&cmd->t_state_lock, flags);
 608        cmd->transport_state &= ~CMD_T_BUSY;
 609
 610        if (dev && dev->transport->transport_complete) {
 611                dev->transport->transport_complete(cmd,
 612                                cmd->t_data_sg,
 613                                transport_get_sense_buffer(cmd));
 614                if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE)
 615                        success = 1;
 616        }
 617
 618        /*
 619         * See if we are waiting to complete for an exception condition.
 620         */
 621        if (cmd->transport_state & CMD_T_REQUEST_STOP) {
 622                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 623                complete(&cmd->task_stop_comp);
 624                return;
 625        }
 626
 627        if (!success)
 628                cmd->transport_state |= CMD_T_FAILED;
 629
 630        /*
 631         * Check for case where an explict ABORT_TASK has been received
 632         * and transport_wait_for_tasks() will be waiting for completion..
 633         */
 634        if (cmd->transport_state & CMD_T_ABORTED &&
 635            cmd->transport_state & CMD_T_STOP) {
 636                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 637                complete(&cmd->t_transport_stop_comp);
 638                return;
 639        } else if (cmd->transport_state & CMD_T_FAILED) {
 640                cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
 641                INIT_WORK(&cmd->work, target_complete_failure_work);
 642        } else {
 643                INIT_WORK(&cmd->work, target_complete_ok_work);
 644        }
 645
 646        cmd->t_state = TRANSPORT_COMPLETE;
 647        cmd->transport_state |= (CMD_T_COMPLETE | CMD_T_ACTIVE);
 648        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
 649
 650        queue_work(target_completion_wq, &cmd->work);
 651}
 652EXPORT_SYMBOL(target_complete_cmd);
 653
 654static void target_add_to_state_list(struct se_cmd *cmd)
 655{
 656        struct se_device *dev = cmd->se_dev;
 657        unsigned long flags;
 658
 659        spin_lock_irqsave(&dev->execute_task_lock, flags);
 660        if (!cmd->state_active) {
 661                list_add_tail(&cmd->state_list, &dev->state_list);
 662                cmd->state_active = true;
 663        }
 664        spin_unlock_irqrestore(&dev->execute_task_lock, flags);
 665}
 666
 667/*
 668 * Handle QUEUE_FULL / -EAGAIN and -ENOMEM status
 669 */
 670static void transport_write_pending_qf(struct se_cmd *cmd);
 671static void transport_complete_qf(struct se_cmd *cmd);
 672
 673static void target_qf_do_work(struct work_struct *work)
 674{
 675        struct se_device *dev = container_of(work, struct se_device,
 676                                        qf_work_queue);
 677        LIST_HEAD(qf_cmd_list);
 678        struct se_cmd *cmd, *cmd_tmp;
 679
 680        spin_lock_irq(&dev->qf_cmd_lock);
 681        list_splice_init(&dev->qf_cmd_list, &qf_cmd_list);
 682        spin_unlock_irq(&dev->qf_cmd_lock);
 683
 684        list_for_each_entry_safe(cmd, cmd_tmp, &qf_cmd_list, se_qf_node) {
 685                list_del(&cmd->se_qf_node);
 686                atomic_dec(&dev->dev_qf_count);
 687                smp_mb__after_atomic_dec();
 688
 689                pr_debug("Processing %s cmd: %p QUEUE_FULL in work queue"
 690                        " context: %s\n", cmd->se_tfo->get_fabric_name(), cmd,
 691                        (cmd->t_state == TRANSPORT_COMPLETE_QF_OK) ? "COMPLETE_OK" :
 692                        (cmd->t_state == TRANSPORT_COMPLETE_QF_WP) ? "WRITE_PENDING"
 693                        : "UNKNOWN");
 694
 695                if (cmd->t_state == TRANSPORT_COMPLETE_QF_WP)
 696                        transport_write_pending_qf(cmd);
 697                else if (cmd->t_state == TRANSPORT_COMPLETE_QF_OK)
 698                        transport_complete_qf(cmd);
 699        }
 700}
 701
 702unsigned char *transport_dump_cmd_direction(struct se_cmd *cmd)
 703{
 704        switch (cmd->data_direction) {
 705        case DMA_NONE:
 706                return "NONE";
 707        case DMA_FROM_DEVICE:
 708                return "READ";
 709        case DMA_TO_DEVICE:
 710                return "WRITE";
 711        case DMA_BIDIRECTIONAL:
 712                return "BIDI";
 713        default:
 714                break;
 715        }
 716
 717        return "UNKNOWN";
 718}
 719
 720void transport_dump_dev_state(
 721        struct se_device *dev,
 722        char *b,
 723        int *bl)
 724{
 725        *bl += sprintf(b + *bl, "Status: ");
 726        switch (dev->dev_status) {
 727        case TRANSPORT_DEVICE_ACTIVATED:
 728                *bl += sprintf(b + *bl, "ACTIVATED");
 729                break;
 730        case TRANSPORT_DEVICE_DEACTIVATED:
 731                *bl += sprintf(b + *bl, "DEACTIVATED");
 732                break;
 733        case TRANSPORT_DEVICE_SHUTDOWN:
 734                *bl += sprintf(b + *bl, "SHUTDOWN");
 735                break;
 736        case TRANSPORT_DEVICE_OFFLINE_ACTIVATED:
 737        case TRANSPORT_DEVICE_OFFLINE_DEACTIVATED:
 738                *bl += sprintf(b + *bl, "OFFLINE");
 739                break;
 740        default:
 741                *bl += sprintf(b + *bl, "UNKNOWN=%d", dev->dev_status);
 742                break;
 743        }
 744
 745        *bl += sprintf(b + *bl, "  Max Queue Depth: %d", dev->queue_depth);
 746        *bl += sprintf(b + *bl, "  SectorSize: %u  HwMaxSectors: %u\n",
 747                dev->se_sub_dev->se_dev_attrib.block_size,
 748                dev->se_sub_dev->se_dev_attrib.hw_max_sectors);
 749        *bl += sprintf(b + *bl, "        ");
 750}
 751
 752void transport_dump_vpd_proto_id(
 753        struct t10_vpd *vpd,
 754        unsigned char *p_buf,
 755        int p_buf_len)
 756{
 757        unsigned char buf[VPD_TMP_BUF_SIZE];
 758        int len;
 759
 760        memset(buf, 0, VPD_TMP_BUF_SIZE);
 761        len = sprintf(buf, "T10 VPD Protocol Identifier: ");
 762
 763        switch (vpd->protocol_identifier) {
 764        case 0x00:
 765                sprintf(buf+len, "Fibre Channel\n");
 766                break;
 767        case 0x10:
 768                sprintf(buf+len, "Parallel SCSI\n");
 769                break;
 770        case 0x20:
 771                sprintf(buf+len, "SSA\n");
 772                break;
 773        case 0x30:
 774                sprintf(buf+len, "IEEE 1394\n");
 775                break;
 776        case 0x40:
 777                sprintf(buf+len, "SCSI Remote Direct Memory Access"
 778                                " Protocol\n");
 779                break;
 780        case 0x50:
 781                sprintf(buf+len, "Internet SCSI (iSCSI)\n");
 782                break;
 783        case 0x60:
 784                sprintf(buf+len, "SAS Serial SCSI Protocol\n");
 785                break;
 786        case 0x70:
 787                sprintf(buf+len, "Automation/Drive Interface Transport"
 788                                " Protocol\n");
 789                break;
 790        case 0x80:
 791                sprintf(buf+len, "AT Attachment Interface ATA/ATAPI\n");
 792                break;
 793        default:
 794                sprintf(buf+len, "Unknown 0x%02x\n",
 795                                vpd->protocol_identifier);
 796                break;
 797        }
 798
 799        if (p_buf)
 800                strncpy(p_buf, buf, p_buf_len);
 801        else
 802                pr_debug("%s", buf);
 803}
 804
 805void
 806transport_set_vpd_proto_id(struct t10_vpd *vpd, unsigned char *page_83)
 807{
 808        /*
 809         * Check if the Protocol Identifier Valid (PIV) bit is set..
 810         *
 811         * from spc3r23.pdf section 7.5.1
 812         */
 813         if (page_83[1] & 0x80) {
 814                vpd->protocol_identifier = (page_83[0] & 0xf0);
 815                vpd->protocol_identifier_set = 1;
 816                transport_dump_vpd_proto_id(vpd, NULL, 0);
 817        }
 818}
 819EXPORT_SYMBOL(transport_set_vpd_proto_id);
 820
 821int transport_dump_vpd_assoc(
 822        struct t10_vpd *vpd,
 823        unsigned char *p_buf,
 824        int p_buf_len)
 825{
 826        unsigned char buf[VPD_TMP_BUF_SIZE];
 827        int ret = 0;
 828        int len;
 829
 830        memset(buf, 0, VPD_TMP_BUF_SIZE);
 831        len = sprintf(buf, "T10 VPD Identifier Association: ");
 832
 833        switch (vpd->association) {
 834        case 0x00:
 835                sprintf(buf+len, "addressed logical unit\n");
 836                break;
 837        case 0x10:
 838                sprintf(buf+len, "target port\n");
 839                break;
 840        case 0x20:
 841                sprintf(buf+len, "SCSI target device\n");
 842                break;
 843        default:
 844                sprintf(buf+len, "Unknown 0x%02x\n", vpd->association);
 845                ret = -EINVAL;
 846                break;
 847        }
 848
 849        if (p_buf)
 850                strncpy(p_buf, buf, p_buf_len);
 851        else
 852                pr_debug("%s", buf);
 853
 854        return ret;
 855}
 856
 857int transport_set_vpd_assoc(struct t10_vpd *vpd, unsigned char *page_83)
 858{
 859        /*
 860         * The VPD identification association..
 861         *
 862         * from spc3r23.pdf Section 7.6.3.1 Table 297
 863         */
 864        vpd->association = (page_83[1] & 0x30);
 865        return transport_dump_vpd_assoc(vpd, NULL, 0);
 866}
 867EXPORT_SYMBOL(transport_set_vpd_assoc);
 868
 869int transport_dump_vpd_ident_type(
 870        struct t10_vpd *vpd,
 871        unsigned char *p_buf,
 872        int p_buf_len)
 873{
 874        unsigned char buf[VPD_TMP_BUF_SIZE];
 875        int ret = 0;
 876        int len;
 877
 878        memset(buf, 0, VPD_TMP_BUF_SIZE);
 879        len = sprintf(buf, "T10 VPD Identifier Type: ");
 880
 881        switch (vpd->device_identifier_type) {
 882        case 0x00:
 883                sprintf(buf+len, "Vendor specific\n");
 884                break;
 885        case 0x01:
 886                sprintf(buf+len, "T10 Vendor ID based\n");
 887                break;
 888        case 0x02:
 889                sprintf(buf+len, "EUI-64 based\n");
 890                break;
 891        case 0x03:
 892                sprintf(buf+len, "NAA\n");
 893                break;
 894        case 0x04:
 895                sprintf(buf+len, "Relative target port identifier\n");
 896                break;
 897        case 0x08:
 898                sprintf(buf+len, "SCSI name string\n");
 899                break;
 900        default:
 901                sprintf(buf+len, "Unsupported: 0x%02x\n",
 902                                vpd->device_identifier_type);
 903                ret = -EINVAL;
 904                break;
 905        }
 906
 907        if (p_buf) {
 908                if (p_buf_len < strlen(buf)+1)
 909                        return -EINVAL;
 910                strncpy(p_buf, buf, p_buf_len);
 911        } else {
 912                pr_debug("%s", buf);
 913        }
 914
 915        return ret;
 916}
 917
 918int transport_set_vpd_ident_type(struct t10_vpd *vpd, unsigned char *page_83)
 919{
 920        /*
 921         * The VPD identifier type..
 922         *
 923         * from spc3r23.pdf Section 7.6.3.1 Table 298
 924         */
 925        vpd->device_identifier_type = (page_83[1] & 0x0f);
 926        return transport_dump_vpd_ident_type(vpd, NULL, 0);
 927}
 928EXPORT_SYMBOL(transport_set_vpd_ident_type);
 929
 930int transport_dump_vpd_ident(
 931        struct t10_vpd *vpd,
 932        unsigned char *p_buf,
 933        int p_buf_len)
 934{
 935        unsigned char buf[VPD_TMP_BUF_SIZE];
 936        int ret = 0;
 937
 938        memset(buf, 0, VPD_TMP_BUF_SIZE);
 939
 940        switch (vpd->device_identifier_code_set) {
 941        case 0x01: /* Binary */
 942                sprintf(buf, "T10 VPD Binary Device Identifier: %s\n",
 943                        &vpd->device_identifier[0]);
 944                break;
 945        case 0x02: /* ASCII */
 946                sprintf(buf, "T10 VPD ASCII Device Identifier: %s\n",
 947                        &vpd->device_identifier[0]);
 948                break;
 949        case 0x03: /* UTF-8 */
 950                sprintf(buf, "T10 VPD UTF-8 Device Identifier: %s\n",
 951                        &vpd->device_identifier[0]);
 952                break;
 953        default:
 954                sprintf(buf, "T10 VPD Device Identifier encoding unsupported:"
 955                        " 0x%02x", vpd->device_identifier_code_set);
 956                ret = -EINVAL;
 957                break;
 958        }
 959
 960        if (p_buf)
 961                strncpy(p_buf, buf, p_buf_len);
 962        else
 963                pr_debug("%s", buf);
 964
 965        return ret;
 966}
 967
 968int
 969transport_set_vpd_ident(struct t10_vpd *vpd, unsigned char *page_83)
 970{
 971        static const char hex_str[] = "0123456789abcdef";
 972        int j = 0, i = 4; /* offset to start of the identifer */
 973
 974        /*
 975         * The VPD Code Set (encoding)
 976         *
 977         * from spc3r23.pdf Section 7.6.3.1 Table 296
 978         */
 979        vpd->device_identifier_code_set = (page_83[0] & 0x0f);
 980        switch (vpd->device_identifier_code_set) {
 981        case 0x01: /* Binary */
 982                vpd->device_identifier[j++] =
 983                                hex_str[vpd->device_identifier_type];
 984                while (i < (4 + page_83[3])) {
 985                        vpd->device_identifier[j++] =
 986                                hex_str[(page_83[i] & 0xf0) >> 4];
 987                        vpd->device_identifier[j++] =
 988                                hex_str[page_83[i] & 0x0f];
 989                        i++;
 990                }
 991                break;
 992        case 0x02: /* ASCII */
 993        case 0x03: /* UTF-8 */
 994                while (i < (4 + page_83[3]))
 995                        vpd->device_identifier[j++] = page_83[i++];
 996                break;
 997        default:
 998                break;
 999        }
1000
1001        return transport_dump_vpd_ident(vpd, NULL, 0);
1002}
1003EXPORT_SYMBOL(transport_set_vpd_ident);
1004
1005static void core_setup_task_attr_emulation(struct se_device *dev)
1006{
1007        /*
1008         * If this device is from Target_Core_Mod/pSCSI, disable the
1009         * SAM Task Attribute emulation.
1010         *
1011         * This is currently not available in upsream Linux/SCSI Target
1012         * mode code, and is assumed to be disabled while using TCM/pSCSI.
1013         */
1014        if (dev->transport->transport_type == TRANSPORT_PLUGIN_PHBA_PDEV) {
1015                dev->dev_task_attr_type = SAM_TASK_ATTR_PASSTHROUGH;
1016                return;
1017        }
1018
1019        dev->dev_task_attr_type = SAM_TASK_ATTR_EMULATED;
1020        pr_debug("%s: Using SAM_TASK_ATTR_EMULATED for SPC: 0x%02x"
1021                " device\n", dev->transport->name,
1022                dev->transport->get_device_rev(dev));
1023}
1024
1025static void scsi_dump_inquiry(struct se_device *dev)
1026{
1027        struct t10_wwn *wwn = &dev->se_sub_dev->t10_wwn;
1028        char buf[17];
1029        int i, device_type;
1030        /*
1031         * Print Linux/SCSI style INQUIRY formatting to the kernel ring buffer
1032         */
1033        for (i = 0; i < 8; i++)
1034                if (wwn->vendor[i] >= 0x20)
1035                        buf[i] = wwn->vendor[i];
1036                else
1037                        buf[i] = ' ';
1038        buf[i] = '\0';
1039        pr_debug("  Vendor: %s\n", buf);
1040
1041        for (i = 0; i < 16; i++)
1042                if (wwn->model[i] >= 0x20)
1043                        buf[i] = wwn->model[i];
1044                else
1045                        buf[i] = ' ';
1046        buf[i] = '\0';
1047        pr_debug("  Model: %s\n", buf);
1048
1049        for (i = 0; i < 4; i++)
1050                if (wwn->revision[i] >= 0x20)
1051                        buf[i] = wwn->revision[i];
1052                else
1053                        buf[i] = ' ';
1054        buf[i] = '\0';
1055        pr_debug("  Revision: %s\n", buf);
1056
1057        device_type = dev->transport->get_device_type(dev);
1058        pr_debug("  Type:   %s ", scsi_device_type(device_type));
1059        pr_debug("                 ANSI SCSI revision: %02x\n",
1060                                dev->transport->get_device_rev(dev));
1061}
1062
1063struct se_device *transport_add_device_to_core_hba(
1064        struct se_hba *hba,
1065        struct se_subsystem_api *transport,
1066        struct se_subsystem_dev *se_dev,
1067        u32 device_flags,
1068        void *transport_dev,
1069        struct se_dev_limits *dev_limits,
1070        const char *inquiry_prod,
1071        const char *inquiry_rev)
1072{
1073        int force_pt;
1074        struct se_device  *dev;
1075
1076        dev = kzalloc(sizeof(struct se_device), GFP_KERNEL);
1077        if (!dev) {
1078                pr_err("Unable to allocate memory for se_dev_t\n");
1079                return NULL;
1080        }
1081
1082        dev->dev_flags          = device_flags;
1083        dev->dev_status         |= TRANSPORT_DEVICE_DEACTIVATED;
1084        dev->dev_ptr            = transport_dev;
1085        dev->se_hba             = hba;
1086        dev->se_sub_dev         = se_dev;
1087        dev->transport          = transport;
1088        INIT_LIST_HEAD(&dev->dev_list);
1089        INIT_LIST_HEAD(&dev->dev_sep_list);
1090        INIT_LIST_HEAD(&dev->dev_tmr_list);
1091        INIT_LIST_HEAD(&dev->delayed_cmd_list);
1092        INIT_LIST_HEAD(&dev->state_list);
1093        INIT_LIST_HEAD(&dev->qf_cmd_list);
1094        spin_lock_init(&dev->execute_task_lock);
1095        spin_lock_init(&dev->delayed_cmd_lock);
1096        spin_lock_init(&dev->dev_reservation_lock);
1097        spin_lock_init(&dev->dev_status_lock);
1098        spin_lock_init(&dev->se_port_lock);
1099        spin_lock_init(&dev->se_tmr_lock);
1100        spin_lock_init(&dev->qf_cmd_lock);
1101        atomic_set(&dev->dev_ordered_id, 0);
1102
1103        se_dev_set_default_attribs(dev, dev_limits);
1104
1105        dev->dev_index = scsi_get_new_index(SCSI_DEVICE_INDEX);
1106        dev->creation_time = get_jiffies_64();
1107        spin_lock_init(&dev->stats_lock);
1108
1109        spin_lock(&hba->device_lock);
1110        list_add_tail(&dev->dev_list, &hba->hba_dev_list);
1111        hba->dev_count++;
1112        spin_unlock(&hba->device_lock);
1113        /*
1114         * Setup the SAM Task Attribute emulation for struct se_device
1115         */
1116        core_setup_task_attr_emulation(dev);
1117        /*
1118         * Force PR and ALUA passthrough emulation with internal object use.
1119         */
1120        force_pt = (hba->hba_flags & HBA_FLAGS_INTERNAL_USE);
1121        /*
1122         * Setup the Reservations infrastructure for struct se_device
1123         */
1124        core_setup_reservations(dev, force_pt);
1125        /*
1126         * Setup the Asymmetric Logical Unit Assignment for struct se_device
1127         */
1128        if (core_setup_alua(dev, force_pt) < 0)
1129                goto err_dev_list;
1130
1131        /*
1132         * Startup the struct se_device processing thread
1133         */
1134        dev->tmr_wq = alloc_workqueue("tmr-%s", WQ_MEM_RECLAIM | WQ_UNBOUND, 1,
1135                                      dev->transport->name);
1136        if (!dev->tmr_wq) {
1137                pr_err("Unable to create tmr workqueue for %s\n",
1138                        dev->transport->name);
1139                goto err_dev_list;
1140        }
1141        /*
1142         * Setup work_queue for QUEUE_FULL
1143         */
1144        INIT_WORK(&dev->qf_work_queue, target_qf_do_work);
1145        /*
1146         * Preload the initial INQUIRY const values if we are doing
1147         * anything virtual (IBLOCK, FILEIO, RAMDISK), but not for TCM/pSCSI
1148         * passthrough because this is being provided by the backend LLD.
1149         * This is required so that transport_get_inquiry() copies these
1150         * originals once back into DEV_T10_WWN(dev) for the virtual device
1151         * setup.
1152         */
1153        if (dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
1154                if (!inquiry_prod || !inquiry_rev) {
1155                        pr_err("All non TCM/pSCSI plugins require"
1156                                " INQUIRY consts\n");
1157                        goto err_wq;
1158                }
1159
1160                strncpy(&dev->se_sub_dev->t10_wwn.vendor[0], "LIO-ORG", 8);
1161                strncpy(&dev->se_sub_dev->t10_wwn.model[0], inquiry_prod, 16);
1162                strncpy(&dev->se_sub_dev->t10_wwn.revision[0], inquiry_rev, 4);
1163        }
1164        scsi_dump_inquiry(dev);
1165
1166        return dev;
1167
1168err_wq:
1169        destroy_workqueue(dev->tmr_wq);
1170err_dev_list:
1171        spin_lock(&hba->device_lock);
1172        list_del(&dev->dev_list);
1173        hba->dev_count--;
1174        spin_unlock(&hba->device_lock);
1175
1176        se_release_vpd_for_dev(dev);
1177
1178        kfree(dev);
1179
1180        return NULL;
1181}
1182EXPORT_SYMBOL(transport_add_device_to_core_hba);
1183
1184int target_cmd_size_check(struct se_cmd *cmd, unsigned int size)
1185{
1186        struct se_device *dev = cmd->se_dev;
1187
1188        if (cmd->unknown_data_length) {
1189                cmd->data_length = size;
1190        } else if (size != cmd->data_length) {
1191                pr_warn("TARGET_CORE[%s]: Expected Transfer Length:"
1192                        " %u does not match SCSI CDB Length: %u for SAM Opcode:"
1193                        " 0x%02x\n", cmd->se_tfo->get_fabric_name(),
1194                                cmd->data_length, size, cmd->t_task_cdb[0]);
1195
1196                if (cmd->data_direction == DMA_TO_DEVICE) {
1197                        pr_err("Rejecting underflow/overflow"
1198                                        " WRITE data\n");
1199                        goto out_invalid_cdb_field;
1200                }
1201                /*
1202                 * Reject READ_* or WRITE_* with overflow/underflow for
1203                 * type SCF_SCSI_DATA_CDB.
1204                 */
1205                if (dev->se_sub_dev->se_dev_attrib.block_size != 512)  {
1206                        pr_err("Failing OVERFLOW/UNDERFLOW for LBA op"
1207                                " CDB on non 512-byte sector setup subsystem"
1208                                " plugin: %s\n", dev->transport->name);
1209                        /* Returns CHECK_CONDITION + INVALID_CDB_FIELD */
1210                        goto out_invalid_cdb_field;
1211                }
1212                /*
1213                 * For the overflow case keep the existing fabric provided
1214                 * ->data_length.  Otherwise for the underflow case, reset
1215                 * ->data_length to the smaller SCSI expected data transfer
1216                 * length.
1217                 */
1218                if (size > cmd->data_length) {
1219                        cmd->se_cmd_flags |= SCF_OVERFLOW_BIT;
1220                        cmd->residual_count = (size - cmd->data_length);
1221                } else {
1222                        cmd->se_cmd_flags |= SCF_UNDERFLOW_BIT;
1223                        cmd->residual_count = (cmd->data_length - size);
1224                        cmd->data_length = size;
1225                }
1226        }
1227
1228        return 0;
1229
1230out_invalid_cdb_field:
1231        cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1232        cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1233        return -EINVAL;
1234}
1235
1236/*
1237 * Used by fabric modules containing a local struct se_cmd within their
1238 * fabric dependent per I/O descriptor.
1239 */
1240void transport_init_se_cmd(
1241        struct se_cmd *cmd,
1242        struct target_core_fabric_ops *tfo,
1243        struct se_session *se_sess,
1244        u32 data_length,
1245        int data_direction,
1246        int task_attr,
1247        unsigned char *sense_buffer)
1248{
1249        INIT_LIST_HEAD(&cmd->se_lun_node);
1250        INIT_LIST_HEAD(&cmd->se_delayed_node);
1251        INIT_LIST_HEAD(&cmd->se_qf_node);
1252        INIT_LIST_HEAD(&cmd->se_cmd_list);
1253        INIT_LIST_HEAD(&cmd->state_list);
1254        init_completion(&cmd->transport_lun_fe_stop_comp);
1255        init_completion(&cmd->transport_lun_stop_comp);
1256        init_completion(&cmd->t_transport_stop_comp);
1257        init_completion(&cmd->cmd_wait_comp);
1258        init_completion(&cmd->task_stop_comp);
1259        spin_lock_init(&cmd->t_state_lock);
1260        cmd->transport_state = CMD_T_DEV_ACTIVE;
1261
1262        cmd->se_tfo = tfo;
1263        cmd->se_sess = se_sess;
1264        cmd->data_length = data_length;
1265        cmd->data_direction = data_direction;
1266        cmd->sam_task_attr = task_attr;
1267        cmd->sense_buffer = sense_buffer;
1268
1269        cmd->state_active = false;
1270}
1271EXPORT_SYMBOL(transport_init_se_cmd);
1272
1273static int transport_check_alloc_task_attr(struct se_cmd *cmd)
1274{
1275        /*
1276         * Check if SAM Task Attribute emulation is enabled for this
1277         * struct se_device storage object
1278         */
1279        if (cmd->se_dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1280                return 0;
1281
1282        if (cmd->sam_task_attr == MSG_ACA_TAG) {
1283                pr_debug("SAM Task Attribute ACA"
1284                        " emulation is not supported\n");
1285                return -EINVAL;
1286        }
1287        /*
1288         * Used to determine when ORDERED commands should go from
1289         * Dormant to Active status.
1290         */
1291        cmd->se_ordered_id = atomic_inc_return(&cmd->se_dev->dev_ordered_id);
1292        smp_mb__after_atomic_inc();
1293        pr_debug("Allocated se_ordered_id: %u for Task Attr: 0x%02x on %s\n",
1294                        cmd->se_ordered_id, cmd->sam_task_attr,
1295                        cmd->se_dev->transport->name);
1296        return 0;
1297}
1298
1299/*      target_setup_cmd_from_cdb():
1300 *
1301 *      Called from fabric RX Thread.
1302 */
1303int target_setup_cmd_from_cdb(
1304        struct se_cmd *cmd,
1305        unsigned char *cdb)
1306{
1307        struct se_subsystem_dev *su_dev = cmd->se_dev->se_sub_dev;
1308        u32 pr_reg_type = 0;
1309        u8 alua_ascq = 0;
1310        unsigned long flags;
1311        int ret;
1312
1313        /*
1314         * Ensure that the received CDB is less than the max (252 + 8) bytes
1315         * for VARIABLE_LENGTH_CMD
1316         */
1317        if (scsi_command_size(cdb) > SCSI_MAX_VARLEN_CDB_SIZE) {
1318                pr_err("Received SCSI CDB with command_size: %d that"
1319                        " exceeds SCSI_MAX_VARLEN_CDB_SIZE: %d\n",
1320                        scsi_command_size(cdb), SCSI_MAX_VARLEN_CDB_SIZE);
1321                cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1322                cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1323                return -EINVAL;
1324        }
1325        /*
1326         * If the received CDB is larger than TCM_MAX_COMMAND_SIZE,
1327         * allocate the additional extended CDB buffer now..  Otherwise
1328         * setup the pointer from __t_task_cdb to t_task_cdb.
1329         */
1330        if (scsi_command_size(cdb) > sizeof(cmd->__t_task_cdb)) {
1331                cmd->t_task_cdb = kzalloc(scsi_command_size(cdb),
1332                                                GFP_KERNEL);
1333                if (!cmd->t_task_cdb) {
1334                        pr_err("Unable to allocate cmd->t_task_cdb"
1335                                " %u > sizeof(cmd->__t_task_cdb): %lu ops\n",
1336                                scsi_command_size(cdb),
1337                                (unsigned long)sizeof(cmd->__t_task_cdb));
1338                        cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1339                        cmd->scsi_sense_reason =
1340                                        TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
1341                        return -ENOMEM;
1342                }
1343        } else
1344                cmd->t_task_cdb = &cmd->__t_task_cdb[0];
1345        /*
1346         * Copy the original CDB into cmd->
1347         */
1348        memcpy(cmd->t_task_cdb, cdb, scsi_command_size(cdb));
1349
1350        /*
1351         * Check for an existing UNIT ATTENTION condition
1352         */
1353        if (core_scsi3_ua_check(cmd, cdb) < 0) {
1354                cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1355                cmd->scsi_sense_reason = TCM_CHECK_CONDITION_UNIT_ATTENTION;
1356                return -EINVAL;
1357        }
1358
1359        ret = su_dev->t10_alua.alua_state_check(cmd, cdb, &alua_ascq);
1360        if (ret != 0) {
1361                /*
1362                 * Set SCSI additional sense code (ASC) to 'LUN Not Accessible';
1363                 * The ALUA additional sense code qualifier (ASCQ) is determined
1364                 * by the ALUA primary or secondary access state..
1365                 */
1366                if (ret > 0) {
1367                        pr_debug("[%s]: ALUA TG Port not available, "
1368                                "SenseKey: NOT_READY, ASC/ASCQ: "
1369                                "0x04/0x%02x\n",
1370                                cmd->se_tfo->get_fabric_name(), alua_ascq);
1371
1372                        transport_set_sense_codes(cmd, 0x04, alua_ascq);
1373                        cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1374                        cmd->scsi_sense_reason = TCM_CHECK_CONDITION_NOT_READY;
1375                        return -EINVAL;
1376                }
1377                cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1378                cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1379                return -EINVAL;
1380        }
1381
1382        /*
1383         * Check status for SPC-3 Persistent Reservations
1384         */
1385        if (su_dev->t10_pr.pr_ops.t10_reservation_check(cmd, &pr_reg_type)) {
1386                if (su_dev->t10_pr.pr_ops.t10_seq_non_holder(
1387                                        cmd, cdb, pr_reg_type) != 0) {
1388                        cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1389                        cmd->se_cmd_flags |= SCF_SCSI_RESERVATION_CONFLICT;
1390                        cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1391                        cmd->scsi_sense_reason = TCM_RESERVATION_CONFLICT;
1392                        return -EBUSY;
1393                }
1394                /*
1395                 * This means the CDB is allowed for the SCSI Initiator port
1396                 * when said port is *NOT* holding the legacy SPC-2 or
1397                 * SPC-3 Persistent Reservation.
1398                 */
1399        }
1400
1401        ret = cmd->se_dev->transport->parse_cdb(cmd);
1402        if (ret < 0)
1403                return ret;
1404
1405        spin_lock_irqsave(&cmd->t_state_lock, flags);
1406        cmd->se_cmd_flags |= SCF_SUPPORTED_SAM_OPCODE;
1407        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
1408
1409        /*
1410         * Check for SAM Task Attribute Emulation
1411         */
1412        if (transport_check_alloc_task_attr(cmd) < 0) {
1413                cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
1414                cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
1415                return -EINVAL;
1416        }
1417        spin_lock(&cmd->se_lun->lun_sep_lock);
1418        if (cmd->se_lun->lun_sep)
1419                cmd->se_lun->lun_sep->sep_stats.cmd_pdus++;
1420        spin_unlock(&cmd->se_lun->lun_sep_lock);
1421        return 0;
1422}
1423EXPORT_SYMBOL(target_setup_cmd_from_cdb);
1424
1425/*
1426 * Used by fabric module frontends to queue tasks directly.
1427 * Many only be used from process context only
1428 */
1429int transport_handle_cdb_direct(
1430        struct se_cmd *cmd)
1431{
1432        int ret;
1433
1434        if (!cmd->se_lun) {
1435                dump_stack();
1436                pr_err("cmd->se_lun is NULL\n");
1437                return -EINVAL;
1438        }
1439        if (in_interrupt()) {
1440                dump_stack();
1441                pr_err("transport_generic_handle_cdb cannot be called"
1442                                " from interrupt context\n");
1443                return -EINVAL;
1444        }
1445        /*
1446         * Set TRANSPORT_NEW_CMD state and CMD_T_ACTIVE to ensure that
1447         * outstanding descriptors are handled correctly during shutdown via
1448         * transport_wait_for_tasks()
1449         *
1450         * Also, we don't take cmd->t_state_lock here as we only expect
1451         * this to be called for initial descriptor submission.
1452         */
1453        cmd->t_state = TRANSPORT_NEW_CMD;
1454        cmd->transport_state |= CMD_T_ACTIVE;
1455
1456        /*
1457         * transport_generic_new_cmd() is already handling QUEUE_FULL,
1458         * so follow TRANSPORT_NEW_CMD processing thread context usage
1459         * and call transport_generic_request_failure() if necessary..
1460         */
1461        ret = transport_generic_new_cmd(cmd);
1462        if (ret < 0)
1463                transport_generic_request_failure(cmd);
1464
1465        return 0;
1466}
1467EXPORT_SYMBOL(transport_handle_cdb_direct);
1468
1469/**
1470 * target_submit_cmd - lookup unpacked lun and submit uninitialized se_cmd
1471 *
1472 * @se_cmd: command descriptor to submit
1473 * @se_sess: associated se_sess for endpoint
1474 * @cdb: pointer to SCSI CDB
1475 * @sense: pointer to SCSI sense buffer
1476 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1477 * @data_length: fabric expected data transfer length
1478 * @task_addr: SAM task attribute
1479 * @data_dir: DMA data direction
1480 * @flags: flags for command submission from target_sc_flags_tables
1481 *
1482 * Returns non zero to signal active I/O shutdown failure.  All other
1483 * setup exceptions will be returned as a SCSI CHECK_CONDITION response,
1484 * but still return zero here.
1485 *
1486 * This may only be called from process context, and also currently
1487 * assumes internal allocation of fabric payload buffer by target-core.
1488 **/
1489int target_submit_cmd(struct se_cmd *se_cmd, struct se_session *se_sess,
1490                unsigned char *cdb, unsigned char *sense, u32 unpacked_lun,
1491                u32 data_length, int task_attr, int data_dir, int flags)
1492{
1493        struct se_portal_group *se_tpg;
1494        int rc;
1495
1496        se_tpg = se_sess->se_tpg;
1497        BUG_ON(!se_tpg);
1498        BUG_ON(se_cmd->se_tfo || se_cmd->se_sess);
1499        BUG_ON(in_interrupt());
1500        /*
1501         * Initialize se_cmd for target operation.  From this point
1502         * exceptions are handled by sending exception status via
1503         * target_core_fabric_ops->queue_status() callback
1504         */
1505        transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1506                                data_length, data_dir, task_attr, sense);
1507        if (flags & TARGET_SCF_UNKNOWN_SIZE)
1508                se_cmd->unknown_data_length = 1;
1509        /*
1510         * Obtain struct se_cmd->cmd_kref reference and add new cmd to
1511         * se_sess->sess_cmd_list.  A second kref_get here is necessary
1512         * for fabrics using TARGET_SCF_ACK_KREF that expect a second
1513         * kref_put() to happen during fabric packet acknowledgement.
1514         */
1515        rc = target_get_sess_cmd(se_sess, se_cmd, (flags & TARGET_SCF_ACK_KREF));
1516        if (rc)
1517                return rc;
1518        /*
1519         * Signal bidirectional data payloads to target-core
1520         */
1521        if (flags & TARGET_SCF_BIDI_OP)
1522                se_cmd->se_cmd_flags |= SCF_BIDI;
1523        /*
1524         * Locate se_lun pointer and attach it to struct se_cmd
1525         */
1526        if (transport_lookup_cmd_lun(se_cmd, unpacked_lun) < 0) {
1527                transport_send_check_condition_and_sense(se_cmd,
1528                                se_cmd->scsi_sense_reason, 0);
1529                target_put_sess_cmd(se_sess, se_cmd);
1530                return 0;
1531        }
1532
1533        rc = target_setup_cmd_from_cdb(se_cmd, cdb);
1534        if (rc != 0) {
1535                transport_generic_request_failure(se_cmd);
1536                return 0;
1537        }
1538
1539        /*
1540         * Check if we need to delay processing because of ALUA
1541         * Active/NonOptimized primary access state..
1542         */
1543        core_alua_check_nonop_delay(se_cmd);
1544
1545        transport_handle_cdb_direct(se_cmd);
1546        return 0;
1547}
1548EXPORT_SYMBOL(target_submit_cmd);
1549
1550static void target_complete_tmr_failure(struct work_struct *work)
1551{
1552        struct se_cmd *se_cmd = container_of(work, struct se_cmd, work);
1553
1554        se_cmd->se_tmr_req->response = TMR_LUN_DOES_NOT_EXIST;
1555        se_cmd->se_tfo->queue_tm_rsp(se_cmd);
1556}
1557
1558/**
1559 * target_submit_tmr - lookup unpacked lun and submit uninitialized se_cmd
1560 *                     for TMR CDBs
1561 *
1562 * @se_cmd: command descriptor to submit
1563 * @se_sess: associated se_sess for endpoint
1564 * @sense: pointer to SCSI sense buffer
1565 * @unpacked_lun: unpacked LUN to reference for struct se_lun
1566 * @fabric_context: fabric context for TMR req
1567 * @tm_type: Type of TM request
1568 * @gfp: gfp type for caller
1569 * @tag: referenced task tag for TMR_ABORT_TASK
1570 * @flags: submit cmd flags
1571 *
1572 * Callable from all contexts.
1573 **/
1574
1575int target_submit_tmr(struct se_cmd *se_cmd, struct se_session *se_sess,
1576                unsigned char *sense, u32 unpacked_lun,
1577                void *fabric_tmr_ptr, unsigned char tm_type,
1578                gfp_t gfp, unsigned int tag, int flags)
1579{
1580        struct se_portal_group *se_tpg;
1581        int ret;
1582
1583        se_tpg = se_sess->se_tpg;
1584        BUG_ON(!se_tpg);
1585
1586        transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess,
1587                              0, DMA_NONE, MSG_SIMPLE_TAG, sense);
1588        /*
1589         * FIXME: Currently expect caller to handle se_cmd->se_tmr_req
1590         * allocation failure.
1591         */
1592        ret = core_tmr_alloc_req(se_cmd, fabric_tmr_ptr, tm_type, gfp);
1593        if (ret < 0)
1594                return -ENOMEM;
1595
1596        if (tm_type == TMR_ABORT_TASK)
1597                se_cmd->se_tmr_req->ref_task_tag = tag;
1598
1599        /* See target_submit_cmd for commentary */
1600        ret = target_get_sess_cmd(se_sess, se_cmd, (flags & TARGET_SCF_ACK_KREF));
1601        if (ret) {
1602                core_tmr_release_req(se_cmd->se_tmr_req);
1603                return ret;
1604        }
1605
1606        ret = transport_lookup_tmr_lun(se_cmd, unpacked_lun);
1607        if (ret) {
1608                /*
1609                 * For callback during failure handling, push this work off
1610                 * to process context with TMR_LUN_DOES_NOT_EXIST status.
1611                 */
1612                INIT_WORK(&se_cmd->work, target_complete_tmr_failure);
1613                schedule_work(&se_cmd->work);
1614                return 0;
1615        }
1616        transport_generic_handle_tmr(se_cmd);
1617        return 0;
1618}
1619EXPORT_SYMBOL(target_submit_tmr);
1620
1621/*
1622 * If the cmd is active, request it to be stopped and sleep until it
1623 * has completed.
1624 */
1625bool target_stop_cmd(struct se_cmd *cmd, unsigned long *flags)
1626{
1627        bool was_active = false;
1628
1629        if (cmd->transport_state & CMD_T_BUSY) {
1630                cmd->transport_state |= CMD_T_REQUEST_STOP;
1631                spin_unlock_irqrestore(&cmd->t_state_lock, *flags);
1632
1633                pr_debug("cmd %p waiting to complete\n", cmd);
1634                wait_for_completion(&cmd->task_stop_comp);
1635                pr_debug("cmd %p stopped successfully\n", cmd);
1636
1637                spin_lock_irqsave(&cmd->t_state_lock, *flags);
1638                cmd->transport_state &= ~CMD_T_REQUEST_STOP;
1639                cmd->transport_state &= ~CMD_T_BUSY;
1640                was_active = true;
1641        }
1642
1643        return was_active;
1644}
1645
1646/*
1647 * Handle SAM-esque emulation for generic transport request failures.
1648 */
1649void transport_generic_request_failure(struct se_cmd *cmd)
1650{
1651        int ret = 0;
1652
1653        pr_debug("-----[ Storage Engine Exception for cmd: %p ITT: 0x%08x"
1654                " CDB: 0x%02x\n", cmd, cmd->se_tfo->get_task_tag(cmd),
1655                cmd->t_task_cdb[0]);
1656        pr_debug("-----[ i_state: %d t_state: %d scsi_sense_reason: %d\n",
1657                cmd->se_tfo->get_cmd_state(cmd),
1658                cmd->t_state, cmd->scsi_sense_reason);
1659        pr_debug("-----[ CMD_T_ACTIVE: %d CMD_T_STOP: %d CMD_T_SENT: %d\n",
1660                (cmd->transport_state & CMD_T_ACTIVE) != 0,
1661                (cmd->transport_state & CMD_T_STOP) != 0,
1662                (cmd->transport_state & CMD_T_SENT) != 0);
1663
1664        /*
1665         * For SAM Task Attribute emulation for failed struct se_cmd
1666         */
1667        if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1668                transport_complete_task_attr(cmd);
1669
1670        switch (cmd->scsi_sense_reason) {
1671        case TCM_NON_EXISTENT_LUN:
1672        case TCM_UNSUPPORTED_SCSI_OPCODE:
1673        case TCM_INVALID_CDB_FIELD:
1674        case TCM_INVALID_PARAMETER_LIST:
1675        case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
1676        case TCM_UNKNOWN_MODE_PAGE:
1677        case TCM_WRITE_PROTECTED:
1678        case TCM_ADDRESS_OUT_OF_RANGE:
1679        case TCM_CHECK_CONDITION_ABORT_CMD:
1680        case TCM_CHECK_CONDITION_UNIT_ATTENTION:
1681        case TCM_CHECK_CONDITION_NOT_READY:
1682                break;
1683        case TCM_RESERVATION_CONFLICT:
1684                /*
1685                 * No SENSE Data payload for this case, set SCSI Status
1686                 * and queue the response to $FABRIC_MOD.
1687                 *
1688                 * Uses linux/include/scsi/scsi.h SAM status codes defs
1689                 */
1690                cmd->scsi_status = SAM_STAT_RESERVATION_CONFLICT;
1691                /*
1692                 * For UA Interlock Code 11b, a RESERVATION CONFLICT will
1693                 * establish a UNIT ATTENTION with PREVIOUS RESERVATION
1694                 * CONFLICT STATUS.
1695                 *
1696                 * See spc4r17, section 7.4.6 Control Mode Page, Table 349
1697                 */
1698                if (cmd->se_sess &&
1699                    cmd->se_dev->se_sub_dev->se_dev_attrib.emulate_ua_intlck_ctrl == 2)
1700                        core_scsi3_ua_allocate(cmd->se_sess->se_node_acl,
1701                                cmd->orig_fe_lun, 0x2C,
1702                                ASCQ_2CH_PREVIOUS_RESERVATION_CONFLICT_STATUS);
1703
1704                ret = cmd->se_tfo->queue_status(cmd);
1705                if (ret == -EAGAIN || ret == -ENOMEM)
1706                        goto queue_full;
1707                goto check_stop;
1708        default:
1709                pr_err("Unknown transport error for CDB 0x%02x: %d\n",
1710                        cmd->t_task_cdb[0], cmd->scsi_sense_reason);
1711                cmd->scsi_sense_reason = TCM_UNSUPPORTED_SCSI_OPCODE;
1712                break;
1713        }
1714
1715        ret = transport_send_check_condition_and_sense(cmd,
1716                        cmd->scsi_sense_reason, 0);
1717        if (ret == -EAGAIN || ret == -ENOMEM)
1718                goto queue_full;
1719
1720check_stop:
1721        transport_lun_remove_cmd(cmd);
1722        if (!transport_cmd_check_stop_to_fabric(cmd))
1723                ;
1724        return;
1725
1726queue_full:
1727        cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
1728        transport_handle_queue_full(cmd, cmd->se_dev);
1729}
1730EXPORT_SYMBOL(transport_generic_request_failure);
1731
1732static void __target_execute_cmd(struct se_cmd *cmd)
1733{
1734        int error = 0;
1735
1736        spin_lock_irq(&cmd->t_state_lock);
1737        cmd->transport_state |= (CMD_T_BUSY|CMD_T_SENT);
1738        spin_unlock_irq(&cmd->t_state_lock);
1739
1740        if (cmd->execute_cmd)
1741                error = cmd->execute_cmd(cmd);
1742
1743        if (error) {
1744                spin_lock_irq(&cmd->t_state_lock);
1745                cmd->transport_state &= ~(CMD_T_BUSY|CMD_T_SENT);
1746                spin_unlock_irq(&cmd->t_state_lock);
1747
1748                transport_generic_request_failure(cmd);
1749        }
1750}
1751
1752void target_execute_cmd(struct se_cmd *cmd)
1753{
1754        struct se_device *dev = cmd->se_dev;
1755
1756        /*
1757         * If the received CDB has aleady been aborted stop processing it here.
1758         */
1759        if (transport_check_aborted_status(cmd, 1))
1760                return;
1761
1762        /*
1763         * Determine if IOCTL context caller in requesting the stopping of this
1764         * command for LUN shutdown purposes.
1765         */
1766        spin_lock_irq(&cmd->t_state_lock);
1767        if (cmd->transport_state & CMD_T_LUN_STOP) {
1768                pr_debug("%s:%d CMD_T_LUN_STOP for ITT: 0x%08x\n",
1769                        __func__, __LINE__, cmd->se_tfo->get_task_tag(cmd));
1770
1771                cmd->transport_state &= ~CMD_T_ACTIVE;
1772                spin_unlock_irq(&cmd->t_state_lock);
1773                complete(&cmd->transport_lun_stop_comp);
1774                return;
1775        }
1776        /*
1777         * Determine if frontend context caller is requesting the stopping of
1778         * this command for frontend exceptions.
1779         */
1780        if (cmd->transport_state & CMD_T_STOP) {
1781                pr_debug("%s:%d CMD_T_STOP for ITT: 0x%08x\n",
1782                        __func__, __LINE__,
1783                        cmd->se_tfo->get_task_tag(cmd));
1784
1785                spin_unlock_irq(&cmd->t_state_lock);
1786                complete(&cmd->t_transport_stop_comp);
1787                return;
1788        }
1789
1790        cmd->t_state = TRANSPORT_PROCESSING;
1791        spin_unlock_irq(&cmd->t_state_lock);
1792
1793        if (dev->dev_task_attr_type != SAM_TASK_ATTR_EMULATED)
1794                goto execute;
1795
1796        /*
1797         * Check for the existence of HEAD_OF_QUEUE, and if true return 1
1798         * to allow the passed struct se_cmd list of tasks to the front of the list.
1799         */
1800        switch (cmd->sam_task_attr) {
1801        case MSG_HEAD_TAG:
1802                pr_debug("Added HEAD_OF_QUEUE for CDB: 0x%02x, "
1803                         "se_ordered_id: %u\n",
1804                         cmd->t_task_cdb[0], cmd->se_ordered_id);
1805                goto execute;
1806        case MSG_ORDERED_TAG:
1807                atomic_inc(&dev->dev_ordered_sync);
1808                smp_mb__after_atomic_inc();
1809
1810                pr_debug("Added ORDERED for CDB: 0x%02x to ordered list, "
1811                         " se_ordered_id: %u\n",
1812                         cmd->t_task_cdb[0], cmd->se_ordered_id);
1813
1814                /*
1815                 * Execute an ORDERED command if no other older commands
1816                 * exist that need to be completed first.
1817                 */
1818                if (!atomic_read(&dev->simple_cmds))
1819                        goto execute;
1820                break;
1821        default:
1822                /*
1823                 * For SIMPLE and UNTAGGED Task Attribute commands
1824                 */
1825                atomic_inc(&dev->simple_cmds);
1826                smp_mb__after_atomic_inc();
1827                break;
1828        }
1829
1830        if (atomic_read(&dev->dev_ordered_sync) != 0) {
1831                spin_lock(&dev->delayed_cmd_lock);
1832                list_add_tail(&cmd->se_delayed_node, &dev->delayed_cmd_list);
1833                spin_unlock(&dev->delayed_cmd_lock);
1834
1835                pr_debug("Added CDB: 0x%02x Task Attr: 0x%02x to"
1836                        " delayed CMD list, se_ordered_id: %u\n",
1837                        cmd->t_task_cdb[0], cmd->sam_task_attr,
1838                        cmd->se_ordered_id);
1839                return;
1840        }
1841
1842execute:
1843        /*
1844         * Otherwise, no ORDERED task attributes exist..
1845         */
1846        __target_execute_cmd(cmd);
1847}
1848EXPORT_SYMBOL(target_execute_cmd);
1849
1850/*
1851 * Process all commands up to the last received ORDERED task attribute which
1852 * requires another blocking boundary
1853 */
1854static void target_restart_delayed_cmds(struct se_device *dev)
1855{
1856        for (;;) {
1857                struct se_cmd *cmd;
1858
1859                spin_lock(&dev->delayed_cmd_lock);
1860                if (list_empty(&dev->delayed_cmd_list)) {
1861                        spin_unlock(&dev->delayed_cmd_lock);
1862                        break;
1863                }
1864
1865                cmd = list_entry(dev->delayed_cmd_list.next,
1866                                 struct se_cmd, se_delayed_node);
1867                list_del(&cmd->se_delayed_node);
1868                spin_unlock(&dev->delayed_cmd_lock);
1869
1870                __target_execute_cmd(cmd);
1871
1872                if (cmd->sam_task_attr == MSG_ORDERED_TAG)
1873                        break;
1874        }
1875}
1876
1877/*
1878 * Called from I/O completion to determine which dormant/delayed
1879 * and ordered cmds need to have their tasks added to the execution queue.
1880 */
1881static void transport_complete_task_attr(struct se_cmd *cmd)
1882{
1883        struct se_device *dev = cmd->se_dev;
1884
1885        if (cmd->sam_task_attr == MSG_SIMPLE_TAG) {
1886                atomic_dec(&dev->simple_cmds);
1887                smp_mb__after_atomic_dec();
1888                dev->dev_cur_ordered_id++;
1889                pr_debug("Incremented dev->dev_cur_ordered_id: %u for"
1890                        " SIMPLE: %u\n", dev->dev_cur_ordered_id,
1891                        cmd->se_ordered_id);
1892        } else if (cmd->sam_task_attr == MSG_HEAD_TAG) {
1893                dev->dev_cur_ordered_id++;
1894                pr_debug("Incremented dev_cur_ordered_id: %u for"
1895                        " HEAD_OF_QUEUE: %u\n", dev->dev_cur_ordered_id,
1896                        cmd->se_ordered_id);
1897        } else if (cmd->sam_task_attr == MSG_ORDERED_TAG) {
1898                atomic_dec(&dev->dev_ordered_sync);
1899                smp_mb__after_atomic_dec();
1900
1901                dev->dev_cur_ordered_id++;
1902                pr_debug("Incremented dev_cur_ordered_id: %u for ORDERED:"
1903                        " %u\n", dev->dev_cur_ordered_id, cmd->se_ordered_id);
1904        }
1905
1906        target_restart_delayed_cmds(dev);
1907}
1908
1909static void transport_complete_qf(struct se_cmd *cmd)
1910{
1911        int ret = 0;
1912
1913        if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1914                transport_complete_task_attr(cmd);
1915
1916        if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
1917                ret = cmd->se_tfo->queue_status(cmd);
1918                if (ret)
1919                        goto out;
1920        }
1921
1922        switch (cmd->data_direction) {
1923        case DMA_FROM_DEVICE:
1924                ret = cmd->se_tfo->queue_data_in(cmd);
1925                break;
1926        case DMA_TO_DEVICE:
1927                if (cmd->t_bidi_data_sg) {
1928                        ret = cmd->se_tfo->queue_data_in(cmd);
1929                        if (ret < 0)
1930                                break;
1931                }
1932                /* Fall through for DMA_TO_DEVICE */
1933        case DMA_NONE:
1934                ret = cmd->se_tfo->queue_status(cmd);
1935                break;
1936        default:
1937                break;
1938        }
1939
1940out:
1941        if (ret < 0) {
1942                transport_handle_queue_full(cmd, cmd->se_dev);
1943                return;
1944        }
1945        transport_lun_remove_cmd(cmd);
1946        transport_cmd_check_stop_to_fabric(cmd);
1947}
1948
1949static void transport_handle_queue_full(
1950        struct se_cmd *cmd,
1951        struct se_device *dev)
1952{
1953        spin_lock_irq(&dev->qf_cmd_lock);
1954        list_add_tail(&cmd->se_qf_node, &cmd->se_dev->qf_cmd_list);
1955        atomic_inc(&dev->dev_qf_count);
1956        smp_mb__after_atomic_inc();
1957        spin_unlock_irq(&cmd->se_dev->qf_cmd_lock);
1958
1959        schedule_work(&cmd->se_dev->qf_work_queue);
1960}
1961
1962static void target_complete_ok_work(struct work_struct *work)
1963{
1964        struct se_cmd *cmd = container_of(work, struct se_cmd, work);
1965        int ret;
1966
1967        /*
1968         * Check if we need to move delayed/dormant tasks from cmds on the
1969         * delayed execution list after a HEAD_OF_QUEUE or ORDERED Task
1970         * Attribute.
1971         */
1972        if (cmd->se_dev->dev_task_attr_type == SAM_TASK_ATTR_EMULATED)
1973                transport_complete_task_attr(cmd);
1974        /*
1975         * Check to schedule QUEUE_FULL work, or execute an existing
1976         * cmd->transport_qf_callback()
1977         */
1978        if (atomic_read(&cmd->se_dev->dev_qf_count) != 0)
1979                schedule_work(&cmd->se_dev->qf_work_queue);
1980
1981        /*
1982         * Check if we need to send a sense buffer from
1983         * the struct se_cmd in question.
1984         */
1985        if (cmd->se_cmd_flags & SCF_TRANSPORT_TASK_SENSE) {
1986                WARN_ON(!cmd->scsi_status);
1987                ret = transport_send_check_condition_and_sense(
1988                                        cmd, 0, 1);
1989                if (ret == -EAGAIN || ret == -ENOMEM)
1990                        goto queue_full;
1991
1992                transport_lun_remove_cmd(cmd);
1993                transport_cmd_check_stop_to_fabric(cmd);
1994                return;
1995        }
1996        /*
1997         * Check for a callback, used by amongst other things
1998         * XDWRITE_READ_10 emulation.
1999         */
2000        if (cmd->transport_complete_callback)
2001                cmd->transport_complete_callback(cmd);
2002
2003        switch (cmd->data_direction) {
2004        case DMA_FROM_DEVICE:
2005                spin_lock(&cmd->se_lun->lun_sep_lock);
2006                if (cmd->se_lun->lun_sep) {
2007                        cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
2008                                        cmd->data_length;
2009                }
2010                spin_unlock(&cmd->se_lun->lun_sep_lock);
2011
2012                ret = cmd->se_tfo->queue_data_in(cmd);
2013                if (ret == -EAGAIN || ret == -ENOMEM)
2014                        goto queue_full;
2015                break;
2016        case DMA_TO_DEVICE:
2017                spin_lock(&cmd->se_lun->lun_sep_lock);
2018                if (cmd->se_lun->lun_sep) {
2019                        cmd->se_lun->lun_sep->sep_stats.rx_data_octets +=
2020                                cmd->data_length;
2021                }
2022                spin_unlock(&cmd->se_lun->lun_sep_lock);
2023                /*
2024                 * Check if we need to send READ payload for BIDI-COMMAND
2025                 */
2026                if (cmd->t_bidi_data_sg) {
2027                        spin_lock(&cmd->se_lun->lun_sep_lock);
2028                        if (cmd->se_lun->lun_sep) {
2029                                cmd->se_lun->lun_sep->sep_stats.tx_data_octets +=
2030                                        cmd->data_length;
2031                        }
2032                        spin_unlock(&cmd->se_lun->lun_sep_lock);
2033                        ret = cmd->se_tfo->queue_data_in(cmd);
2034                        if (ret == -EAGAIN || ret == -ENOMEM)
2035                                goto queue_full;
2036                        break;
2037                }
2038                /* Fall through for DMA_TO_DEVICE */
2039        case DMA_NONE:
2040                ret = cmd->se_tfo->queue_status(cmd);
2041                if (ret == -EAGAIN || ret == -ENOMEM)
2042                        goto queue_full;
2043                break;
2044        default:
2045                break;
2046        }
2047
2048        transport_lun_remove_cmd(cmd);
2049        transport_cmd_check_stop_to_fabric(cmd);
2050        return;
2051
2052queue_full:
2053        pr_debug("Handling complete_ok QUEUE_FULL: se_cmd: %p,"
2054                " data_direction: %d\n", cmd, cmd->data_direction);
2055        cmd->t_state = TRANSPORT_COMPLETE_QF_OK;
2056        transport_handle_queue_full(cmd, cmd->se_dev);
2057}
2058
2059static inline void transport_free_sgl(struct scatterlist *sgl, int nents)
2060{
2061        struct scatterlist *sg;
2062        int count;
2063
2064        for_each_sg(sgl, sg, nents, count)
2065                __free_page(sg_page(sg));
2066
2067        kfree(sgl);
2068}
2069
2070static inline void transport_free_pages(struct se_cmd *cmd)
2071{
2072        if (cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC)
2073                return;
2074
2075        transport_free_sgl(cmd->t_data_sg, cmd->t_data_nents);
2076        cmd->t_data_sg = NULL;
2077        cmd->t_data_nents = 0;
2078
2079        transport_free_sgl(cmd->t_bidi_data_sg, cmd->t_bidi_data_nents);
2080        cmd->t_bidi_data_sg = NULL;
2081        cmd->t_bidi_data_nents = 0;
2082}
2083
2084/**
2085 * transport_release_cmd - free a command
2086 * @cmd:       command to free
2087 *
2088 * This routine unconditionally frees a command, and reference counting
2089 * or list removal must be done in the caller.
2090 */
2091static void transport_release_cmd(struct se_cmd *cmd)
2092{
2093        BUG_ON(!cmd->se_tfo);
2094
2095        if (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)
2096                core_tmr_release_req(cmd->se_tmr_req);
2097        if (cmd->t_task_cdb != cmd->__t_task_cdb)
2098                kfree(cmd->t_task_cdb);
2099        /*
2100         * If this cmd has been setup with target_get_sess_cmd(), drop
2101         * the kref and call ->release_cmd() in kref callback.
2102         */
2103         if (cmd->check_release != 0) {
2104                target_put_sess_cmd(cmd->se_sess, cmd);
2105                return;
2106        }
2107        cmd->se_tfo->release_cmd(cmd);
2108}
2109
2110/**
2111 * transport_put_cmd - release a reference to a command
2112 * @cmd:       command to release
2113 *
2114 * This routine releases our reference to the command and frees it if possible.
2115 */
2116static void transport_put_cmd(struct se_cmd *cmd)
2117{
2118        unsigned long flags;
2119
2120        spin_lock_irqsave(&cmd->t_state_lock, flags);
2121        if (atomic_read(&cmd->t_fe_count)) {
2122                if (!atomic_dec_and_test(&cmd->t_fe_count))
2123                        goto out_busy;
2124        }
2125
2126        if (cmd->transport_state & CMD_T_DEV_ACTIVE) {
2127                cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
2128                target_remove_from_state_list(cmd);
2129        }
2130        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2131
2132        transport_free_pages(cmd);
2133        transport_release_cmd(cmd);
2134        return;
2135out_busy:
2136        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2137}
2138
2139/*
2140 * transport_generic_map_mem_to_cmd - Use fabric-alloced pages instead of
2141 * allocating in the core.
2142 * @cmd:  Associated se_cmd descriptor
2143 * @mem:  SGL style memory for TCM WRITE / READ
2144 * @sg_mem_num: Number of SGL elements
2145 * @mem_bidi_in: SGL style memory for TCM BIDI READ
2146 * @sg_mem_bidi_num: Number of BIDI READ SGL elements
2147 *
2148 * Return: nonzero return cmd was rejected for -ENOMEM or inproper usage
2149 * of parameters.
2150 */
2151int transport_generic_map_mem_to_cmd(
2152        struct se_cmd *cmd,
2153        struct scatterlist *sgl,
2154        u32 sgl_count,
2155        struct scatterlist *sgl_bidi,
2156        u32 sgl_bidi_count)
2157{
2158        if (!sgl || !sgl_count)
2159                return 0;
2160
2161        /*
2162         * Reject SCSI data overflow with map_mem_to_cmd() as incoming
2163         * scatterlists already have been set to follow what the fabric
2164         * passes for the original expected data transfer length.
2165         */
2166        if (cmd->se_cmd_flags & SCF_OVERFLOW_BIT) {
2167                pr_warn("Rejecting SCSI DATA overflow for fabric using"
2168                        " SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC\n");
2169                cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2170                cmd->scsi_sense_reason = TCM_INVALID_CDB_FIELD;
2171                return -EINVAL;
2172        }
2173
2174        cmd->t_data_sg = sgl;
2175        cmd->t_data_nents = sgl_count;
2176
2177        if (sgl_bidi && sgl_bidi_count) {
2178                cmd->t_bidi_data_sg = sgl_bidi;
2179                cmd->t_bidi_data_nents = sgl_bidi_count;
2180        }
2181        cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
2182        return 0;
2183}
2184EXPORT_SYMBOL(transport_generic_map_mem_to_cmd);
2185
2186void *transport_kmap_data_sg(struct se_cmd *cmd)
2187{
2188        struct scatterlist *sg = cmd->t_data_sg;
2189        struct page **pages;
2190        int i;
2191
2192        /*
2193         * We need to take into account a possible offset here for fabrics like
2194         * tcm_loop who may be using a contig buffer from the SCSI midlayer for
2195         * control CDBs passed as SGLs via transport_generic_map_mem_to_cmd()
2196         */
2197        if (!cmd->t_data_nents)
2198                return NULL;
2199
2200        BUG_ON(!sg);
2201        if (cmd->t_data_nents == 1)
2202                return kmap(sg_page(sg)) + sg->offset;
2203
2204        /* >1 page. use vmap */
2205        pages = kmalloc(sizeof(*pages) * cmd->t_data_nents, GFP_KERNEL);
2206        if (!pages) {
2207                cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2208                return NULL;
2209        }
2210
2211        /* convert sg[] to pages[] */
2212        for_each_sg(cmd->t_data_sg, sg, cmd->t_data_nents, i) {
2213                pages[i] = sg_page(sg);
2214        }
2215
2216        cmd->t_data_vmap = vmap(pages, cmd->t_data_nents,  VM_MAP, PAGE_KERNEL);
2217        kfree(pages);
2218        if (!cmd->t_data_vmap) {
2219                cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2220                return NULL;
2221        }
2222
2223        return cmd->t_data_vmap + cmd->t_data_sg[0].offset;
2224}
2225EXPORT_SYMBOL(transport_kmap_data_sg);
2226
2227void transport_kunmap_data_sg(struct se_cmd *cmd)
2228{
2229        if (!cmd->t_data_nents) {
2230                return;
2231        } else if (cmd->t_data_nents == 1) {
2232                kunmap(sg_page(cmd->t_data_sg));
2233                return;
2234        }
2235
2236        vunmap(cmd->t_data_vmap);
2237        cmd->t_data_vmap = NULL;
2238}
2239EXPORT_SYMBOL(transport_kunmap_data_sg);
2240
2241static int
2242transport_generic_get_mem(struct se_cmd *cmd)
2243{
2244        u32 length = cmd->data_length;
2245        unsigned int nents;
2246        struct page *page;
2247        gfp_t zero_flag;
2248        int i = 0;
2249
2250        nents = DIV_ROUND_UP(length, PAGE_SIZE);
2251        cmd->t_data_sg = kmalloc(sizeof(struct scatterlist) * nents, GFP_KERNEL);
2252        if (!cmd->t_data_sg)
2253                return -ENOMEM;
2254
2255        cmd->t_data_nents = nents;
2256        sg_init_table(cmd->t_data_sg, nents);
2257
2258        zero_flag = cmd->se_cmd_flags & SCF_SCSI_DATA_CDB ? 0 : __GFP_ZERO;
2259
2260        while (length) {
2261                u32 page_len = min_t(u32, length, PAGE_SIZE);
2262                page = alloc_page(GFP_KERNEL | zero_flag);
2263                if (!page)
2264                        goto out;
2265
2266                sg_set_page(&cmd->t_data_sg[i], page, page_len, 0);
2267                length -= page_len;
2268                i++;
2269        }
2270        return 0;
2271
2272out:
2273        while (i > 0) {
2274                i--;
2275                __free_page(sg_page(&cmd->t_data_sg[i]));
2276        }
2277        kfree(cmd->t_data_sg);
2278        cmd->t_data_sg = NULL;
2279        return -ENOMEM;
2280}
2281
2282/*
2283 * Allocate any required resources to execute the command.  For writes we
2284 * might not have the payload yet, so notify the fabric via a call to
2285 * ->write_pending instead. Otherwise place it on the execution queue.
2286 */
2287int transport_generic_new_cmd(struct se_cmd *cmd)
2288{
2289        int ret = 0;
2290
2291        /*
2292         * Determine is the TCM fabric module has already allocated physical
2293         * memory, and is directly calling transport_generic_map_mem_to_cmd()
2294         * beforehand.
2295         */
2296        if (!(cmd->se_cmd_flags & SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC) &&
2297            cmd->data_length) {
2298                ret = transport_generic_get_mem(cmd);
2299                if (ret < 0)
2300                        goto out_fail;
2301        }
2302        /*
2303         * If this command doesn't have any payload and we don't have to call
2304         * into the fabric for data transfers, go ahead and complete it right
2305         * away.
2306         */
2307        if (!cmd->data_length &&
2308            cmd->t_task_cdb[0] != REQUEST_SENSE &&
2309            cmd->se_dev->transport->transport_type != TRANSPORT_PLUGIN_PHBA_PDEV) {
2310                spin_lock_irq(&cmd->t_state_lock);
2311                cmd->t_state = TRANSPORT_COMPLETE;
2312                cmd->transport_state |= CMD_T_ACTIVE;
2313                spin_unlock_irq(&cmd->t_state_lock);
2314
2315                INIT_WORK(&cmd->work, target_complete_ok_work);
2316                queue_work(target_completion_wq, &cmd->work);
2317                return 0;
2318        }
2319
2320        atomic_inc(&cmd->t_fe_count);
2321
2322        /*
2323         * If this command is not a write we can execute it right here,
2324         * for write buffers we need to notify the fabric driver first
2325         * and let it call back once the write buffers are ready.
2326         */
2327        target_add_to_state_list(cmd);
2328        if (cmd->data_direction != DMA_TO_DEVICE) {
2329                target_execute_cmd(cmd);
2330                return 0;
2331        }
2332
2333        spin_lock_irq(&cmd->t_state_lock);
2334        cmd->t_state = TRANSPORT_WRITE_PENDING;
2335        spin_unlock_irq(&cmd->t_state_lock);
2336
2337        transport_cmd_check_stop(cmd, false);
2338
2339        ret = cmd->se_tfo->write_pending(cmd);
2340        if (ret == -EAGAIN || ret == -ENOMEM)
2341                goto queue_full;
2342
2343        if (ret < 0)
2344                return ret;
2345        return 1;
2346
2347out_fail:
2348        cmd->se_cmd_flags |= SCF_SCSI_CDB_EXCEPTION;
2349        cmd->scsi_sense_reason = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
2350        return -EINVAL;
2351queue_full:
2352        pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n", cmd);
2353        cmd->t_state = TRANSPORT_COMPLETE_QF_WP;
2354        transport_handle_queue_full(cmd, cmd->se_dev);
2355        return 0;
2356}
2357EXPORT_SYMBOL(transport_generic_new_cmd);
2358
2359static void transport_write_pending_qf(struct se_cmd *cmd)
2360{
2361        int ret;
2362
2363        ret = cmd->se_tfo->write_pending(cmd);
2364        if (ret == -EAGAIN || ret == -ENOMEM) {
2365                pr_debug("Handling write_pending QUEUE__FULL: se_cmd: %p\n",
2366                         cmd);
2367                transport_handle_queue_full(cmd, cmd->se_dev);
2368        }
2369}
2370
2371void transport_generic_free_cmd(struct se_cmd *cmd, int wait_for_tasks)
2372{
2373        if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD)) {
2374                if (wait_for_tasks && (cmd->se_cmd_flags & SCF_SCSI_TMR_CDB))
2375                         transport_wait_for_tasks(cmd);
2376
2377                transport_release_cmd(cmd);
2378        } else {
2379                if (wait_for_tasks)
2380                        transport_wait_for_tasks(cmd);
2381
2382                core_dec_lacl_count(cmd->se_sess->se_node_acl, cmd);
2383
2384                if (cmd->se_lun)
2385                        transport_lun_remove_cmd(cmd);
2386
2387                transport_put_cmd(cmd);
2388        }
2389}
2390EXPORT_SYMBOL(transport_generic_free_cmd);
2391
2392/* target_get_sess_cmd - Add command to active ->sess_cmd_list
2393 * @se_sess:    session to reference
2394 * @se_cmd:     command descriptor to add
2395 * @ack_kref:   Signal that fabric will perform an ack target_put_sess_cmd()
2396 */
2397static int target_get_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd,
2398                               bool ack_kref)
2399{
2400        unsigned long flags;
2401        int ret = 0;
2402
2403        kref_init(&se_cmd->cmd_kref);
2404        /*
2405         * Add a second kref if the fabric caller is expecting to handle
2406         * fabric acknowledgement that requires two target_put_sess_cmd()
2407         * invocations before se_cmd descriptor release.
2408         */
2409        if (ack_kref == true) {
2410                kref_get(&se_cmd->cmd_kref);
2411                se_cmd->se_cmd_flags |= SCF_ACK_KREF;
2412        }
2413
2414        spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2415        if (se_sess->sess_tearing_down) {
2416                ret = -ESHUTDOWN;
2417                goto out;
2418        }
2419        list_add_tail(&se_cmd->se_cmd_list, &se_sess->sess_cmd_list);
2420        se_cmd->check_release = 1;
2421
2422out:
2423        spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2424        return ret;
2425}
2426
2427static void target_release_cmd_kref(struct kref *kref)
2428{
2429        struct se_cmd *se_cmd = container_of(kref, struct se_cmd, cmd_kref);
2430        struct se_session *se_sess = se_cmd->se_sess;
2431        unsigned long flags;
2432
2433        spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2434        if (list_empty(&se_cmd->se_cmd_list)) {
2435                spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2436                se_cmd->se_tfo->release_cmd(se_cmd);
2437                return;
2438        }
2439        if (se_sess->sess_tearing_down && se_cmd->cmd_wait_set) {
2440                spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2441                complete(&se_cmd->cmd_wait_comp);
2442                return;
2443        }
2444        list_del(&se_cmd->se_cmd_list);
2445        spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2446
2447        se_cmd->se_tfo->release_cmd(se_cmd);
2448}
2449
2450/* target_put_sess_cmd - Check for active I/O shutdown via kref_put
2451 * @se_sess:    session to reference
2452 * @se_cmd:     command descriptor to drop
2453 */
2454int target_put_sess_cmd(struct se_session *se_sess, struct se_cmd *se_cmd)
2455{
2456        return kref_put(&se_cmd->cmd_kref, target_release_cmd_kref);
2457}
2458EXPORT_SYMBOL(target_put_sess_cmd);
2459
2460/* target_sess_cmd_list_set_waiting - Flag all commands in
2461 *         sess_cmd_list to complete cmd_wait_comp.  Set
2462 *         sess_tearing_down so no more commands are queued.
2463 * @se_sess:    session to flag
2464 */
2465void target_sess_cmd_list_set_waiting(struct se_session *se_sess)
2466{
2467        struct se_cmd *se_cmd;
2468        unsigned long flags;
2469
2470        spin_lock_irqsave(&se_sess->sess_cmd_lock, flags);
2471
2472        WARN_ON(se_sess->sess_tearing_down);
2473        se_sess->sess_tearing_down = 1;
2474
2475        list_for_each_entry(se_cmd, &se_sess->sess_cmd_list, se_cmd_list)
2476                se_cmd->cmd_wait_set = 1;
2477
2478        spin_unlock_irqrestore(&se_sess->sess_cmd_lock, flags);
2479}
2480EXPORT_SYMBOL(target_sess_cmd_list_set_waiting);
2481
2482/* target_wait_for_sess_cmds - Wait for outstanding descriptors
2483 * @se_sess:    session to wait for active I/O
2484 * @wait_for_tasks:     Make extra transport_wait_for_tasks call
2485 */
2486void target_wait_for_sess_cmds(
2487        struct se_session *se_sess,
2488        int wait_for_tasks)
2489{
2490        struct se_cmd *se_cmd, *tmp_cmd;
2491        bool rc = false;
2492
2493        list_for_each_entry_safe(se_cmd, tmp_cmd,
2494                                &se_sess->sess_cmd_list, se_cmd_list) {
2495                list_del(&se_cmd->se_cmd_list);
2496
2497                pr_debug("Waiting for se_cmd: %p t_state: %d, fabric state:"
2498                        " %d\n", se_cmd, se_cmd->t_state,
2499                        se_cmd->se_tfo->get_cmd_state(se_cmd));
2500
2501                if (wait_for_tasks) {
2502                        pr_debug("Calling transport_wait_for_tasks se_cmd: %p t_state: %d,"
2503                                " fabric state: %d\n", se_cmd, se_cmd->t_state,
2504                                se_cmd->se_tfo->get_cmd_state(se_cmd));
2505
2506                        rc = transport_wait_for_tasks(se_cmd);
2507
2508                        pr_debug("After transport_wait_for_tasks se_cmd: %p t_state: %d,"
2509                                " fabric state: %d\n", se_cmd, se_cmd->t_state,
2510                                se_cmd->se_tfo->get_cmd_state(se_cmd));
2511                }
2512
2513                if (!rc) {
2514                        wait_for_completion(&se_cmd->cmd_wait_comp);
2515                        pr_debug("After cmd_wait_comp: se_cmd: %p t_state: %d"
2516                                " fabric state: %d\n", se_cmd, se_cmd->t_state,
2517                                se_cmd->se_tfo->get_cmd_state(se_cmd));
2518                }
2519
2520                se_cmd->se_tfo->release_cmd(se_cmd);
2521        }
2522}
2523EXPORT_SYMBOL(target_wait_for_sess_cmds);
2524
2525/*      transport_lun_wait_for_tasks():
2526 *
2527 *      Called from ConfigFS context to stop the passed struct se_cmd to allow
2528 *      an struct se_lun to be successfully shutdown.
2529 */
2530static int transport_lun_wait_for_tasks(struct se_cmd *cmd, struct se_lun *lun)
2531{
2532        unsigned long flags;
2533        int ret = 0;
2534
2535        /*
2536         * If the frontend has already requested this struct se_cmd to
2537         * be stopped, we can safely ignore this struct se_cmd.
2538         */
2539        spin_lock_irqsave(&cmd->t_state_lock, flags);
2540        if (cmd->transport_state & CMD_T_STOP) {
2541                cmd->transport_state &= ~CMD_T_LUN_STOP;
2542
2543                pr_debug("ConfigFS ITT[0x%08x] - CMD_T_STOP, skipping\n",
2544                         cmd->se_tfo->get_task_tag(cmd));
2545                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2546                transport_cmd_check_stop(cmd, false);
2547                return -EPERM;
2548        }
2549        cmd->transport_state |= CMD_T_LUN_FE_STOP;
2550        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2551
2552        // XXX: audit task_flags checks.
2553        spin_lock_irqsave(&cmd->t_state_lock, flags);
2554        if ((cmd->transport_state & CMD_T_BUSY) &&
2555            (cmd->transport_state & CMD_T_SENT)) {
2556                if (!target_stop_cmd(cmd, &flags))
2557                        ret++;
2558        }
2559        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2560
2561        pr_debug("ConfigFS: cmd: %p stop tasks ret:"
2562                        " %d\n", cmd, ret);
2563        if (!ret) {
2564                pr_debug("ConfigFS: ITT[0x%08x] - stopping cmd....\n",
2565                                cmd->se_tfo->get_task_tag(cmd));
2566                wait_for_completion(&cmd->transport_lun_stop_comp);
2567                pr_debug("ConfigFS: ITT[0x%08x] - stopped cmd....\n",
2568                                cmd->se_tfo->get_task_tag(cmd));
2569        }
2570
2571        return 0;
2572}
2573
2574static void __transport_clear_lun_from_sessions(struct se_lun *lun)
2575{
2576        struct se_cmd *cmd = NULL;
2577        unsigned long lun_flags, cmd_flags;
2578        /*
2579         * Do exception processing and return CHECK_CONDITION status to the
2580         * Initiator Port.
2581         */
2582        spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2583        while (!list_empty(&lun->lun_cmd_list)) {
2584                cmd = list_first_entry(&lun->lun_cmd_list,
2585                       struct se_cmd, se_lun_node);
2586                list_del_init(&cmd->se_lun_node);
2587
2588                spin_lock(&cmd->t_state_lock);
2589                pr_debug("SE_LUN[%d] - Setting cmd->transport"
2590                        "_lun_stop for  ITT: 0x%08x\n",
2591                        cmd->se_lun->unpacked_lun,
2592                        cmd->se_tfo->get_task_tag(cmd));
2593                cmd->transport_state |= CMD_T_LUN_STOP;
2594                spin_unlock(&cmd->t_state_lock);
2595
2596                spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
2597
2598                if (!cmd->se_lun) {
2599                        pr_err("ITT: 0x%08x, [i,t]_state: %u/%u\n",
2600                                cmd->se_tfo->get_task_tag(cmd),
2601                                cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
2602                        BUG();
2603                }
2604                /*
2605                 * If the Storage engine still owns the iscsi_cmd_t, determine
2606                 * and/or stop its context.
2607                 */
2608                pr_debug("SE_LUN[%d] - ITT: 0x%08x before transport"
2609                        "_lun_wait_for_tasks()\n", cmd->se_lun->unpacked_lun,
2610                        cmd->se_tfo->get_task_tag(cmd));
2611
2612                if (transport_lun_wait_for_tasks(cmd, cmd->se_lun) < 0) {
2613                        spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2614                        continue;
2615                }
2616
2617                pr_debug("SE_LUN[%d] - ITT: 0x%08x after transport_lun"
2618                        "_wait_for_tasks(): SUCCESS\n",
2619                        cmd->se_lun->unpacked_lun,
2620                        cmd->se_tfo->get_task_tag(cmd));
2621
2622                spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
2623                if (!(cmd->transport_state & CMD_T_DEV_ACTIVE)) {
2624                        spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2625                        goto check_cond;
2626                }
2627                cmd->transport_state &= ~CMD_T_DEV_ACTIVE;
2628                target_remove_from_state_list(cmd);
2629                spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2630
2631                /*
2632                 * The Storage engine stopped this struct se_cmd before it was
2633                 * send to the fabric frontend for delivery back to the
2634                 * Initiator Node.  Return this SCSI CDB back with an
2635                 * CHECK_CONDITION status.
2636                 */
2637check_cond:
2638                transport_send_check_condition_and_sense(cmd,
2639                                TCM_NON_EXISTENT_LUN, 0);
2640                /*
2641                 *  If the fabric frontend is waiting for this iscsi_cmd_t to
2642                 * be released, notify the waiting thread now that LU has
2643                 * finished accessing it.
2644                 */
2645                spin_lock_irqsave(&cmd->t_state_lock, cmd_flags);
2646                if (cmd->transport_state & CMD_T_LUN_FE_STOP) {
2647                        pr_debug("SE_LUN[%d] - Detected FE stop for"
2648                                " struct se_cmd: %p ITT: 0x%08x\n",
2649                                lun->unpacked_lun,
2650                                cmd, cmd->se_tfo->get_task_tag(cmd));
2651
2652                        spin_unlock_irqrestore(&cmd->t_state_lock,
2653                                        cmd_flags);
2654                        transport_cmd_check_stop(cmd, false);
2655                        complete(&cmd->transport_lun_fe_stop_comp);
2656                        spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2657                        continue;
2658                }
2659                pr_debug("SE_LUN[%d] - ITT: 0x%08x finished processing\n",
2660                        lun->unpacked_lun, cmd->se_tfo->get_task_tag(cmd));
2661
2662                spin_unlock_irqrestore(&cmd->t_state_lock, cmd_flags);
2663                spin_lock_irqsave(&lun->lun_cmd_lock, lun_flags);
2664        }
2665        spin_unlock_irqrestore(&lun->lun_cmd_lock, lun_flags);
2666}
2667
2668static int transport_clear_lun_thread(void *p)
2669{
2670        struct se_lun *lun = p;
2671
2672        __transport_clear_lun_from_sessions(lun);
2673        complete(&lun->lun_shutdown_comp);
2674
2675        return 0;
2676}
2677
2678int transport_clear_lun_from_sessions(struct se_lun *lun)
2679{
2680        struct task_struct *kt;
2681
2682        kt = kthread_run(transport_clear_lun_thread, lun,
2683                        "tcm_cl_%u", lun->unpacked_lun);
2684        if (IS_ERR(kt)) {
2685                pr_err("Unable to start clear_lun thread\n");
2686                return PTR_ERR(kt);
2687        }
2688        wait_for_completion(&lun->lun_shutdown_comp);
2689
2690        return 0;
2691}
2692
2693/**
2694 * transport_wait_for_tasks - wait for completion to occur
2695 * @cmd:        command to wait
2696 *
2697 * Called from frontend fabric context to wait for storage engine
2698 * to pause and/or release frontend generated struct se_cmd.
2699 */
2700bool transport_wait_for_tasks(struct se_cmd *cmd)
2701{
2702        unsigned long flags;
2703
2704        spin_lock_irqsave(&cmd->t_state_lock, flags);
2705        if (!(cmd->se_cmd_flags & SCF_SE_LUN_CMD) &&
2706            !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2707                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2708                return false;
2709        }
2710
2711        if (!(cmd->se_cmd_flags & SCF_SUPPORTED_SAM_OPCODE) &&
2712            !(cmd->se_cmd_flags & SCF_SCSI_TMR_CDB)) {
2713                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2714                return false;
2715        }
2716        /*
2717         * If we are already stopped due to an external event (ie: LUN shutdown)
2718         * sleep until the connection can have the passed struct se_cmd back.
2719         * The cmd->transport_lun_stopped_sem will be upped by
2720         * transport_clear_lun_from_sessions() once the ConfigFS context caller
2721         * has completed its operation on the struct se_cmd.
2722         */
2723        if (cmd->transport_state & CMD_T_LUN_STOP) {
2724                pr_debug("wait_for_tasks: Stopping"
2725                        " wait_for_completion(&cmd->t_tasktransport_lun_fe"
2726                        "_stop_comp); for ITT: 0x%08x\n",
2727                        cmd->se_tfo->get_task_tag(cmd));
2728                /*
2729                 * There is a special case for WRITES where a FE exception +
2730                 * LUN shutdown means ConfigFS context is still sleeping on
2731                 * transport_lun_stop_comp in transport_lun_wait_for_tasks().
2732                 * We go ahead and up transport_lun_stop_comp just to be sure
2733                 * here.
2734                 */
2735                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2736                complete(&cmd->transport_lun_stop_comp);
2737                wait_for_completion(&cmd->transport_lun_fe_stop_comp);
2738                spin_lock_irqsave(&cmd->t_state_lock, flags);
2739
2740                target_remove_from_state_list(cmd);
2741                /*
2742                 * At this point, the frontend who was the originator of this
2743                 * struct se_cmd, now owns the structure and can be released through
2744                 * normal means below.
2745                 */
2746                pr_debug("wait_for_tasks: Stopped"
2747                        " wait_for_completion(&cmd->t_tasktransport_lun_fe_"
2748                        "stop_comp); for ITT: 0x%08x\n",
2749                        cmd->se_tfo->get_task_tag(cmd));
2750
2751                cmd->transport_state &= ~CMD_T_LUN_STOP;
2752        }
2753
2754        if (!(cmd->transport_state & CMD_T_ACTIVE)) {
2755                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2756                return false;
2757        }
2758
2759        cmd->transport_state |= CMD_T_STOP;
2760
2761        pr_debug("wait_for_tasks: Stopping %p ITT: 0x%08x"
2762                " i_state: %d, t_state: %d, CMD_T_STOP\n",
2763                cmd, cmd->se_tfo->get_task_tag(cmd),
2764                cmd->se_tfo->get_cmd_state(cmd), cmd->t_state);
2765
2766        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2767
2768        wait_for_completion(&cmd->t_transport_stop_comp);
2769
2770        spin_lock_irqsave(&cmd->t_state_lock, flags);
2771        cmd->transport_state &= ~(CMD_T_ACTIVE | CMD_T_STOP);
2772
2773        pr_debug("wait_for_tasks: Stopped wait_for_compltion("
2774                "&cmd->t_transport_stop_comp) for ITT: 0x%08x\n",
2775                cmd->se_tfo->get_task_tag(cmd));
2776
2777        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2778
2779        return true;
2780}
2781EXPORT_SYMBOL(transport_wait_for_tasks);
2782
2783static int transport_get_sense_codes(
2784        struct se_cmd *cmd,
2785        u8 *asc,
2786        u8 *ascq)
2787{
2788        *asc = cmd->scsi_asc;
2789        *ascq = cmd->scsi_ascq;
2790
2791        return 0;
2792}
2793
2794static int transport_set_sense_codes(
2795        struct se_cmd *cmd,
2796        u8 asc,
2797        u8 ascq)
2798{
2799        cmd->scsi_asc = asc;
2800        cmd->scsi_ascq = ascq;
2801
2802        return 0;
2803}
2804
2805int transport_send_check_condition_and_sense(
2806        struct se_cmd *cmd,
2807        u8 reason,
2808        int from_transport)
2809{
2810        unsigned char *buffer = cmd->sense_buffer;
2811        unsigned long flags;
2812        int offset;
2813        u8 asc = 0, ascq = 0;
2814
2815        spin_lock_irqsave(&cmd->t_state_lock, flags);
2816        if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
2817                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2818                return 0;
2819        }
2820        cmd->se_cmd_flags |= SCF_SENT_CHECK_CONDITION;
2821        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
2822
2823        if (!reason && from_transport)
2824                goto after_reason;
2825
2826        if (!from_transport)
2827                cmd->se_cmd_flags |= SCF_EMULATED_TASK_SENSE;
2828        /*
2829         * Data Segment and SenseLength of the fabric response PDU.
2830         *
2831         * TRANSPORT_SENSE_BUFFER is now set to SCSI_SENSE_BUFFERSIZE
2832         * from include/scsi/scsi_cmnd.h
2833         */
2834        offset = cmd->se_tfo->set_fabric_sense_len(cmd,
2835                                TRANSPORT_SENSE_BUFFER);
2836        /*
2837         * Actual SENSE DATA, see SPC-3 7.23.2  SPC_SENSE_KEY_OFFSET uses
2838         * SENSE KEY values from include/scsi/scsi.h
2839         */
2840        switch (reason) {
2841        case TCM_NON_EXISTENT_LUN:
2842                /* CURRENT ERROR */
2843                buffer[offset] = 0x70;
2844                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2845                /* ILLEGAL REQUEST */
2846                buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2847                /* LOGICAL UNIT NOT SUPPORTED */
2848                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x25;
2849                break;
2850        case TCM_UNSUPPORTED_SCSI_OPCODE:
2851        case TCM_SECTOR_COUNT_TOO_MANY:
2852                /* CURRENT ERROR */
2853                buffer[offset] = 0x70;
2854                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2855                /* ILLEGAL REQUEST */
2856                buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2857                /* INVALID COMMAND OPERATION CODE */
2858                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x20;
2859                break;
2860        case TCM_UNKNOWN_MODE_PAGE:
2861                /* CURRENT ERROR */
2862                buffer[offset] = 0x70;
2863                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2864                /* ILLEGAL REQUEST */
2865                buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2866                /* INVALID FIELD IN CDB */
2867                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
2868                break;
2869        case TCM_CHECK_CONDITION_ABORT_CMD:
2870                /* CURRENT ERROR */
2871                buffer[offset] = 0x70;
2872                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2873                /* ABORTED COMMAND */
2874                buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2875                /* BUS DEVICE RESET FUNCTION OCCURRED */
2876                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x29;
2877                buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x03;
2878                break;
2879        case TCM_INCORRECT_AMOUNT_OF_DATA:
2880                /* CURRENT ERROR */
2881                buffer[offset] = 0x70;
2882                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2883                /* ABORTED COMMAND */
2884                buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2885                /* WRITE ERROR */
2886                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
2887                /* NOT ENOUGH UNSOLICITED DATA */
2888                buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0d;
2889                break;
2890        case TCM_INVALID_CDB_FIELD:
2891                /* CURRENT ERROR */
2892                buffer[offset] = 0x70;
2893                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2894                /* ILLEGAL REQUEST */
2895                buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2896                /* INVALID FIELD IN CDB */
2897                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x24;
2898                break;
2899        case TCM_INVALID_PARAMETER_LIST:
2900                /* CURRENT ERROR */
2901                buffer[offset] = 0x70;
2902                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2903                /* ILLEGAL REQUEST */
2904                buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2905                /* INVALID FIELD IN PARAMETER LIST */
2906                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x26;
2907                break;
2908        case TCM_UNEXPECTED_UNSOLICITED_DATA:
2909                /* CURRENT ERROR */
2910                buffer[offset] = 0x70;
2911                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2912                /* ABORTED COMMAND */
2913                buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2914                /* WRITE ERROR */
2915                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x0c;
2916                /* UNEXPECTED_UNSOLICITED_DATA */
2917                buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x0c;
2918                break;
2919        case TCM_SERVICE_CRC_ERROR:
2920                /* CURRENT ERROR */
2921                buffer[offset] = 0x70;
2922                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2923                /* ABORTED COMMAND */
2924                buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2925                /* PROTOCOL SERVICE CRC ERROR */
2926                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x47;
2927                /* N/A */
2928                buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x05;
2929                break;
2930        case TCM_SNACK_REJECTED:
2931                /* CURRENT ERROR */
2932                buffer[offset] = 0x70;
2933                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2934                /* ABORTED COMMAND */
2935                buffer[offset+SPC_SENSE_KEY_OFFSET] = ABORTED_COMMAND;
2936                /* READ ERROR */
2937                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x11;
2938                /* FAILED RETRANSMISSION REQUEST */
2939                buffer[offset+SPC_ASCQ_KEY_OFFSET] = 0x13;
2940                break;
2941        case TCM_WRITE_PROTECTED:
2942                /* CURRENT ERROR */
2943                buffer[offset] = 0x70;
2944                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2945                /* DATA PROTECT */
2946                buffer[offset+SPC_SENSE_KEY_OFFSET] = DATA_PROTECT;
2947                /* WRITE PROTECTED */
2948                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x27;
2949                break;
2950        case TCM_ADDRESS_OUT_OF_RANGE:
2951                /* CURRENT ERROR */
2952                buffer[offset] = 0x70;
2953                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2954                /* ILLEGAL REQUEST */
2955                buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2956                /* LOGICAL BLOCK ADDRESS OUT OF RANGE */
2957                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x21;
2958                break;
2959        case TCM_CHECK_CONDITION_UNIT_ATTENTION:
2960                /* CURRENT ERROR */
2961                buffer[offset] = 0x70;
2962                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2963                /* UNIT ATTENTION */
2964                buffer[offset+SPC_SENSE_KEY_OFFSET] = UNIT_ATTENTION;
2965                core_scsi3_ua_for_check_condition(cmd, &asc, &ascq);
2966                buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
2967                buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
2968                break;
2969        case TCM_CHECK_CONDITION_NOT_READY:
2970                /* CURRENT ERROR */
2971                buffer[offset] = 0x70;
2972                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2973                /* Not Ready */
2974                buffer[offset+SPC_SENSE_KEY_OFFSET] = NOT_READY;
2975                transport_get_sense_codes(cmd, &asc, &ascq);
2976                buffer[offset+SPC_ASC_KEY_OFFSET] = asc;
2977                buffer[offset+SPC_ASCQ_KEY_OFFSET] = ascq;
2978                break;
2979        case TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE:
2980        default:
2981                /* CURRENT ERROR */
2982                buffer[offset] = 0x70;
2983                buffer[offset+SPC_ADD_SENSE_LEN_OFFSET] = 10;
2984                /* ILLEGAL REQUEST */
2985                buffer[offset+SPC_SENSE_KEY_OFFSET] = ILLEGAL_REQUEST;
2986                /* LOGICAL UNIT COMMUNICATION FAILURE */
2987                buffer[offset+SPC_ASC_KEY_OFFSET] = 0x80;
2988                break;
2989        }
2990        /*
2991         * This code uses linux/include/scsi/scsi.h SAM status codes!
2992         */
2993        cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
2994        /*
2995         * Automatically padded, this value is encoded in the fabric's
2996         * data_length response PDU containing the SCSI defined sense data.
2997         */
2998        cmd->scsi_sense_length  = TRANSPORT_SENSE_BUFFER + offset;
2999
3000after_reason:
3001        return cmd->se_tfo->queue_status(cmd);
3002}
3003EXPORT_SYMBOL(transport_send_check_condition_and_sense);
3004
3005int transport_check_aborted_status(struct se_cmd *cmd, int send_status)
3006{
3007        int ret = 0;
3008
3009        if (cmd->transport_state & CMD_T_ABORTED) {
3010                if (!send_status ||
3011                     (cmd->se_cmd_flags & SCF_SENT_DELAYED_TAS))
3012                        return 1;
3013
3014                pr_debug("Sending delayed SAM_STAT_TASK_ABORTED"
3015                        " status for CDB: 0x%02x ITT: 0x%08x\n",
3016                        cmd->t_task_cdb[0],
3017                        cmd->se_tfo->get_task_tag(cmd));
3018
3019                cmd->se_cmd_flags |= SCF_SENT_DELAYED_TAS;
3020                cmd->se_tfo->queue_status(cmd);
3021                ret = 1;
3022        }
3023        return ret;
3024}
3025EXPORT_SYMBOL(transport_check_aborted_status);
3026
3027void transport_send_task_abort(struct se_cmd *cmd)
3028{
3029        unsigned long flags;
3030
3031        spin_lock_irqsave(&cmd->t_state_lock, flags);
3032        if (cmd->se_cmd_flags & SCF_SENT_CHECK_CONDITION) {
3033                spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3034                return;
3035        }
3036        spin_unlock_irqrestore(&cmd->t_state_lock, flags);
3037
3038        /*
3039         * If there are still expected incoming fabric WRITEs, we wait
3040         * until until they have completed before sending a TASK_ABORTED
3041         * response.  This response with TASK_ABORTED status will be
3042         * queued back to fabric module by transport_check_aborted_status().
3043         */
3044        if (cmd->data_direction == DMA_TO_DEVICE) {
3045                if (cmd->se_tfo->write_pending_status(cmd) != 0) {
3046                        cmd->transport_state |= CMD_T_ABORTED;
3047                        smp_mb__after_atomic_inc();
3048                }
3049        }
3050        cmd->scsi_status = SAM_STAT_TASK_ABORTED;
3051
3052        pr_debug("Setting SAM_STAT_TASK_ABORTED status for CDB: 0x%02x,"
3053                " ITT: 0x%08x\n", cmd->t_task_cdb[0],
3054                cmd->se_tfo->get_task_tag(cmd));
3055
3056        cmd->se_tfo->queue_status(cmd);
3057}
3058
3059static void target_tmr_work(struct work_struct *work)
3060{
3061        struct se_cmd *cmd = container_of(work, struct se_cmd, work);
3062        struct se_device *dev = cmd->se_dev;
3063        struct se_tmr_req *tmr = cmd->se_tmr_req;
3064        int ret;
3065
3066        switch (tmr->function) {
3067        case TMR_ABORT_TASK:
3068                core_tmr_abort_task(dev, tmr, cmd->se_sess);
3069                break;
3070        case TMR_ABORT_TASK_SET:
3071        case TMR_CLEAR_ACA:
3072        case TMR_CLEAR_TASK_SET:
3073                tmr->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
3074                break;
3075        case TMR_LUN_RESET:
3076                ret = core_tmr_lun_reset(dev, tmr, NULL, NULL);
3077                tmr->response = (!ret) ? TMR_FUNCTION_COMPLETE :
3078                                         TMR_FUNCTION_REJECTED;
3079                break;
3080        case TMR_TARGET_WARM_RESET:
3081                tmr->response = TMR_FUNCTION_REJECTED;
3082                break;
3083        case TMR_TARGET_COLD_RESET:
3084                tmr->response = TMR_FUNCTION_REJECTED;
3085                break;
3086        default:
3087                pr_err("Uknown TMR function: 0x%02x.\n",
3088                                tmr->function);
3089                tmr->response = TMR_FUNCTION_REJECTED;
3090                break;
3091        }
3092
3093        cmd->t_state = TRANSPORT_ISTATE_PROCESSING;
3094        cmd->se_tfo->queue_tm_rsp(cmd);
3095
3096        transport_cmd_check_stop_to_fabric(cmd);
3097}
3098
3099int transport_generic_handle_tmr(
3100        struct se_cmd *cmd)
3101{
3102        INIT_WORK(&cmd->work, target_tmr_work);
3103        queue_work(cmd->se_dev->tmr_wq, &cmd->work);
3104        return 0;
3105}
3106EXPORT_SYMBOL(transport_generic_handle_tmr);
3107
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.